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

时间:2016-01-23 22:10:22

标签: 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?

我找不到内置的这种openCV功能。我想也许你可以随时做到这一点?我怎么能实现这个?

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

enter image description here

和此输出图像:

enter image description here

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:3)

我认为带有遮罩图像的function mean 是在轮廓内获取颜色的唯一方法,但遗憾的是我无法通过Python代码显示它。

您可以通过boundingRect获取轮廓的边界框,并使用它从源图像获取图像ROI,并使用二值化图像进行遮罩(请注意克隆二值化图像,因为findcontour会破坏它)

也许一个示例c ++会很有用(抱歉我的英语很差。)

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int, char** argv )
{
  /// Load source image
  Mat src = imread(argv[1]);
  if (src.empty())
  {
    cerr << "No image supplied ..." << endl;
    return -1;
  }

  /// Convert image to gray
  Mat src_gray;
  cvtColor( src, src_gray, COLOR_BGR2GRAY );
  threshold( src_gray, src_gray, 50, 255, THRESH_BINARY );
  imshow( "src_gray", src_gray );
  /// Find contours
  vector<vector<Point> > contours;
  findContours( src_gray.clone(), contours, RETR_TREE, CHAIN_APPROX_SIMPLE );

  Mat resImage0 = src.clone();
  Mat resImage1 = src.clone();
  /// Draw contours
  for( size_t i = 0; i< contours.size(); i++ )
     {
       Scalar color = Scalar( 0, 0, 255 );
       Rect _boundingRect = boundingRect( contours[i] );
       Scalar mean_color0 = mean( src( _boundingRect ) );
       Scalar mean_color1 = mean( src( _boundingRect ), src_gray( _boundingRect ) );

       drawContours( resImage0, contours, (int)i, mean_color0, FILLED );
       drawContours( resImage1, contours, (int)i, mean_color1, FILLED );
     }

  /// Show in a window
  imshow( "src", src );
  imshow( "resImage0", resImage0 );
  imshow( "resImage1", resImage1 );
  waitKey(0);
  return(0);
}

输入图片:

enter image description here

输出图片:

enter image description here enter image description here