KeyError: ((1, 1, 1280), '|u1') while using PIL's Image.fromarray - PIL

為{幸葍}努か 提交于 2021-02-11 14:34:57

问题


I have this code:

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()

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:

Convert numpy.array object to PIL image object

However I don't get it nor know how to implement it.


回答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.

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')

Here you could see another solution: Convert numpy.array object to PIL image object

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

(add this before the img = Image.fromarray(img))




回答2:


I am not certain what you are trying to do but if you want the mean:

from PIL import Image
import numpy as np
img = Image.open('img.jpg')

# Make Numpy array
imgN = np.array(img)

mean = np.mean(imgN,axis=2)

# Revert back to PIL Image from Numpy array
result = Image.fromarray(mean)

Alternatively, if you want a greyscale which is an alternative to the mean

from PIL import Image
import numpy as np
img = Image.open('img.jpg').convert('L')


来源:https://stackoverflow.com/questions/57621092/keyerror-1-1-1280-u1-while-using-pils-image-fromarray-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!