17 图像直方图
代码
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# 自己编写程序实现灰度图像直方图的统计
def custom_hist(gray):
h, w = gray.shape
hist = np.zeros([256], dtype=np.int32)
for row in range(h):
for col in range(w):
pv = gray[row, col]
hist[pv] += 1
y_pos = np.arange(0, 256, 1, dtype=np.int32)
plt.bar(y_pos, hist, align='center', color='r', alpha=0.5)
plt.xticks(y_pos, y_pos)
plt.ylabel('Frequency')
plt.title('Histogram')
# plt.plot(hist, color='r')
# plt.xlim([0, 256])
plt.show()
# 调用函数cv.calcHist实现图像直方图的统计
def image_hist(image):
cv.imshow("input", image)
color = ('blue', 'green', 'red')
for i, color in enumerate(color):
hist = cv.calcHist([image], [i], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
plt.show()
src = cv.imread("../images/river.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imshow("input", gray)
custom_hist(gray)
image_hist(src)
# plt.show()
cv.waitKey(0)
cv.destroyAllWindows()
实验结果
解释
图像直方图是图像像素值的统计学特征、计算代价较小,具有图像平移、旋转、缩放不变性等众多优点,广泛地应用于图像处理的各个领域,特别是灰度图像的阈值分割、基于颜色的图像检索以及图像分类、反向投影跟踪。常见的分为
- 灰度直方图
- 颜色直方图
所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。