Converting an RGB image to grayscale and manipulating the pixel data in python
Question: I have an RGB image which I want to convert to a grayscale image, so that I
can have one number (maybe between 0 and 1) for each pixel. This gives me a
matrix which has the dimensions equal to that of the pixels of the image. Then
I want to do some manipulations on this matrix and generate a new grayscale
image from this manipulated matrix. How can I do this?


Answer: I frequently work with images as NumPy arrays - I do it like so:

    
    
    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 array values y are no longer in the range 0-255 after the
manipulations, you could step up to 16-bit TIFFs or simply rescale.

-Aldo

