其他分享
首页 > 其他分享> > 19_图像直方图

19_图像直方图

作者:互联网

# 图像直方图

# 1. 图像直方图简介

# 2. 图像直方图统计
import cv2
import numpy as np
import matplotlib.pyplot as plt

def cv_show(img,name):
    cv2.imshow(name,img)
    cv2.waitKey()
    cv2.destroyAllWindows()

img = cv2.imread('D:/pycharm/pycharm-cope/opencv/resource/photo/01_Cat.jpg',0) # 0 表示灰度图
print((img.ravel()).shape)
plt.hist(img.ravel(),256) # img.ravel()将 img 拉成一维数组
plt.show()

img = cv2.imread('D:/pycharm/pycharm-cope/opencv/resource/photo/01_Cat.jpg')
color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    print(histr.shape)
    plt.plot(histr,color=col)
    plt.xlim([0,256])

# 3. 图像掩码区域

img = cv2.imread('D:/pycharm/pycharm-cope/opencv/resource/photo/01_Cat.jpg',0)
# cv_show(img,'img')
print(img.shape[:2])
mask = np.zeros(img.shape[:2],np.uint8)# np.uint8无符号整形
print(mask.shape)
mask[100:300,100:400] = 255
# cv_show(mask,'mask')
masked_img = cv2.bitwise_and(img,img,mask=mask) # 与操作
cv_show(np.hstack((img,mask,masked_img)),'res')

# 4. 图像掩码直方图

hist_full = cv2.calcHist([img],[0],None,[256],[0,256]) # 不带掩码统计直方图
hist_mask = cv2.calcHist([img],[0],mask,[256],[0,256]) # 带上掩码统计直方图
plt.subplot(221), plt.imshow(img,'gray')
plt.subplot(222), plt.imshow(mask,'gray')
plt.subplot(223), plt.imshow(masked_img,'gray')
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask) # 掩码对应的部分区域的直方图的量要小一些
plt.xlim([0,256])
plt.show()

# 5. 直方图均衡化

img = cv2.imread('D:/pycharm/pycharm-cope/opencv/resource/photo/16_Clahe.jpg',0)
plt.hist(img.ravel(),256)
plt.show()

equ = cv2.equalizeHist(img)
plt.hist(equ.ravel(),256)
plt.show()

res = np.hstack((img,equ))
cv_show(res,'res')

# 6. 自适应直方图均衡化

img = cv2.imread('D:/pycharm/pycharm-cope/opencv/resource/photo/16_Clahe.jpg',0)
clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=(8,8)) # 自适应均衡化方法生成出来
res_clahe = clahe.apply(img) # 方法应用到输入图片当中
res = np.hstack((img,equ,res_clahe))
cv_show(res,'res')

 

标签:plt,img,19,mask,cv2,直方图,图像,256
来源: https://www.cnblogs.com/tuyin/p/16546369.html