How to Compute and Plot 2D Histograms of an Image in OpenCV Python?
Histograms are a very useful tool in image processing and analysis. They are used to visualize the distribution of pixel intensities in an image. In OpenCV Python, we can compute and plot 2D histograms of an image using the cv2.calcHist
and plt.hist2d
functions.
Prerequisites
Before we start, we need to have the following Python packages installed:
- OpenCV
- Matplotlib
You can install them using pip:
pip install opencv-python matplotlib
Computing 2D Histograms
The first step to computing a 2D histogram of an image is to load the image. We can do this using the cv2.imread
function:
import cv2
image = cv2.imread('image.png')
Next, we need to convert the image to grayscale, so that we have a single channel image. We can do this using the cv2.cvtColor
function:
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Now, we are ready to compute the 2D histogram. We can do this using the cv2.calcHist
function. The function takes the following arguments:
images
: a list of images (we have only one image, so we pass a list with a single element)channels
: a list of channels for which we want to compute the histogram (we have only one channel, so we pass a list with a single element)mask
: an optional mask that specifies which pixels to include in the histogramhistSize
: a list of integers that specifies the number of bins in each dimension of the histogramranges
: a list of floats that specifies the minimum and maximum values to be considered for each bin
For our grayscale image, we want to compute a histogram with 256 bins in the range [0, 256] (since the pixel values range from 0 to 255). We can do this as follows:
histogram = cv2.calcHist([gray_image], [0], None, [256], [0, 256])
The histogram
variable now contains the values of the 2D histogram.
Plotting 2D Histograms
To plot the 2D histogram, we can use the plt.hist2d
function. The function takes the following arguments:
x
: the x-coordinates of the centers of each biny
: the y-coordinates of the centers of each binbins
: the number of bins in each dimension of the histogramcmap
: the color map to use for the plotnorm
: the normalization for the color mapvmin
: the minimum value for the color mapvmax
: the maximum value for the color map
We can create the x and y coordinates for the bins using the np.meshgrid
function:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.meshgrid(np.arange(256), np.arange(256))
Now, we are ready to plot the 2D histogram:
plt.hist2d(x.ravel(), y.ravel(), bins=[256, 256], cmap='hot', norm=LogNorm(), data=histogram)
plt.colorbar()
plt.show()
The plt.colorbar()
function adds a color bar to the plot, showing the relationship between the color and the value of the histogram.
Putting It All Together
Here is the complete code to compute and plot a 2D histogram of an image in OpenCV Python:
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
image = cv2.imread('image.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
histogram = cv2.calcHist([gray_image], [0], None, [256], [0, 256])
x, y = np.meshgrid(np.arange(256), np.arange(256))
plt.hist2d(x.ravel(), y.ravel(), bins=[256, 256], cmap='hot', norm=LogNorm(), data=histogram)
plt.colorbar()
plt.show()
Conclusion
In this article, we have learned how to compute and plot 2D histograms of an image in OpenCV Python. We have seen how to use the cv2.calcHist
function to compute the histogram, and the plt.hist2d
function to plot it. We have also learned how to use color maps and color bars to make the plot more informative. With this knowledge, you can now analyze the pixel distribution of your images and gaininsights into their characteristics.