使用 PIL 的 Image.fromarray 时出现 KeyError: ((1, 1, 1280), '|u1') - PIL

2024-04-06

我有这个代码:

from PIL import Image
import numpy as np
img = Image.open('img.jpg')
Image.fromarray(np.array([[np.mean(i, axis=1).astype(int).tolist()]*len(i) for i in np.array(img).tolist()]).astype('uint8')).show()

我正在尝试修改 PIL 中图像的像素,但是当我运行它时,它会出现如下错误:

KeyError: ((1, 1, 1280), '|u1')

不仅如此,它还输出第二个错误,如下:

TypeError: Cannot handle this data type

有办法克服这个问题吗?

附:我搜索了一下,与我最相关的问题是:

将 numpy.array 对象转换为 PIL 图像对象 https://stackoverflow.com/questions/51479140/convert-numpy-array-object-to-pil-image-object

但是我不明白也不知道如何实现它。


用于通过任何图像库读取特定像素,例如PIL or OpenCV图像的第一个通道是Height第二个通道是Width最后一个是通道数这是3。当您将图像转换为灰度时,第三个通道将是1.

但是当你想使用将 numpy 数组转换为 PIL 图像时会发生此错误Image.fromarray但它显示以下错误:

KeyError: ((1, 1, 3062), '|u1')

在这里你可以看到另一种解决方案:将 numpy.array 对象转换为 PIL 图像对象 https://stackoverflow.com/questions/51479140/convert-numpy-array-object-to-pil-image-object

你的数据的形状。 枕头的fromarray函数只能处理 MxNx3 数组(RGB 图像)或 MxN 数组(灰度)。要使灰度图像正常工作,您必须将 MxNx1 数组转换为 MxN 数组。您可以使用np.reshape()功能。这会将数据展平,然后将其放入不同的数组形状中。

img = img.reshape(M, N) #let M and N be the dimensions of your image

(在之前添加此img = Image.fromarray(img))

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 PIL 的 Image.fromarray 时出现 KeyError: ((1, 1, 1280), '|u1') - PIL 的相关文章

随机推荐