从列表到np数组转换为JPEG时出错。

问题描述 投票:1回答:1

在我的代码中,我需要将一个图像转换为一个numpy数组,然后从数组转换为一个列表。在对列表进行一些修改后,我需要将其转换回图像,但我得到了这个错误信息

    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

我知道这个错误是由于从数组到列表再到数组的转换而发生的,但我不知道为什么。这里有一些代码产生了同样的错误,但没有对图像数据的内容进行任何修改,因为打印语句返回的是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")
python numpy python-imaging-library jpeg
1个回答
1
投票

很好的难题! 我一直在寻找两者之间的区别。ab 是,并发现numpy的 dtype 两者是不同的。

>>> print(a.dtype)
uint8
>>> print(b.dtype)
int64

如果你创建 b 用下面的方法,它又可以工作了。

b = np.asarray(lst, dtype=a.dtype)
© www.soinside.com 2019 - 2024. All rights reserved.