OpenCV:如何在轮廓/多边形内找到颜色? [英] OpenCV: How can I find the color inside a contour/polygon?

查看:414
本文介绍了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?

我找不到内置的这种openCV函数.我想也许您可以随便做吗?我该如何实现?

I can find no such openCV function built in. I assume perhaps you can do it with the moments? How can I achieve this??

使用Zaw Lin给出的建议解决方案,我得到以下输入图像:

with the proposed solution given by Zaw Lin I have this input image:

和此输出图像:

推荐答案

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

This gets the average color inside each contour and draws contours with that color to final image.

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)

这篇关于OpenCV:如何在轮廓/多边形内找到颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆