将黑白数组转换为python中的图像?

时间:2021-04-14 00:23:43

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

我有一个50x50元素的数组,每个元素都是True或False - 这代表一个50x50的黑白图像。

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.

我已经看到PIL有一些功能,但它们只转换RGB像素列表,我有一个简单的黑白数组,没有其他通道。

1 个解决方案

#1


7  

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

首先,你应该使你的数组​​50x50而不是1d数组:

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

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

然后,要获得标准的8位图像,您应该使用无符号的8位整数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:

但你不希望真的是1,你希望它们是255:

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

Finally, you can convert to a PIL image:

最后,您可以转换为PIL图像:

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)

#1


7  

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

首先,你应该使你的数组​​50x50而不是1d数组:

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

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

然后,要获得标准的8位图像,您应该使用无符号的8位整数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:

但你不希望真的是1,你希望它们是255:

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

Finally, you can convert to a PIL image:

最后,您可以转换为PIL图像:

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)