Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert black and white array into an image in python?

I have an array of 50x50 elements of which each is either True or False - this represents a 50x50 black and white image.

I can't convert this into image? I've tried countless different functions and none of them work.

import numpy as np
from PIL import Image

my_array = np.array([[True,False,False,False THE DATA IS IN THIS ARRAY OF 2500 elements]])

im = Image.fromarray(my_array)

im.save("results.jpg")

^ This one gives me: "Cannot handle this data type".

I've seen that PIL has some functions but they only convert a list of RGB pixels and I have a simple black and white array without the other channels.

like image 836
user3010273 Avatar asked Apr 07 '14 01:04

user3010273


People also ask

How do I convert an array to an image in Python?

The Approach to convert NumPy Array to an Image: Import numpy library and create 2D NumPy array using randint() method. Pass this array to the fromarray() method. This will return an image object. Save the image to the filesystem using the save() method.


1 Answers

First you should make your array 50x50 instead of a 1d array:

my_array = my_array.reshape((50, 50))

Then, to get a standard 8bit image, you should use an unsigned 8-bit integer dtype:

my_array = my_array.reshape((50, 50)).astype('uint8')

But you don't want the Trues to be 1, you want them to be 255:

my_array = my_array.reshape((50, 50)).astype('uint8')*255

Finally, you can convert to a PIL image:

im = Image.fromarray(my_array)

I'd do it all at once like this:

im = Image.fromarray(my_array.reshape((50,50)).astype('uint8')*255)
like image 154
askewchan Avatar answered Oct 19 '22 23:10

askewchan