Convert black and white array to image in python?

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

Can't I convert this to an image? I have 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 gives me: "Unable to process this data type."

I saw that PIL has some functions, but they only convert a list of RGB pixels, and I have a simple black and white array with no other channels.

+4
source share
1 answer

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

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

, 8- , unsigned 8-bit integer dtype:

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

, True 1, , 255:

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

, PIL:

im = Image.fromarray(my_array)

:

im = Image.fromarray(my_array.reshape((50,50)).astype('uint8')*255)
+6

Source: https://habr.com/ru/post/1535294/


All Articles