Convert RGB images to grayscale and control pixel data in python

I have an RGB image that I want to convert to a grayscale image so that I can have one number (maybe 0 to 1) for each pixel. This gives me a matrix that has dimensions equal to the pixel dimensions of the image. Then I want to do some manipulations on this matrix and generate a new grayscale image from this managed matrix. How can i do this?

+8
python image image-processing python-imaging-library
source share
1 answer

I often work with images as NumPy arrays - I do it like this:

import numpy as np from PIL import Image x=Image.open('im1.jpg','r') x=x.convert('L') #makes it greyscale y=np.asarray(x.getdata(),dtype=np.float64).reshape((x.size[1],x.size[0])) <manipulate matrix y...> y=np.asarray(y,dtype=np.uint8) #if values still in range 0-255! w=Image.fromarray(y,mode='L') w.save('out.jpg') 

If your y array values ​​are no longer in the 0-255 range after the manipulations, you can increase up to 16 TIFF bits or simply rescale.

-Aldo

+10
source share

All Articles