1

我是编程新手,所以请帮助我。我只想检索对象的外轮廓,但问题是我得到了另一个轮廓,例如边框。如何在没有任何其他轮廓的情况下获得对象的唯一外部轮廓?

示例图像:

在此处输入图像描述

这是我制作的代码:

// cvAutoHeight.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "opencv\cvaux.h"
#include "opencv\cxmisc.h"
#include "opencv\highgui.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdlib.h>

using namespace std;
using namespace cv;

int main(int, char**)
{
 Mat threshold_output;
 int thresh = 100;
 vector<vector<Point> > contours;
 vector<Vec4i> hierarchy;
 RNG rng(12345);

 CvCapture* capture = cvCaptureFromCAM(0);

cv::Mat frame; cv::Mat src_gray;

while(1) {
    frame = cvQueryFrame( capture );

    cvtColor( frame,src_gray, CV_BGR2GRAY );
    blur( src_gray, src_gray, Size(3,3) );

    //Canny( src_gray, threshold_output, 128, 255, 3 );
    threshold( src_gray, threshold_output, 100, 200, THRESH_BINARY );
findContours( threshold_output, contours, hierarchy,CV_RETR_TREE,
    CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

    /// Find the rotated rectangles and ellipses for each contour
    vector<RotatedRect> minRect( contours.size() );

  for( int i = 0; i < contours.size(); i++ )
     { 
         minRect[i] = minAreaRect( Mat(contours[i]) );
      }

  /// Draw contours + rotated rects + ellipses
  Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
  for( int i = 0; i< contours.size(); i++ )
     {

   Scalar color = Scalar( rng.uniform(0,0), rng.uniform(0,0), rng.uniform(250,250) );
       // contour
       drawContours( drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0,
               Point() );

       // rotated rectangle
       Point2f rect_points[4]; minRect[i].points( rect_points );
       for( int j = 0; j < 4; j++ )
          line( frame, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );
     }


  namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
  imshow( "Contours", frame );

    cvWaitKey(33);
}
return 0;
 }

`

4

1 回答 1

0

默认情况下,超出边界的像素值为 0 = 黑色。在阈值之后,您会得到带有白色背景的黑色斑点。这就是为什么你有 2 个轮廓。选择其中一种解决方案:

  • 使用二进制阈值倒置。
  • 在阈值后应用精明。
于 2013-06-27T20:04:08.320 回答