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:
In order for the algorithm to function correctly the value for the contrast correction factor (F) needs to be stored as a floating point number and not as an integer. The value C in the formula denotes 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 procedure Truncate() was previously mentioned in part 2 of this series and just ensures that the new values of red, green and blue are within the valid range of 0 to 255.
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, 2015 Francis G. Loch