直方图

直方图

 cv2.calcHist([img], [channels], mask, [histSize],[ranges]) 

参数:  

  img:输入图像

  channels:选择图像的通道

  mask:掩膜

  histSize:使用多少个bin(柱子)

  ranges:像素值的范围

  注意除了mask都要带[]

返回值:

  返回每个像素块在图像中的数量,用坐标系表达直方图

 

import cv2
import matplotlib.pyplot as plt
import numpy as np

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

img = cv2.imread('1.jpg',0)
cv_show('img',img)

 

  • opencv版
img = cv2.imread('1.jpg',0)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
#opencv版
plt.plot(hist)
plt.show()

 

  • plt版

img.ravel()是降维后的一维数组,用直方图表达

img = cv2.imread('1.jpg',0)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
#plt版
#img.ravel()是降维后的一维数组,用直方图表达
plt.hist(img.ravel(), bins=256, rwidth=0.8)
plt.show()

 

每个颜色通道直方图

img = cv2.imread('1.jpg')
cv_show('img',img)
color = ('b', 'g', 'r')
for i, col in enumerate(color):
    histr = cv2.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(histr,color=col)
    plt.xlim([0,256])
plt.show()

 

 

  •  掩膜

相当于一个窗口,只有窗口中的图像会出现,窗口外的图象被遮挡

掩膜先设置一个跟图像有同样shape的全0矩阵即黑色,相当于全部遮挡

然后设置窗口大小,即需要出现的部分的值设为255,即白色

再利用bitwise_and按位与函数,图像和掩膜按位与,只留下窗口内的图像

img = cv2.imread('1.jpg')
mask = np.zeros(img.shape[:2],np.uint8)
mask[30:80,30:80] = 255
cv_show('img',mask)
masked_img = cv2.bitwise_and(img,img,mask=mask)
cv_show('img',masked_img)

掩膜:                                             图像使用掩膜:

 

 使用掩膜和不适用掩膜直方图对比

img = cv2.imread('1.jpg')
mask = np.zeros(img.shape[:2],np.uint8)
mask[30:80,30:80] = 255
masked_img = cv2.bitwise_and(img,img,mask=mask)
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.show()

 

  • 直方图均衡化

  cv2.equalize(img)是全局的均衡化

img = cv2.imread('1.jpg',0)
cv_show('img',img)
equ = cv2.equalizeHist(img)
cv_show('equ',equ)
plt.hist(equ.ravel(), bins=256, rwidth=0.8)
plt.show()

 

             

 

   cv2.createCLAHE()是分块的均衡化

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)

 

posted @ 2021-02-19 20:24  MMMMinoz  阅读(179)  评论(0编辑  收藏  举报