图像直方图绘制
一、定义
图像直方图: 统计图像中每级像素出现的个数,以像素级为坐标,该像素级的像素个数值所画出的直方图
图像直方图由于其计算代价较小,且具有图像平移、旋转、缩放不变性等众多优点,广泛地应用于图像处理的各个领域,特别是灰度图像的阈值分割、基于颜色的图像检索以及图像分类。
python实现
import cv2
import matplotlib.pyplot as plt
def histogram(img_gray):
'''
求灰度图像的直方图
:param img_gray: 灰度图像
:return:
'''
histogram = [0 for x in range(256)]
h,w = img_gray.shape
for i in range(h):
for j in range(w):
histogram[img_gray[i][j]] = histogram[img_gray[i][j]]+1
return histogram
def RGB_histogram(img):
'''
求彩色图像的直方图
:param img: BGR图像或者RGB图像
:return:
'''
Bhistogram = histogram(img[:,:,0])
Ghistogram = histogram(img[:,:,1])
Rhistogram = histogram(img[:,:,2])
return Bhistogram,Ghistogram,Rhistogram
###读取灰度图并显示
img = cv2.imread('image0.JPG',1)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
plt.subplot(221)
plt.imshow(img_gray,cmap = "gray")
### 计算灰度直方图并显示
plt.subplot(222)
histogram_x = [x for x in range(256)]
Gray_histogram = histogram(img_gray)
plt.bar(histogram_x,Gray_histogram,width=1)
# 计算彩色直方图并显示
BGRhistogram = RGB_histogram(img)
plt.subplot(223)
plt.bar(histogram_x,BGRhistogram[0],color="blue",width=1)
plt.bar(histogram_x,BGRhistogram[1],color="green",width=1)
plt.bar(histogram_x,BGRhistogram[2],color="red",width=1)
# 使用直方图函数画直方图
plt.subplot(224)
img = img_gray.reshape(-1) #将图像展开成一个一维的numpy数组
plt.hist(img, 256,width=2) #将数据分为256组
plt.show()