How can I write a binary array as an image in Pyth

2019-06-16 03:30发布

I have an array of binary numbers in Python:

data = [0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1...]

I would like to take this data out and save it as a bitmap, with a '0' corresponding to white and a '1' corresponding to black. I know that there are 2500 numbers in the array, corresponding to a 50x50 bitmap. I've downloaded and installed PIL, but I'm not sure how to use it for this purpose. How can I convert this array into the corresponding image?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-16 03:53
import scipy.misc
import numpy as np
data = [1,0,1,0,1,0...]
data = np.array(data).reshape(50,50)
scipy.misc.imsave('outfile.bmp', data)
查看更多
我只想做你的唯一
3楼-- · 2019-06-16 03:58

The numpy and matplotlib way of doing it would be:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
plt.imsave('filename.png', np.array(data).reshape(50,50), cmap=cm.gray)

See this

查看更多
叛逆
4楼-- · 2019-06-16 03:59

You can use Image.new with 1 mode and put each integer as pixel in your initial image:

>>> from PIL import Image
>>> import random

>>> data = [random.choice((0, 1)) for _ in range(2500)]
>>> data[:] = [data[i:i + 50] for i in range(0, 2500, 50)]
>>> print data
[[0, 1, 0, 0, 1, ...], [0, 1, 1, 0, 1, ...], [1, 1, 0, 1, ...], ...]

>>> img = Image.new('1', (50, 50))
>>> pixels = img.load()

>>> for i in range(img.size[0]):
...    for j in range(img.size[1]):
...        pixels[i, j] = data[i][j]

>>> img.show()
>>> img.save('/tmp/image.bmp')

enter image description here

查看更多
再贱就再见
5楼-- · 2019-06-16 04:04

Not for binary array

In case you have binary data in this format - b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00..., then you may use this method to write it as an image file:

with open("image_name.png", "wb") as img:
    img.write(binary_data)
查看更多
登录 后发表回答