1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| import cv2 import numpy as np import matplotlib.pyplot as plt #cv2.calcHist(images,channels,mask,histSize,ranges) '''
·images 原图像图像格式为uint8或float32.当传入函数是用中括号[],例如[img] ·channels 同样用中括号来,他会告函数我们统幅图像的直方图。如果传入图像是灰度图他的值就是[0],如是彩色图像的传入参数可以是 [0][1][2]他们对应的是BRG ·mask 掩模图像。统整幅图像的直方图就把他的None。但是如果你想统图像莫一部分的直方图的你就制作一个掩模图像并使用他 ·histSize BIN的数目。应用中括号来 ·ranges 像素值范围常为[0~256]
'''
img_gary = cv2.imread('dm.png',0) # 0表示灰度图 # cv2.imshow('img',img) # print(img.shape) # cv2.waitKey(0)
hist = cv2.calcHist([img_gary],[0],None,[256],[0,256]) print(hist.shape)
img = cv2.imread('dm.png') color = ('b','g','r') for i ,col in enumerate(color): ''' cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate ]]) ->hist imag imaes:输入的图像 channels:选择图像的通道 mask:掩膜,是一个大小和image一样的np数组,其中把需要处理的部分指定为1,不需要处理的部分指定为0,一般设置为None,表示处理整幅图像 histSize:使用多少个bin(柱子),一般为256 ranges:像素值的范围,一般为[0,255]表示0~255
''' histr = cv2.calcHist([img],[i],None,[256],[0,256]) plt.plot(histr,color=col) plt.xlim([0,256]) plt.show()
#mask操作
#创建mask mask = np.zeros(img.shape[:2],np.uint8) #yint8 无符号整形 mask[200:400,600:800] = 255 cv2.imshow('mask',mask)
img = cv2.imread('dm.png') cv2.imshow('img',img)
masked_img = cv2.bitwise_and(img,img,mask=mask) #与操作 cv2.imshow('mask_img',masked_img) cv2.waitKey(0)
|