Monday, November 27, 2023

OpenCV and Image Processing - Histogram for Grayscale Images

There are two ways to compute and display histograms. First, OpenCV provides cv2.calcHist() function to compute a histogram for an image, second, use matplotlib to plot the histogram diagram, matplotlib is a Python library for creating static, animated, and interactive visualizations.

Figure 7 shows the histogram of a real image. 

Figure 7

Look at a specific point, i.e the • point in the histogram plot at the right-side of Figure 7, it means there are about 1,200 pixels with color value of 50 in the leftside grayscale image.

This is how to read the histogram diagram which gives an overall idea of how the color value is distributed.

Here are the codes to produce the histogram in Figure 7:

1 # Get histogram using OpenCV

2 def show_histogram_gray(image):

3 hist = cv2.calcHist([image], [0], None, [256], [0, 256])

4 fig = plt.figure(figsize=(6, 4))

5 fig.suptitle('Histogram - using OpenCV', fontsize=18)

6 plt.plot(hist)

7 plt.show()

The second way to display a histogram is to use matplotlib, which provides plt.hist() function to generate a histogram plot, it does the exact same thing just looks a little bit differently, as Figure 8:


Here are the codes to produce the histogram in Figure 8-

9 # Alternative way for histogram using matplotlib

10 def show_histogram_gray_alt(image):

11 fig = plt.figure(figsize=(6, 4))

12 fig.suptitle('Histogram - using matplotlib',fontsize=18)

13 plt.hist(image.ravel(), 256, [0, 256])

14 plt.show()

Explanations:

Line 1 - 7 Use OpenCV cv2.calchist to generate a histogram.

Line 3 Call cv2.calcHist() function, pass the image as the parameter.

Line 4 - 6 Create a plot using matplotlib, specify the plot size, set the title, and plot the histogram created in line 3.

Line 7 Show the plot

Line 10 - 14 Alternatively, use matplotlib function to generate a histogram.

Line 11 -12 Create a plot using matplotlib, specify the plot size, set the title.

Line 13 Call plt.hist() function to create a histogram of the image.

Share:

0 comments:

Post a Comment