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
Asked
Active
Viewed 3.9k times
16
-
3possible duplicate of [Formula to determine brightness of RGB color](http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color) – Ignacio Vazquez-Abrams Jun 22 '11 at 15:08
-
2Duplicate 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?) – Chris Morgan Jun 22 '11 at 15:10
-
I'd suggest you to remove python from the title and from the tags, as this is not programming language specific – Vitor Jun 22 '11 at 15:11
-
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 calculations – Double AA Jun 22 '11 at 15:25
-
http://graphicdesign.stackexchange.com/a/29383 – Double AA Apr 13 '14 at 04:14
1 Answers
29
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))

Tom de Geus
- 5,625
- 2
- 33
- 77

Saúl Pilatowsky-Cameo
- 1,224
- 1
- 15
- 20
-
shouldn't pixelRGB = imag.getpixel((X,Y)) R,G,B = pixelRGB be (R,G,B) = imag.getpixel((X,Y)) – RobotHumans Feb 27 '17 at 22:04
-
-
1LuminanceC does not make sense to me. You should use the root of the sum of 0.299R², 0.587G² and 0.114B², right Saulpila? – Aiyion.Prime Jan 25 '18 at 12:40
-
1I guess so. That part was copied from the [reference](https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color) 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. – Saúl Pilatowsky-Cameo Feb 02 '18 at 05:43
-
5**Or just `.convert("L")`.** _When translating a color `image` to grayscale (mode “L”), the library uses the ITU-R 601-2 luma transform._ – Константин Ван Sep 29 '20 at 12:29