Use OpenCV, Numpy to calculate histograms, and Matplot to plot and analyze histograms

This blog will show you how to calculate histograms using Python, OpenCV, Numpy functions, draw histograms using OpenCV and Matplotlib functions, and analyze histograms.

By viewing the histogram of an image, you can intuitively understand the contrast, brightness and intensity distribution of the image.

1. The rendering

The original picture is as follows:

Gray histogram effect is as follows:

You can see that the left area shows the number of darker pixels in the image and the right area shows the number of brighter pixels. As you can see from the histogram, there are not many dark areas, nor many light areas, and the number of intermediate tones (pixels in the middle range, such as around 170/210) is very high.

Histogram rendering of three BGR channels: The original graph VS Mask VS Mask image VS mixed histogram is as follows:In the fourth histogram, the blue line represents the histogram of the complete image and the red line represents the histogram of the masked area.

Principle 2.

The histogram can help to get a complete picture of the intensity distribution of the image. The most basic histogram is a grayscale image histogram, a graph with pixel values (ranging from 0 to 255) on the X-axis and the corresponding number of pixels in the image on the Y-axis.

There are 3 ways to compute a histogram:

  • Hist = cv2. CalcHist ([img], [0], None, [256], [0256])
  • Hist, bins = np. Histogram (img. Ravel (), 256, [0256])
  • np.bincount(img.ravel(),minlength=256)

The CV2 method is 40 times faster than THE NP. histogram;

Np. bincount is 10 times faster than NP. histogram, so cv2.calhist () method is preferred;

There are two ways to draw a histogram:

  • Matplot calculates the histogram and plots: plt.hist(img.ravel(),256,[0,256]); plt.show()
  • Histr = cv2.calchist ([img],[I],None,[256],[0 256]) plt.plot(histr,color = col) plt.xlim([0 256])

3. The source code

3.1 There are three calculation methods and two rendering methods for histogram

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('ml.jpg'.0)

# CV compute histogram
# cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
# -img: The image to compute the histogram
# -channels: Channel value. If the incoming gray scale graph is 0, the color graph [0][1][2] calculates THE BGR channel respectively
# -mask: calculates the histogram for the entire graph
# -histsize: The number of ranges in the X axis
# -ranges: ranges of values, usually [0,256]
hist = cv2.calcHist([img], [0].None[256], [0.256])

# numpy computes the histogram
# np.bincount() is approximately 10 times faster than np.histogram()
# cv2.calhist () is approximately 40 times faster than NP.histogram ()
hist, bins = np.histogram(img.ravel(), 256[0.256])
hist = np.bincount(img.ravel(), minlength=256)

Histogram method 1: matplot
img = cv2.imread('ml.jpg'.0)
plt.hist(img.ravel(), 256[0.256])
plt.show()

Histogram method 2: Matplot common plotting method
img = cv2.imread('ml.jpg')
color = ('b'.'g'.'r')
for i, col in enumerate(color):
    histr = cv2.calcHist([img], [i], None[256], [0.256])
    plt.plot(histr, color=col)
    plt.xlim([0.256])
plt.show()
Copy the code

3.2 Histogram of Mask image

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('ml.jpg'.0)

Construct a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300.100:400] = 255
masked_img = cv2.bitwise_and(img, img, mask=mask)

# Calculate the histogram of the entire graph and the histogram of the mask
hist_full = cv2.calcHist([img], [0].None[256], [0.256])
hist_mask = cv2.calcHist([img], [0], mask, [256], [0.256])

plt.subplot(221), plt.imshow(img, 'gray')
plt.subplot(222), plt.imshow(mask, 'gray')
plt.subplot(223), plt.imshow(masked_img, 'gray')
plt.subplot(224), plt.plot(hist_full, color='b'), plt.plot(hist_mask, color='r')
plt.xlim([0.256])

plt.show()
Copy the code

reference

  • Docs.opencv.org/3.0-beta/do…