Histogram Equalization And Magic Behind It

C# tutorial on how to achieve histogram equalization on an image.


Andraz Krzisnik
Histogram Equalization And Magic Behind It

This tutorial is meant to demonstrate how histogram equalization works. This is a continuation on contrast stretch articles I’ve made in the past. An article on histogram equalization already exists on here, but it is made in “unsafe” code and that just kinda bothers me a little bit.

This article is accompanied by code, that manipulates bytes of an image with a “lockbits” method. This method basically stores image into a one dimensional byte array.

How does histogram equalization even work?

Histograms are charts to visualize data in columns.We can create a histogram from an image, where vertical axis shows us number of pixels and horizontal axis shows color intensities that these pixels have.

Images that need to be processed here will have a washed out look. This is because the range of intensities in this image doesn’t span the whole range of possible intensities. Histogram equalization basically stretches this range to cover complete spectrum of possible intensities.

Sounds familiar doesn’t it? We talked about the same effect in article for normalization, but the key difference here is that we use a different equation to achieve this effect. As it turns out normalization is not as effective in expanding the range as histogram equalization is.

Math behind this process

pn = number of pixels with intensity n / total number of pixels

pn represents the probability of each intensity in an image.

And finally the equation that does all the heavy lifting,

histogram equalization contrast stretch

where k represents intensity value and L all possible intensities.

For example, if we have a pixel with intensity value of 100, we need to sum all probabilities pn up to the probability for pixels with intensity value of 100. Then we need to multiply this summation by 255 and round it down to the closest integer value. Since we are working with images of 32 bit pixel format, the max intensity value for each channel is 255, hence the multiplication with this number.



Let’s take a look at the function written in C#

Demonstration

contrast stretch

Entire Project is Available for Download

Download Project
Show Comments (0)

Comments

Related Articles

C# Basics

C# Basics – Functions – Part 10

Functions We’ve been writing simple programs so far. But when things get more complicated, writing it all into one block of code could become hard to read. We can use functions...

Posted on by Andraz Krzisnik
C# Tutorial

C# Tutorial: How To Create An Image Negative

A negative image is a complete inversion of an image, we would say to be normal. In other words, dark areas will appear light, and light areas will become dark. More in detail, a...

Posted on by Andraz Krzisnik