OpenCV Image Histogram
In image processing, a histogram is a very important tool that helps us understand the pixel distribution of an image.
By analyzing an image's histogram, we can perform image enhancement, contrast adjustment, image segmentation, and other operations.
What is an image histogram?
An image histogram is a graphical representation of the distribution of pixel intensities in an image. For a grayscale image, the histogram shows the frequency of each gray level (0 to 255) in the image. For a color image, we can compute the histogram of each channel (such as R, G, B) separately.
A histogram can help us understand information such as the brightness and contrast of an image. For example, if the histogram is concentrated in low gray-level regions, 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, with the horizontal axis showing pixel intensity values and the vertical axis showing the number of pixels with that intensity value.
-
Grayscale histogram: A histogram for grayscale images, showing the number of pixels at each gray level.
-
Color histogram: A histogram for color images, showing the pixel intensity distribution of each color channel (such as BGR) separately.
OpenCV provides a rich set of functions for histogram computation and manipulation:
| Function | function | Description |
|---|---|---|
| Computing the Histogram | cv2.calcHist() |
Compute the histogram of an image. |
| Histogram equalization | cv2.equalizeHist() |
Enhance the contrast of an image. |
| Histogram comparison | cv2.compareHist() |
Compare the similarity of two histograms. |
| Draw a histogram | matplotlib.pyplot.plot() |
Plot a histogram using Matplotlib. |
Histogram Computation Functions in OpenCV
In OpenCV, we can use the cv2.calcHist() function to compute 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 index of the channel for which to compute the histogram. For a grayscale image, use
[0]; for a color image, you can use[0]、[1]、[2]to compute the histograms of the blue, green, and red channels, respectively. - mask: The mask image. If a mask is specified, only pixels within the mask region are computed. If no mask is needed, you can pass in
None。 - histSize: The number of bins in the histogram. For a grayscale image, this is usually set to
[256], which divides the gray levels into 256 bins. - ranges: The range of pixel values. For a grayscale image, this is usually set to
[0, 256], indicating that the pixel value range is 0 to 255. - hist: The output histogram array.
- accumulate: Whether to accumulate the histogram. If set to
True, the histogram is not cleared but accumulated on each call.
Suppose we have a grayscale image img, we can use the following code to compute its histogram:
Example
import
cv2
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
Read an image
img
=
cv2.
imread
(
'image.jpg'
,
cv2.
IMREAD_GRAYSCALE
)
Computing the Histogram
hist
=
cv2.
calcHist
(
[
img
]
,
[
0
]
,
None
,
[
256
]
,
[
0
,
256
]
)
Draw a histogram
plt.
plot
(
hist
)
plt.
title
(
'Grayscale Histogram'
)
plt.
xlabel
(
'Pixel Value'
)
plt.
ylabel
(
'Frequency'
)
plt.
show
(
)
Histogram equalization
Histogram equalization is a method of enhancing image contrast by redistributing pixel intensity values to make the histogram more uniform.
Syntax:
equalized_image = cv2.equalizeHist(image)
Example
Histogram equalization
equalized_image
=
cv2.
equalizeHist
(
image
)
Display Results
cv2.
imshow
(
"Equalized Image"
,
equalized_image
)
cv2.
waitKey
(
0
)
cv2.
destroyAllWindows
(
)
Color Histogram
Compute a color histogram
For a color image, you can compute the histogram of each color channel separately.
Example
Read a color image
image
=
cv2.
imread
(
"path/to/image"
)
Compute the histograms of the BGR channels
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 a histogram
plt.
title
(
"Color Histogram"
)
plt.
xlabel
(
"Pixel Intensity"
)
plt.
ylabel
(
"Pixel Count"
)
plt.
show
(
)
Color Histogram Equalization
For a color image, histogram equalization can be performed on each channel separately.
Example
Split channels
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 Results
cv2.
imshow
(
"Equalized Color Image"
,
equalized_image
)
cv2.
waitKey
(
0
)
cv2.
destroyAllWindows
(
)
Histogram comparison
OpenCV provides the cv2.compareHist() function to compare the similarity of two histograms.
Syntax:
similarity = cv2.compareHist(hist1, hist2, method)
-
hist1: The first histogram. -
hist2: The second histogram. -
method: The comparison method, such ascv2.HISTCMP_CORREL(correlation comparison).
Example
Compute the histograms of two images
hist1
=
cv2.
calcHist
(
[
image1
]
,
[
0
]
,
None
,
[
256
]
,
[
0
,
256
]
)
hist2
=
cv2.
calcHist
(
[
image2
]
,
[
0
]
,
None
,
[
256
]
,
[
0
,
256
]
)
Compare the histograms
similarity
=
cv2.
compareHist
(
hist1
,
hist2
,
cv2.
HISTCMP_CORREL
)
(
"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 for image matching and retrieval.
- Color analysis: Through color histograms, the color distribution of an image can be analyzed for color correction and stylization.
The following is a complete histogram computation and equalization example code:
Example
import
cv2
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
Read a grayscale image
image
=
cv2.
imread
(
"path/to/image"
,
cv2.
IMREAD_GRAYSCALE
)
Compute the grayscale histogram
hist
=
cv2.
calcHist
(
[
image
]
,
[
0
]
,
None
,
[
256
]
,
[
0
,
256
]
)
Draw a 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 Results
cv2.
imshow
(
"Equalized Image"
,
equalized_image
)
cv2.
waitKey
(
0
)
cv2.
destroyAllWindows
(
)