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程序时,它会产生以下输出窗口
上面的输出图片显示了输入图像中一个矩形区域的直方图。
上面的两个输出图像是输入图像的掩膜和矩形区域。直方图只在这个掩膜区域计算。