opencv 绘制直方图

1,绘制直方图函数说明:

cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate ]])

参数说明:images(图像数据),channels为频道,mask默认为None,histSize:使用多少个bin(柱子),一般为256

ranges:像素值的范围,一般为[0,255]表示0~255,一般为[0.0,255.0];

2,获取像素值函数的说明:

void minMaxLoc( const Mat& src)

minMaxLoc获取水平和垂直方向的最大和最小像素值,为后面的归一化做准备

绘图函数代码实现:

def ImageHist(image,type):
    color = (255,255,255)
    windowName = 'Gray'
    if type == 31:
        color = (255,0,0)
        windowName = 'B Hist'
    elif type == 32:
        color = (0,255,0)
        windowName = 'G Hist'
    elif type == 33:
        color = (0,0,255)
        windowName = 'R Hist'
    # 1 image 2 [0] 3 mask None 4 256 5 0-255
    hist = cv2.calcHist([image],[0],None,[256],[0.0,255.0])
    #minMaxLoc获取水平和垂直方向的最大和最小像素值,为后面的归一化做准备
    minV,maxV,minL,maxL = cv2.minMaxLoc(hist)
    histImg = np.zeros([256,256,3],np.uint8)
    #归一化处理
    for h in range(256):
        intenNormal = int(hist[h]*256/maxV)
        #画线条,第二个参数是起始点,第三个参数是终止点,第四个参数是参数类型,第五个参数是线条的宽度。
        cv2.line(histImg,(h,256),(h,256-intenNormal),color)
    cv2.imshow(windowName,histImg)
    return histImg
img = cv2.imread('image0.jpg',1)
#spli的作用是分离出图片的B,R,G颜色通道
channels = cv2.split(img)# RGB - R G B
for i in range(0,3):
    ImageHist(channels[i],31+i)
cv2.waitKey(0)

实现结果如下:

opencv 绘制直方图_第1张图片

 

你可能感兴趣的:(opencv)