Histogram equalization for contrast enhancement

A very common method of enhancing the contrast of an image is by transforming its pixel values so that its new histogram matches a predefined distribution. MATLAB offers a function for this process called as histeq. The function can also be called with one input, in which case it uses the default target histogram. Let's see what this function does, by writing the following script:

img = imread('my_image.bmp');
img_eq = histeq(img);
subplot(2,2,1),imshow(img),title('Original Image');
subplot(2,2,2),imshow(img_eq),title('Equalized Image');
subplot(2,2,3),imhist(img,64),title('Original Image Histogram');
subplot(2,2,4),imhist(img_eq,64),title('Equalized Image Histogram');

Saving this script as HistogramEqualization.m and typing it in the command line, leads to the following result:

As we can see, the contrast of the image is enhanced and the values are almost evenly spread throughout the range of possible values (0 to 255). This process usually has the effect of enhancing useful details, but also at the same time enhancing unwanted noise. Therefore, this approach should be used cautiously.