Convert NumPy Array to PIL Image

I want to create a PIL image from a NumPy array. Here is my attempt:

# Create a NumPy array, which has four elements. The top-left should be pure red, the top-right should be pure blue, the bottom-left should be pure green, and the bottom-right should be yellow pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 0]]]) # Create a PIL image from the NumPy array image = Image.fromarray(pixels, 'RGB') # Print out the pixel values print image.getpixel((0, 0)) print image.getpixel((0, 1)) print image.getpixel((1, 0)) print image.getpixel((1, 1)) # Save the image image.save('image.png') 

However, the listing gives the following:

 (255, 0, 0) (0, 0, 0) (0, 0, 0) (0, 0, 0) 

And the saved image has a pure red color in the upper left corner, but all the other pixels are black. Why don't these other pixels retain the color that I assigned them in the NumPy array?

Thanks!

+5
source share
1 answer

RGB mode expects 8-bit values, so a simple array execution should fix the problem:

 In [25]: image = Image.fromarray(pixels.astype('uint8'), 'RGB') ...: ...: # Print out the pixel values ...: print image.getpixel((0, 0)) ...: print image.getpixel((0, 1)) ...: print image.getpixel((1, 0)) ...: print image.getpixel((1, 1)) ...: (255, 0, 0) (0, 0, 255) (0, 255, 0) (255, 255, 0) 
+10
source

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


All Articles