How to write a binary array as an image in Python?

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 extract this data and save it as bitmap images, and β€œ0” is white and β€œ1” is black. I know that there are 2500 numbers in the array, which corresponds to a 50x50 bitmap. I downloaded and installed PIL, but I'm not sure how to use it for this purpose. How to convert this array to the corresponding image?

+8
python python-imaging-library
source share
3 answers

numpy and matplotlib way to do this:

 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
source share

You can use Image.new with 1 and put each integer as a pixel in the original 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

+13
source share
 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) 
+2
source share

All Articles