Histograms and contrast

In this section, we are going to learn how to manipulate the contrast and histogram of images in MATLAB.

Intensity transformations

These transformations act over a unique pixel of the image, modifying its intensity value:

g = imadjust(f, [low_in high_in], [low_out high_out], gamma)

The intensity of the pixels is changed according to the plots below, which depend on the value of gamma. If gamma is ommited, it takes a default value of 1. If high_out is lower than low_out, the exit intensity will be inverted with respect to the original image.

Intensity transformations plots

For example, this:

g = imadjust(f, [0.5 0.75], [0 1])


Image adjustment example

Logaritmic transformations

It is also possible to make a logaritmic transformation:

g = c * log(1 + double(f))

where c is an arbitrary constant. This transformation compresses the dynamic range of an image, and its shape is similar to the gamma curve.

Since the result is going to be in a wide range, it is convenient to reduce it in the following way:

gs = im2uint8(mat2gray(g))

The command mat2gray() reduces the scale to values between [0, 1], and the command im2uint8() adapts them to a representation of [0, 255].

Logarithmic transformation example


Finally, the technique of Contrast-Stretching compresses the intensity values lower than m into darker values, and values larger than m into lighter values.

Constrast-Stretching plots

g = 1./(1 + (m./ (double(f) + eps) ).^E)

E controls the slope of the function and m is the mid-line where you want to switch from dark values to light values, eps is a MATLAB constant that represents the distance between 1.0 and the next largest number that can be represented in double-precision floating point. In this equation it is used to prevent division by zero in the event that the image has any zero valued pixels.

Rx image of a human body and its resulting constrast-stretching image

Histogram processing

To create the histogram of an image in MATLAB:

h = imhist(f,b)

where f is the image and b is the number of bins used to form the histogram. If b is not specified, 256 is used by default.

Image of a rose and its resulting histogram

Histogram equalizing

To equalize a histogram:

h = histeq(f,nlev)

where f is the image and nlev is the number of bins for the output image. If nlev is lower than the original number of levels of gray, histeq will try to distribute the levels so that you end up with a flat histogram. By default we choose 256.

Image of a group of pollen cells and its resulting histogram

The previous image, equalized, and its resulting equalized histogram

Local adaptations

To make a local adaptation of the histogram of an image:

g = histeq(f,hspec)

where f is the image and hspec is the histogram to which we want to adapt the histogram of our image.

Image of a satellite before and after applying the local adaptation to its darker side to make it brighter

You can practice these concepts using snippet02.