OpenCV Python – 如何计算和绘制图像区域的直方图?


在 OpenCV 中,我们使用 `cv2.calcHist()` 函数来计算图像的直方图。我们可以使用此函数来计算图像区域的直方图。要计算图像中某个区域的直方图,首先我们定义一个掩码。掩码中的白色表示要检查原始输入图像中的区域,而掩码图像中的黑色表示要忽略的区域。现在我们计算直方图,并将此掩码作为参数传递给函数。

步骤

要计算和绘制图像区域的直方图,可以按照以下步骤操作:

  • 导入所需的库 **OpenCV、NumPy** 和 **matplotlib。** 请确保您已经安装了它们。

  • 使用 `cv2.imread()` 方法读取输入图像。指定图像的完整路径。

  • 为我们的图像定义一个掩码。掩码图像中的黑色表示要忽略的区域,白色表示要检查原始输入图像中的区域。

  • 使用 `cv2.split()` 函数分割输入图像的不同通道(蓝色、绿色和红色)。

  • 使用上面定义的掩码计算输入图像不同通道的直方图。绘制输入图像不同颜色的直方图。

hist = cv2.calcHist([channel], [0], mask, [256], [0, 256])
  • 要可视化输入图像的掩码区域,请对输入图像与掩码图像执行 `cv2.bitwise_and()` 操作。它会创建一个输入图像的掩码区域。

让我们看一些例子,以便更好地理解这个问题。

输入

我们在下面的示例中使用以下图像作为输入文件。


示例

在此示例中,我们计算输入图像矩形区域的直方图并绘制直方图。

# import required libraries import cv2 from matplotlib import pyplot as plt import numpy as np # Read the input image img = cv2.imread('architecture2.jpg') # define a function to compute and plot histogram def plot_histogram(img, title, mask=None): # split the image into blue, green and red channels channels = cv2.split(img) colors = ("b", "g", "r") plt.title(title) plt.xlabel("Bins") plt.ylabel("# of Pixels") # loop over the image channels for (channel, color) in zip(channels, colors): # compute the histogram for the current channel and plot it hist = cv2.calcHist([channel], [0], mask, [256], [0, 256]) plt.plot(hist, color=color) plt.xlim([0, 256]) # define a mask for our image; black for regions to ignore # and white for regions to examine mask = np.zeros(img.shape[:2], dtype="uint8") cv2.rectangle(mask, (160, 130), (410, 290), 255, -1) # display the masked region masked = cv2.bitwise_and(img, img, mask=mask) # compute a histogram for masked image plot_histogram(img, "Histogram for Masked Image", mask=mask) # show the plots plt.show() cv2.imshow("Mask", mask) cv2.imshow("Mask Image", masked) cv2.waitKey(0)

输出

运行上述 Python 程序时,它会生成以下输出窗口:


上述输出图像显示了输入图像中矩形区域的直方图。



上述两张输出图像是输入图像的掩码和矩形区域。直方图仅针对此掩码区域计算。

更新于:2022年12月2日

3K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.