此系列源码在我的GitHub里:https://github.com/yeyujujishou19/Python-OpenCV
原图
一,CV2分通道描绘直方图:
import cv2
import numpy as np
#计算并绘制直方图
def calcAndDrawHist(image, color):
hist = cv2.calcHist([image],
[0], # 使用的通道
None, # 没有使用mask
[256], # HistSize
[0.0, 255.0]) # 直方图柱的范围
#要求矩阵的最小值,最大值,并得到最大值,最小值的索引
minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)
histImg = np.zeros([256, 256, 3], np.uint8) #画板
hpt = int(0.9 * 256);
for h in range(256):
intensity = int(hist[h] * hpt / maxVal)
cv2.line(histImg, (h, 256), (h, 256 - intensity), color)
return histImg;
if __name__ == '__main__':
img = cv2.imread("D:/lena.jpg")
b, g, r = cv2.split(img) #分离通道
histImgB = calcAndDrawHist(b, [255, 0, 0]) #绘制直方图
histImgG = calcAndDrawHist(g, [0, 255, 0])
histImgR = calcAndDrawHist(r, [0, 0, 255])
cv2.imshow("histImgB", histImgB)
cv2.imshow("histImgG", histImgG)
cv2.imshow("histImgR", histImgR)
cv2.imshow("Img", img)
cv2.waitKey(0)
cv2.destroyAllWindows() #注销窗口
代码结果:
二,CV2折线来描绘直方图
# coding=utf-8
import cv2
import numpy as np
img = cv2.imread('D:/lena.jpg')
h = np.zeros((256, 256, 3)) # 创建用于绘制直方图的全0图像
bins = np.arange(256).reshape(256, 1) # 直方图中各bin的顶点位置
color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] # BGR三种颜色
for ch, col in enumerate(color):
#cv2.calcHist函数得到的是float32类型的数组
originHist = cv2.calcHist([img], [ch], None, [256], [0, 256])
#归一化函数,该函数将直方图的范围限定在0-255×0.9之间。
cv2.normalize(originHist, originHist, 0, 255 * 0.9, cv2.NORM_MINMAX)
hist = np.int32(np.around(originHist)) #将整数部分转成np.int32类型
pts = np.column_stack((bins, hist)) #将直方图中每个bin的值转成相应的坐标
cv2.polylines(h, [pts], False, col) #根据这些点绘制出折线
h = np.flipud(h) #反转绘制好的直方图,因为绘制时,[0,0]在图像的左上角
cv2.imshow('colorhist', h)
cv2.waitKey(0)
代码结果:
三,NumPy版的直方图计算
# coding=utf-8
import cv2
import numpy as np
img = cv2.imread('D:/lena.jpg')
h = np.zeros((300, 256, 3))
bins = np.arange(257)
bin = bins[0:-1]
color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
for ch, col in enumerate(color):
item = img[:, :, ch]
N, bins = np.histogram(item, bins)
v = N.max()
N = np.int32(np.around((N * 255) / v))
N = N.reshape(256, 1)
pts = np.column_stack((bin, N))
cv2.polylines(h, [pts], False, col)
h = np.flipud(h)
cv2.imshow('image', h)
cv2.waitKey(0)
代码结果:
四,通过NumPy和matplotlib绘制出直方图
import matplotlib.pyplot as plt
import numpy as np
import cv2
img = cv2.imread('D:/lena.jpg')
bins = np.arange(257)
item = img[:, :, 1]
hist, bins = np.histogram(item, bins)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()
代码结果:
原文地址:https://blog.csdn.net/sunny2038/article/details/9097989