python -- measuring pixel brightness

Double AA picture Double AA · Jun 22, 2011 · Viewed 26.7k times · Source

How can I get a measure for a pixels brightness for a specific pixel in an image? I'm looking for an absolute scale for comparing different pixels' brightness. Thanks

Answer

Saulpila picture Saulpila · Jun 23, 2011

To get the pixel's RGB value you can use PIL:

from PIL import Image
from math import sqrt
imag = Image.open("yourimage.yourextension")
#Convert the image te RGB if it is a .gif for example
imag = imag.convert ('RGB')
#coordinates of the pixel
X,Y = 0,0
#Get RGB
pixelRGB = imag.getpixel((X,Y))
R,G,B = pixelRGB 

Then, brightness is simply a scale from black to white, witch can be extracted if you average the three RGB values:

brightness = sum([R,G,B])/3 ##0 is dark (black) and 255 is bright (white)

OR you can go deeper and use the Luminance formula that Ignacio Vazquez-Abrams commented about: ( Formula to determine brightness of RGB color )

#Standard
LuminanceA = (0.2126*R) + (0.7152*G) + (0.0722*B)
#Percieved A
LuminanceB = (0.299*R + 0.587*G + 0.114*B)
#Perceived B, slower to calculate
LuminanceC = sqrt(0.299*(R**2) + 0.587*(G**2) + 0.114*(B**2))