OpenCV Python 如何计算和绘制图像的2D直方图
我们可以使用 cv2.calcHist() 函数来计算图像的2D直方图。彩色图像有三个通道-红色、绿色和蓝色。我们可以同时计算两个颜色通道的2D直方图。因此,我们有三种颜色通道取两个的组合-红色和绿色(或绿色和红色)、绿色和蓝色(或蓝色和绿色)以及蓝色和红色(或红色和蓝色)。
步骤
要计算和绘制输入图像的2D直方图,可以按照以下步骤进行操作 –
- 导入所需的库 OpenCV 和 matplotlib 。确保你已经安装了它们。
-
使用 cv2.imread() 方法读取输入图像。指定图像的完整路径。
-
使用 cv2.split() 函数将输入图像分割为各自的蓝色、绿色和红色通道。
blue, green, red = cv2.split(img)
- 同时计算两个颜色通道的2D颜色直方图。计算三个颜色通道三种组合的2D直方图。要计算绿色和蓝色通道的2D直方图,我们应用以下代码片段。
hist = cv2.calcHist([green, blue], [0, 1], None, [32, 32],[0, 256, 0, 256])
- 绘制上述计算出的2D直方图。
让我们看一些示例,以清楚理解问题。
我们将以下图像作为示例中的 输入文件 。
示例
在此Python程序中,我们计算并绘制输入图像的三种颜色组合(蓝色和绿色,绿色和红色,红色和蓝色)的2D直方图。
# import required libraries
import cv2
from matplotlib import pyplot as plt
# Read the input image
img = cv2.imread('blue-pool.jpg')
# split the image into the respective channels Blue, Green and Red
blue, green, red = cv2.split(img)
# 2D color histogram for the
# green and blue channels
plt.subplot(131)
hist1 = cv2.calcHist([green, blue], [0, 1], None, [32, 32],[0, 256, 0, 256])
p = plt.imshow(hist1, interpolation="nearest")
plt.title("2D Histogram for G and B", fontsize=8)
plt.colorbar(p)
# 2D color histogram for the red and green channels
plt.subplot(132)
hist2 = cv2.calcHist([red, green], [0, 1], None, [32, 32],[0, 256, 0, 256])
p = plt.imshow(hist2, interpolation="nearest")
plt.title("2D Histogram for R and G", fontsize=8)
plt.colorbar(p)
# 2D color histogram for the blue and red channels
plt.subplot(133)
hist3 = cv2.calcHist([blue, red], [0, 1], None, [32, 32],[0, 256, 0, 256])
p = plt.imshow(hist3, interpolation="nearest")
plt.title("2D Histogram for B and R", fontsize=8)
plt.colorbar(p)
plt.show()
当您运行上述程序时,它将产生以下输出窗口,显示输入图像的2D直方图。