Visual Media Processing Using Matlab Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Calculating and displaying histograms with imhist

The histogram of an image is usually depicted as a bar graph and conveys information about the distribution of the pixel intensities in a predefined number of bins (ranges of intensities), spanning from the minimum to the maximum intensity. The information depicted in a histogram can provide a rough idea about how bright, or dark an image is. It can also give a first estimation of the optimal threshold for segmenting the pixels of an image into two or more distinct classes based on their intensities.

To calculate the histogram of an image, we may use the inherent MATLAB function imhist. This function outputs a one-dimensional matrix containing the distribution of the pixels in the input image in a set of bins (the default value for grayscale images is 256). The user can also give an extra input for different number of bins to be used. Let's see how this works for our previous example:

>> img = imread('my_image.bmp');
>> subplot (1,3,1),imshow(img),title('Original Image')
>> subplot (1,3,2),imhist(img),title('Histogram for 256 bins')
>> subplot (1,3,3),imhist(img,16),title('Histogram for 16 bins')

These previous commands yield to the following result:

This result gives us some insight of why the automatic threshold was estimated to be 99 in the previous step, as this threshold lies between two large distributions centered approximately at 44 and 125. We can also see what the result of the histogram for a reduced number of bins looks like, with a higher number of pixels in the y axis, since the numbers of 16 different bins have been summed into one.

The histogram is useful for a variety of reasons. Apart from being a useful tool for automatic threshold selection, it can also be applied for the enhancement of images, which is the next topic in line.