Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

python - Is there a way to use Pillows "Image.convert()" on an existing variable?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...