In my code I need to convert an image to a numpy array, then from an array to a list. After performing some changes to the list I need to convert back to an image but I get this error
Traceback (most recent call last):
File "/home/owner/anaconda3/envs/proj1/lib/python3.7/site-packages/PIL/Image.py", line 2714, in fromarray
mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 3), '<i8')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/owner/PycharmProjects/arrays3/test.py", line 31, in <module>
im = Image.fromarray(b)
File "/home/owner/anaconda3/envs/proj1/lib/python3.7/site-packages/PIL/Image.py", line 2716, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey)
TypeError: Cannot handle this data type: (1, 1, 3), <i8
I know that the error is occuring due to the transition from array to list and back but I'm not sure why. Here is some code that produces the same error but makes no modifications to the contents of the image data, as the print statement returns true.
im = Image.open("wp2793461-windows-98-wallpaper-pack.jpg")
a = np.asarray(im)
lst = a.tolist()
b = np.asarray(lst)
print(np.array_equal(a, b))
im = Image.fromarray(b)
im.save("new.jpg")
Nice conundrum! I was looking at what the differences between a
and b
are, and found that numpy's dtype
is different for both.
>>> print(a.dtype)
uint8
>>> print(b.dtype)
int64
If you create b
in the following way, it works again:
b = np.asarray(lst, dtype=a.dtype)