Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an RGB image to grayscale and manipulating the pixel data in python

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?

like image 408
lovespeed Avatar asked May 29 '14 14:05

lovespeed


People also ask

How do I convert RGB pixels to grayscale?

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.


1 Answers

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

like image 72
Aldo Avatar answered Oct 19 '22 01:10

Aldo