This article was originally published in issue 57 of The Crypt Mag
Gamma, represented by the Greek letter , can be described as the relationship between an input and the resulting output. For the scope of this article the input will be the RGB intensity values of an image.
The relationship in this case between the input and output is that the output is proportional to the input raised to the power of gamma. The formula for calculating the resulting output is as follows:
To illustrate, here are a few gamma curves:
Note that with a gamma of 1 the input equals the output producing a straight line.
For calculating gamma correction the input value is raised to the power of the inverse of gamma. The formula for this is as follows:
The following graph shows a comparison between the gamma curve and the gamma correction curve:
In pseudo-code performing gamma correction would go something like this:
gammaCorrection = 1 / gamma colour = GetPixelColour(x, y) newRed = 255 * (Red(colour) / 255) ^ gammaCorrection newGreen = 255 * (Green(colour) / 255) ^ gammaCorrection newBlue = 255 * (Blue(colour) / 255) ^ gammaCorrection PutPixelColour(x, y) = RGB(newRed, newGreen, newBlue)
The range of values used for gamma will depend on the application, but personally I tend to use a range of 0.01 to 7.99.
Here we have the ‘Lena’ and ‘Mandrill’ images which have had the gamma corrected using a gamma of 0.25 and 2.00:
There have been a few people that have had trouble getting this algorithm to work properly. The following tip has been provided by Felix in the comments below, but I have reiterated here:
The algorithm works great. A notice for those who code in static type languages, all variables used in the formula must be double type (even if they contain integers), and all integer constants (such as 255) must be written in double type (255.0).
Thanks for the tip Felix! 🙂
Article copyright © 2008, 2010 Francis G. Loch