8

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.

4
  • 1
    To clarify: If you have an array [True, False] then you want that to represent two pixels, one being black and the other white? Commented Apr 7, 2014 at 1:10
  • If the value is True - it means white pixel if it's False it's a black pixel. So each element corresponds to just one pixel. That's why I have just 2500 elements for each 50x50 image. Commented Apr 7, 2014 at 1:11
  • 1
    And you just have one numpy array of length 2500? In other words, it's a 2500x1 array and not a 50x50 array? Commented Apr 7, 2014 at 1:14
  • I have 50x50 array. 50 elements of 50 pixels - of which one element is one row. I can't seem to convert this into a simple 50x50 image. Commented Apr 7, 2014 at 1:16

1 Answer 1

15

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)
Sign up to request clarification or add additional context in comments.

13 Comments

This assumes that your array has 50 * 50 = 2500 elements. What is my_array.shape?
Oh I see, somehow your array is not a uniform array, but is a like an array of arrays. How do you create your array? What is my_array[0].dtype?
my_array[0].dtype shows Attribute Error: 'list' has no attribute dtype, I deleted one pair of outer parenthesis and I think it might have been causing some of the problems. But when I run your solution on this modified array I get: Value Error: only 2 non-keyword arguments accepted.
Is my_array.dtype now bool?
Oh, they are 0 and 1 and jpeg runs 0 to 255. Try multiplying the array by 255 :P
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.