问题描述
我有此代码:
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
有办法克服吗?
P.S.我搜索了,最相关的问题是:
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
)读取特定像素,图像的第一通道是 Height 第二个频道是 Width ,最后一个是频道数,这里是 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)
之前)
这篇关于KeyError:((1,1,1280),'| u1')在使用PIL的Image.fromarray-PIL时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!