OpenCV:如何找到轮廓/多边形内的颜色?

Big*_*337 5 python opencv

这就是我所拥有的

im = cv2.imread('luffy.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,0)

contours,h = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:

    // return color inside of the contour here
    mask = np.zeros(cnt.shape[:2],np.uint8)
    mean = cv2.mean(cant,mask)   // I think this is promising but so far it returns arrays with just zeros. I think its because I used np.zeros above to find the mask....
    moment = cv2.moments(cnt)   //maybe this will help?
Run Code Online (Sandbox Code Playgroud)

我找不到内置的openCV函数.我想也许你可以用这些时刻做到这一点?我怎么能实现这个?

编辑:使用Zaw Lin提出的解决方案我有这个输入图像:

在此输入图像描述

这个输出图像:

在此输入图像描述

Zaw*_*Lin 9

这将获得每个轮廓内的平均颜色,并将具有该颜色的轮廓绘制到最终图像.

import cv2
import numpy as np
im = cv2.imread('/home/zawlin/test.png')

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
contours,h = cv2.findContours(gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

final = np.zeros(im.shape,np.uint8)
mask = np.zeros(gray.shape,np.uint8)

for i in xrange(0,len(contours)):
    mask[...]=0
    cv2.drawContours(mask,contours,i,255,-1)
    cv2.drawContours(final,contours,i,cv2.mean(im,mask),-1)

cv2.imshow('im',im)
cv2.imshow('final',final)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)