Image Processing Algorithms Part 5: Contrast Adjustment
This article was originally published in issue 56 of The Crypt Mag
Last time we looked at adjusting the brightness of an image. This time we are going to look at adjusting the contrast of an image which is a little bit more complex.
The first step is to calculate a contrast correction factor which is given by the following formula where the value C is the desired level of contrast:
The next step is to perform the actual contrast adjustment itself. The following formula shows the adjustment in contrast being made to the red component of a colour:
Translating the above formulas into pseudo-code would give something like this:
factor = (259 * (contrast + 255)) / (255 * (259 - contrast)) colour = GetPixelColour(x, y) newRed = Truncate(factor * (Red(colour) - 128) + 128) newGreen = Truncate(factor * (Green(colour) - 128) + 128) newBlue = Truncate(factor * (Blue(colour) - 128) + 128) PutPixelColour(x, y) = RGB(newRed, newGreen, newBlue)
The value of contrast will be in the range of -255 to +255. Negative values will decrease the amount of contrast and conversely positive values will increase the amount of contrast.
Here we have the ‘Lena’ and ‘Mandrill’ images which have had the contrast adjusted by -128 (decreased) and +128 (increased):
Article copyright © 2008, 2010 Francis G. Loch