如何在 Python 中将二进制数组编写为图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32105954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I write a binary array as an image in Python?
提问by interplex
I have an array of binary numbers in Python:
我在 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?
我想将这些数据取出并保存为位图,其中“0”对应白色,“1”对应黑色。我知道数组中有 2500 个数字,对应一个 50x50 的位图。我已经下载并安装了 PIL,但我不确定如何将其用于此目的。如何将此数组转换为相应的图像?
采纳答案by CT Zhu
回答by Back2Basics
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)
回答by ozgur
You can use Image.new
with 1
mode and put each integer as pixel in your initial image:
您可以使用Image.new
with1
模式并将每个整数作为像素放在初始图像中:
>>> 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')
回答by Shanid
Not for binary array
不适用于二进制数组
In case you have binary datain 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:
如果您有这种格式的二进制数据- b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00...
,那么您可以使用此方法将其写为图像文件:
with open("image_name.png", "wb") as img:
img.write(binary_data)