1、彩色直方图计算
#!/usr/bin env python3
# -*- coding:UTF8 -*-
# 彩色图像直方图的计算与显示
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('test.png')
cv2.imshow('SrcImage', img)
chans = cv2.split(img)
colors = ('b', 'g', 'r')
plt.title("’Flattened’ Color Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
for (chan, color) in zip(chans, colors):
hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
plt.show()
2、灰度直方图转换
#!/usr/bin env python3
# -*- coding:UTF8 -*-
# 灰度直方图的计算与显示
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('test.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(img_gray, cmap=plt.cm.gray)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
print(type(hist))
# 创建一个新的子视图存放灰度图
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.plot(hist)
# 设置参数范围
plt.xlim([0, 256])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
3、自定义函数实现灰度直方图计算
#!/usr/bin env python3
# -*- coding:UTF8 -*-
"""
自定义函数实现灰度直方图计算
"""
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
'''
安装matplotlib指令:
pip install matplotlib -i https://pypi.doubanio.com/simple
'''
def calcGrayHist(image):
# 灰度图像矩阵的高、宽
rows, cols = image.shape
# 存储灰度直方图
grayHist = np.zeros([256], np.uint64)
for r in range(rows):
for c in range(cols):
grayHist[image[r][c]] += 1
return grayHist
src = cv.imread('test.png', cv.IMREAD_GRAYSCALE)
cv.imshow("src", src)
# 计算灰度直方图
gray = calcGrayHist(src)
# 画出灰度直方图
x_range = range(256)
plt.plot(x_range, gray, 'r', linewidth=2, c='black')
# 设置坐标轴的范围
y_maxValue = np.max(gray)
plt.axis([0, 255, 0, y_maxValue])
# 设置坐标轴的标签
plt.xlabel('gray Level')
plt.ylabel('number of pixels')
# 显示灰度直方图
plt.show()
cv.waitKey(0)
cv.destroyAllWindows()