OpenCV Python:如何在calcHist中使用轮廓作为遮罩?

时间:2019-08-28 09:32:58

标签: python-2.7 opencv histogram mask contour

我正在尝试获取图片上某个区域的RGB直方图。我已经通过对图片进行阈值来隔离我的区域(背景是明亮的,而我的隔离区域是黑暗的)。我知道如何使用calcHist OpenCV函数中的区域轮廓作为蒙版,制作整个图片的颜色直方图,而不是仅区域的RGB直方图。

我实际上所做的是:

#I threshlod my picture to obtain my objects of interest
threshold = threshold3(img, param['thresh_red_low'], param['thresh_red_high'], param['thresh_green_low'], param['thresh_green_high'], param['thresh_blue_low'])

#I find contours of my objects
contours = cv2.findContours(threshold , cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

#For each of my objects
for indexx, contour in enumerate(contours):

    #If I directly try to put contour as a mask in calcHist, I got an error
    #I convert the contour into a mask
    mask = cv2.drawContours(image_color, contour, -1, (255, 255, 255), 2)

    #I calculate histograms for BGR channel, on ten ranges, from 5 to 256
    b_hist = cv2.calcHist([image_color],[0],mask,[10],[5,256])                        
    g_hist = cv2.calcHist([image_color],[1],mask,[10],[5,256])
    r_hist = cv2.calcHist([image_color],[2],mask,[10],[5,256])

   #Then I save results into a csv

但是我在每个直方图范围内都有太多的值。例如,我的第一个区域的面积为6371 px,其直方图值为:

Number of red pixels per range : 388997,500656,148124,97374,198893,793015,894672,1232693,674721,105807

Number of green pixels per range :
123052,478714,349357,153624,117838,105738,84656,1205018,1356478,1064373

Number of blue pixels per range :
1590057,702532,547988,430238,320658,103876,15366,7629,1527,2645

更像是整个图片的直方图,而不是区域的直方图。我对calcHist函数中的蒙版和轮廓不了解什么?

1 个答案:

答案 0 :(得分:0)

抱歉,这么晚的回复,但是我希望这对其他人有帮助。

大体上,您的代码是正确的,只是您可能只需要添加一两行并稍微修改一行即可。

#I threshlod my picture to obtain my objects of interest
threshold = threshold3(img, param['thresh_red_low'], param['thresh_red_high'], param['thresh_green_low'], param['thresh_green_high'], param['thresh_blue_low'])

#I find contours of my objects
contours = cv2.findContours(threshold , cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
#For each of my objects
for indexx, contour in enumerate(contours):
#If I directly try to put contour as a mask in calcHist, I got an error
#I convert the contour into a mask

w, h = img.shape
mask = np.zeros((h, w), dtype="uint8")
cv2.drawContours(mask, contours, indexx, 255, cv2.FILLED)


#I calculate histograms for BGR channel, on ten ranges, from 5 to 256
b_hist = cv2.calcHist([image_color],[0],mask,[10],[5,256])                        
g_hist = cv2.calcHist([image_color],[1],mask,[10],[5,256])
r_hist = cv2.calcHist([image_color],[2],mask,[10],[5,256])

#Then I save results into a csv

此解决方案假定您对轮廓内发现的所有东西都感兴趣。