(1)统计一张三通道图像的彩色直方图:
原图如下:

import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
def draw_colors_hist(source_path):
'''
draw the color histogram of one three channels picture
'''
source_image=cv2.imread(source_path)
colors=['blue','green','red']
for i in range(3):
hist_total,hist_edges=np.histogram(source_image[:,:,i].ravel(),bins=256,range=(0,256))
plt.plot(0.5*(hist_edges[:-1]+hist_edges[1:]),hist_total,label=colors[i],color=colors[i])
plt.show()
draw_colors_hist('0.jpg')#注意图片的命名,若含有中文字符,会无法读取到图像。
结果如下:

(2)统计一张图片的灰度直方图。
def draw_gray_hist(source_path):
#draw the grey histogram of one three channels picture
source_image=cv2.imread(source_path)
gray_img=cv2.cvtColor(source_image,cv2.COLOR_BGR2GRAY)
hist_total,hist_edges=np.histogram(gray_img[:,:].ravel(),bins=256,range=(0,256))
plt.plot(0.5*(hist_edges[1:]+hist_edges[:-1]),hist_total,label='grey',color='gray')
plt.show()
draw_gray_hist('1.jpg')
仍采用本文开头所示的速腾2019款照片。
结果如下:

图像直方图绘制教程
本文详细介绍如何使用Python和OpenCV库绘制三通道彩色图像及灰度图像的直方图,包括代码实现与示例结果展示。
7729

被折叠的 条评论
为什么被折叠?



