DEV Community

Cover image for Discovering OpenCV with Python: Gamma correction

Discovering OpenCV with Python: Gamma correction

tinazhouhui profile image Tina ・2 min read

Another practical exercise that I had quite some fun with was gamma correction. This concept is mainly used when we want to adjust the brightness of an image. We could also use it to restore the faded pictures to their previous depth of colour. Since I am just a Python Padawan, we will be demonstrating this on grayscale pictures but I promise, the concept works on coloured images as well.

In this short article, I will focus on the restoration of faded pictures.

A bit of (mathematical) background

The logic behind is based on a concept called linear stretching. The faded picture simply means that the values of pixels are compressed to a smaller range and therefore not using the full range of values (in grayscale that would be from 0 to 255). For example, in the faded picture below, the values of the pixels range from 101 to 160. What linear stretching does, is that it re-scales the values to their full range from 0 to 255.

Here is the mathematical formula on how this can be achieved with each value:

Linear stretching

Python implementation

Just like in convolution, the necessary step is to cycle through every pixel and apply this mathematical formula to each of them. Be sure to check out my GitHub to see how it can be done.

And voila, below is the result, look closely at how the histogram of pixel values stretched out from the original narrow range:
Gamma correction
Tool used to create histogram

Hope you enjoyed the post, I recommend having a go at this and playing around with different images. Again, would appreciate if you let me know your thoughts. May the Python be with you.

Discussion (0)

Editor guide