0

I am new to PIL, so i was playing around with the functions:

from PIL import Image
import numpy as np
image_array = np.array([   
    [[0, 0, 0],
    [255, 255, 255],
    [0, 0, 0]],
    [[255, 255, 255],
    [0, 0, 0],
    [255, 255, 255]],
    [[0, 0, 0],
    [255, 255, 255],
    [0, 0, 0]]])
image = Image.fromarray(image_array)
image.show()

However, when i want to use it, it gives me the following error in the 13th line: TypeError Cannot handle this data type: (1, 1, 3), <i8 But surprisingly, it doesn't give me an error when i use image_array = np.array(Image.open('Image.png')) which is the exact same image with the exact same array: Image.png (The image is very small, 3 by 3 pixels)

Nobody else seems to have the same problem, or maybe i'm just missing something

adam_Barfi
  • 45
  • 4

2 Answers2

2

Try this with a datatype conversion or define the array with dtype=np.unit8 parameter to begin with.

A relevant answer (different question) can be found here as well. -

img = Image.fromarray(image_array.astype(np.uint8)) #<---
img.width, img.height
(3,3)

Or, simply use np.array([[],[],[]], dtype=np.uint8) to begin with, if memory is an issue.

Further more, if you want to build an array as int64, just use copy=False to return the original array instead of a copy, before you hand it over to PIL.

image_array.astype(np.unit8, copy=False)
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • Why not just create the array with that `dtype` from the start, rather than create it incorrectly then change it? – Mark Setchell Jan 01 '22 at 18:56
  • That's not the point of my answer. Its to point out that a datatype conversion is needed. It's up to OP to decide whether they want to do that dtype specified during the definition of the array. Moreover, they may want to work with the defined array before pushing it to PIL. – Akshay Sehgal Jan 01 '22 at 18:58
1

When you create your image array with:

image_array = np.array([   
[[0, 0, 0],
[255, 255, 255],
[0, 0, 0]],
[[255, 255, 255],
[0, 0, 0],
[255, 255, 255]],
[[0, 0, 0],
[255, 255, 255],
[0, 0, 0]]])

It will be int64, rather than np.uint8. You can check that with:

print(image_array.dtype)

so it will take 8 times more RAM than necessary. Rather than create something unnecessarily large and then correct it by creating yet another version now requiring 9 times the RAM, I suggest you create it with the correct type in the first place. So, use:

image_array = np.array([   
[[0, 0, 0],
[255, 255, 255],
[0, 0, 0]],
[[255, 255, 255],
[0, 0, 0],
[255, 255, 255]],
[[0, 0, 0],
[255, 255, 255],
[0, 0, 0]]], dtype=np.uint8)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432