Python使用matplotlib计算并绘制图像的直方图

除了使用OpenCV计算图像直方图外,matplotlib也提供了直方图计算并绘制功能,只需要把图像(或对应通道)作为参数输入,即可通过matplotlib输出直方图(标准直方图,非条形图表达),特记录下来,示例代码如下:

import cv2
import matplotlib.pyplot as plt

# 读取图像
image_path = '../data/park.jpg'
image = cv2.imread(image_path)  # 读取彩色图像

# 分离图像通道
b, g, r = cv2.split(image)

# 绘制直方图
plt.figure(figsize=(10, 6))

# 使用matplotlib的hist函数计算并绘制直方图
plt.hist(b.ravel(), bins=256, range=[0, 256], color='blue', alpha=0.7)
plt.hist(g.ravel(), bins=256, range=[0, 256], color='green', alpha=0.7)
plt.hist(r.ravel(), bins=256, range=[0, 256], color='red', alpha=0.7)

# 设置标题和轴标签
plt.title('Histogram of the Image')
plt.xlabel('Intensity Value')
plt.ylabel('Frequency')

# 显示网格
plt.grid(axis='y', linestyle='--', alpha=0.7)

# 显示图表
plt.show()

matplotlib直接计算并显示图像直方图

猜你喜欢

转载自blog.csdn.net/Humbunklung/article/details/141404542