python -- measuring pixel brightness
Asked Answered
W

1

17

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

Willwilla answered 22/6, 2011 at 15:7 Comment(5)
possible duplicate of Formula to determine brightness of RGB colorFederico
Duplicate is assuming that it's only that part that you're wanting help with - the "python" labelling is entirely irrelevant in that case as you don't care about the code, just the scale. If you do care about the Python aspect, more information is needed (PIL, PyQt4, Something Else?)Contra
I'd suggest you to remove python from the title and from the tags, as this is not programming language specificOscaroscillate
I was looking for a way to do this in python preferably with a single function from pil or even elsewhere. I was looking to avoid excessive manual calculationsWillwilla
graphicdesign.stackexchange.com/a/29383Willwilla
T
30

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))
Tuscany answered 23/6, 2011 at 4:35 Comment(5)
shouldn't pixelRGB = imag.getpixel((X,Y)) R,G,B = pixelRGB be (R,G,B) = imag.getpixel((X,Y))Ette
How would you get the alpha component though?Permeability
LuminanceC does not make sense to me. You should use the root of the sum of 0.299R², 0.587G² and 0.114B², right Saulpila?Remote
I guess so. That part was copied from the reference on top of that block. It was apparently corrected there. I'll edit it in. Still, note this answer is almost seven years old. There are maybe better methods out there now.Tremolo
Or just .convert("L"). When translating a color image to grayscale (mode “L”), the library uses the ITU-R 601-2 luma transform.Hemiterpene

© 2022 - 2024 — McMap. All rights reserved.