Is there a way to use Pillows “Image.convert()” on an existing variable?

假如想象 提交于 2020-01-25 03:57:05

问题


Hello,

maybe this question looks stupid, but I try to use Pillows Image.convert() to convert an image to grayscale. This image I have stored in a variable img because I already pre-processed it, but not with Pillow (type: numpy.ndarray). So I type:

img = Image.convert('LA')

But it does not seem to work, as it says:

AttributeError: module 'PIL.Image' has no attribute 'convert'

If I type img = Image.open("picture.jpg").convert('LA') it works, but I want to use it on a variable that already exists. I also do not want to save the preprocessed image just to open and convert it with the previous command because this is even more inefficient (in terms of speed and CPU-power). So: Is there a proper way to do this?

Thanks for the help in advance!


回答1:


Whilst you could perfectly well convert your Numpy array to a PIL Image and then convert that to greyscale and then convert back to a Numpy array like this:

PILImage = Image.fromarray(Numpyimg)
PILgrey  = PILImage.convert('L')
Numpygrey= np.array(PILgrey)

You might as well just do the ITU-R 601-2 luma transform yourself, i.e.

L = 0.299 * Red + 0.587 * Green + 0.114 * Blue

So, you would get:

Numpygrey = np.dot(Numpyimg[...,:3], [0.299, 0.587, 0.114]).astype(np.uint8)



回答2:


You can use

img = Image.fromarray(img)

to convert to a PIL Image type. From there, you should be able to use PIL's convert() function

img = img.convert('LA')

then, to access the pixel values directly you can either convert back to a numpy array

img_array = np.asarray(img)

or get pixel access to the PIL Image using

pixels = img.load()


来源:https://stackoverflow.com/questions/58526520/is-there-a-way-to-use-pillows-image-convert-on-an-existing-variable

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