问题描述
我有这个代码:
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 中图像的像素,但是当我运行它时,它给出如下错误:
And I am trying to modify the pixels of the image in PIL, however when I run it it gives an error as follows:
KeyError: ((1, 1, 1280), '|u1')
不仅如此,它还输出第二个错误如下:
Not just that, it also outputs a second error as follows:
TypeError: Cannot handle this data type
有没有办法克服这个问题?
Is there a way to overcome this?
附言我搜索过,与我最相关的问题是:
P.S. I searched and the most related question to mine was:
但是我不明白,也不知道如何实现它.
However I don't get it nor know how to implement it.
推荐答案
对于通过任何图像库(例如 PIL
或 OpenCV
)读取特定像素,图像的第一个通道是 高度第二个通道是宽度,最后一个是通道数,这里是3
.当您将图像转换为灰度时,第三个通道将为 1
.
For reading specific pixel via any image library such as PIL
or OpenCV
first channel of image is Height second channel is Width and last one is number of channels and here is 3
. When you convert image to gray scale, third channel will be 1
.
但是当您想使用 Image.fromarray
将 numpy 数组转换为 PIL 图像时会发生此错误,但它显示以下错误:
But this error happen when you want to convert a numpy array to PIL image using Image.fromarray
but it shows the following error:
KeyError: ((1, 1, 3062), '|u1')
在这里您可以看到另一种解决方案:将 numpy.array 对象转换为 PIL 图像对象
Here you could see another solution:Convert numpy.array object to PIL image object
数据的形状.Pillow 的 fromarray
函数只能做一个 MxNx3 数组(RGB 图像),或者一个 MxN 数组(灰度).要使灰度图像工作,您必须将 MxNx1 数组转换为 MxN 数组.您可以使用 np.reshape()
函数来完成此操作.这会将数据展平,然后将其放入不同的数组形状.
the shape of your data.Pillow's fromarray
function can only do a MxNx3 array (RGB image), or an MxN array (grayscale). To make the grayscale image work, you have to turn you MxNx1 array into a MxN array. You can do this by using the np.reshape()
function. This will flatten out the data and then put it into a different array shape.
img = img.reshape(M, N) #let M and N be the dimensions of your image
(在 img = Image.fromarray(img)
之前添加这个)
(add this before the img = Image.fromarray(img)
)
这篇关于KeyError: ((1, 1, 1280), '|u1') 同时使用 PIL's Image.fromarray - PIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!