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
CodePudding user response:
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)
CodePudding user response:
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)