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?
RGB images are converted to grayscale using the formula gray=(red+green+blue)/3 or gray=0.299red+0.587green+0.114blue if "Weighted RGB to Grayscale Conversion" is checked in Edit>Options>Conversions.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With