OpenCV Image Histogram
In image processing, the histogram is a very important tool that can help us understand the pixel distribution of an image.
By analyzing the image histogram, we can perform operations such as image enhancement, contrast adjustment, and image segmentation.
What is an image histogram?
An image histogram is a graphical representation of the pixel intensity distribution of an image. For grayscale images, the histogram shows the frequency of each gray level (0 to 255) appearing in the image. For color images, we can calculate the histogram for each channel (such as R, G, B) separately.
The histogram can help us understand information such as the brightness and contrast of an image. For example, if the histogram is concentrated in the low gray level region, the image is dark; if the histogram is evenly distributed, the image has good contrast.
Histogram:Represents the distribution of pixel intensities in an image. The horizontal axis represents pixel intensity values, and the vertical axis represents the number of pixels with that intensity value.
Grayscale histogram:A histogram for grayscale images, representing the number of pixels at each gray level.
Color histogram:A histogram for color images, representing the pixel intensity distribution of each color channel (such as BGR) separately.
OpenCV provides a rich set of histogram calculation and manipulation functions:
| Feature | Function | Description |
|---|---|---|
| Calculate histogram | cv2.calcHist() | Calculate the histogram of an image. |
| Histogram equalization | cv2.equalizeHist() | Enhance image contrast. |
| Histogram comparison | cv2.compareHist() | Compare the similarity of two histograms. |
| Draw histogram | matplotlib.pyplot.plot() | Use Matplotlib to draw histograms. |
Histogram calculation functions in OpenCV
In OpenCV, we can usecv2.calcHist()function to calculate the histogram of an image.
cv2.calcHist()Function syntax
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
Parameter description
- images: The list of input images, usually a list containing single-channel or multi-channel images. For example
[img]。 - channels: The channel index for which the histogram needs to be calculated. For grayscale images, use
[0]; for color images, you can use[0]、[1]、[2]to calculate the histograms of the blue, green, and red channels respectively. - mask: Mask image. If a mask is specified, only pixels within the mask area are calculated. If no mask is needed, you can pass in
None。 - histSize: The number of bins in the histogram. For grayscale images, it is usually set to
[256], indicating that the gray levels are divided into 256 bins. - ranges: The range of pixel values. For grayscale images, it is usually set to
[0, 256], indicating that the range of pixel values is 0 to 255. - hist: The output histogram array.
- accumulate: Whether to accumulate the histogram. If set to
True, the histogram will not be cleared, but will accumulate on each call.
Suppose we have a grayscale imageimg, we can use the following code to calculate its histogram:
Example
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# Calculate histogram
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
# Draw histogram
plt.plot(hist)
plt.title('Grayscale Histogram')
plt.xlabel('Pixel Value')
plt.ylabel('Frequency')
plt.show()
Histogram equalization
Histogram equalization is a method for enhancing image contrast by redistributing pixel intensity values to make the histogram more uniform.
Syntax:
equalized_image = cv2.equalizeHist(image)
Example
equalized_image = cv2.equalizeHist(image)
# Display result
cv2.imshow("Equalized Image", equalized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Color histogram
Calculate color histogram
For color images, the histogram of each color channel can be calculated separately.
Example
image = cv2.imread("path/to/image")
# Calculate the histogram of each BGR channel
colors = ('b', 'g', 'r')
for i, color in enumerate(colors):
hist = cv2.calcHist([image], [i], None, [256], [0, 256])
plt.plot(hist, color=color)
# Draw histogram
plt.title("Color Histogram")
plt.xlabel("Pixel Intensity")
plt.ylabel("Pixel Count")
plt.show()
Color histogram equalization
For color images, histogram equalization can be applied to each channel separately.
Example
b, g, r = cv2.split(image)
# Perform histogram equalization on each channel
b_eq = cv2.equalizeHist(b)
g_eq = cv2.equalizeHist(g)
r_eq = cv2.equalizeHist(r)
# Merge channels
equalized_image = cv2.merge([b_eq, g_eq, r_eq])
# Display result
cv2.imshow("Equalized Color Image", equalized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Histogram comparison
OpenCV provides the cv2.compareHist() function for comparing the similarity of two histograms.
Syntax:
similarity = cv2.compareHist(hist1, hist2, method)
hist1: The first histogram.hist2: The second histogram.method: Comparison method, for examplecv2.HISTCMP_CORREL(correlation comparison).
Example
hist1 = cv2.calcHist([image1], [0], None, [256], [0, 256])
hist2 = cv2.calcHist([image2], [0], None, [256], [0, 256])
# Compare histograms
similarity = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
print("Histogram Similarity:", similarity)
Applications of histograms
- Image enhancement: Through histogram equalization, the contrast of an image can be enhanced, making details clearer.
- Image segmentation: By analyzing the histogram, a threshold can be determined for image segmentation.
- Image matching: By comparing histograms, the similarity of two images can be determined, which is used for image matching and retrieval.
- Color analysis: Through color histograms, the color distribution of an image can be analyzed for color correction and stylization processing.
The following is a complete example code for histogram calculation and equalization:
Example
import numpy as np
import matplotlib.pyplot as plt
# Read grayscale image
image = cv2.imread("path/to/image", cv2.IMREAD_GRAYSCALE)
# Calculate grayscale histogram
hist = cv2.calcHist([image], [0], None, [256], [0, 256])
# Draw histogram
plt.plot(hist)
plt.title("Grayscale Histogram")
plt.xlabel("Pixel Intensity")
plt.ylabel("Pixel Count")
plt.show()
# Histogram equalization
equalized_image = cv2.equalizeHist(image)
# Display result
cv2.imshow("Equalized Image", equalized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()