OpenCV 使用直方图分析图像
直方图是一种图形表示方式,显示了图像中像素强度(范围从0到255)的分布情况。对于一幅数字图像,直方图绘制了像素强度与像素数量之间的关系图。x轴表示强度变化,y轴表示该强度下像素的数量。
我们可以看到图像及其直方图。通过简单地观察图像的直方图,我们可以对该图像的对比度、亮度、强度分布等有一些基本的了解。
在本文中,我们将编写一个使用OpenCV模块来分析灰度图像和彩色图像的Python程序。
cv2.calcHist()函数
OpenCV提供了一个calcHist()函数来计算一个或多个图像数组的直方图。calcHist()函数的语法如下:
calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
参数
- images : 源图像。形式应该是方括号,例如[image]。
-
channels : 指定要计算直方图的通道索引。如果图像是灰度图像,则其值为[0];如果图像是彩色图像,则需要分别传递[0]、[1]或[2]来计算蓝、绿或红通道的直方图。
-
mask : 掩膜图像。如果要找到图像的特定区域的直方图,则必须为非想要的区域创建一个掩膜。如果要找到整个图像的直方图,则为空。
-
histSize : 直方图大小的数组。
-
ranges: 通常为[0,256]。
示例
在这个示例中,我们将以灰度模式找到图像的直方图。
import matplotlib.pyplot as plt
import cv2
img = cv2.imread('Images/Dog.jpg')
histogram = cv2.calcHist([img],[0],None,[256],[0,256])
plt.xlabel("Pixel values")
plt.ylabel("Nuber of Pixels")
plt.plot(histogram)
plt.show()
输出
示例
让我们在彩色模式下找到一张图像的直方图。
import matplotlib.pyplot as plt
import cv2
image = cv2.imread('Images/Sky and Beach.jpg')
# split the image into its respective channels
channels = cv2.split(image)
colors = ("b", "g", "r")
plt.title("Color Histogram")
plt.xlabel("Pixel values")
plt.ylabel("Nuber of Pixels")
# loop over the image channels
for (chan, color) in zip(channels, colors):
# create a histogram for the current channel and plot it
hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
输入图像
输出图像
从上面的直方图中,我们可以观察到图像中的蓝色部分有一些高值区域。