【问题标题】:Error when converting from list to np array to JPEG从列表转换为 np 数组到 JPEG 时出错
【发布时间】:2020-05-21 15:53:11
【问题描述】:

在我的代码中,我需要将图像转换为 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

我知道错误是由于从数组到列表再返回而发生的,但我不知道为什么。这是一些产生相同错误但不修改图像数据内容的代码,因为 print 语句返回 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】:

    好难题!我正在查看ab 之间的区别是什么,发现numpy 的dtype 对两者都不同。

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

    如果你按以下方式创建b,它会再次起作用:

    b = np.asarray(lst, dtype=a.dtype)
    

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 2020-10-18
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2016-04-05
      • 1970-01-01
      • 2018-05-04
      相关资源
      最近更新 更多