c++ - 检索对象的外轮廓

标签 c++ opencv image-segmentation

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

示例图片:

enter image description here

这是我编写的代码:

// 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;
 }

`

最佳答案

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

  • 使用反转的二进制阈值。
  • 在阈值之后应用精明。

关于c++ - 检索对象的外轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349543/

相关文章:

matlab - Watershed算法的过分割

c++ - 如果我不在发布版本中加入 "destruction"上的线程怎么办?

c++ - 动态异常规范已弃用

java - OpenCV 2.4.11 Java : Drawing lines from center of mass to edge of contour

c++ - 如何在 C++ 中使用 ffmpeg 流式传输 opencv Mat

从 PDF 中提取文本的算法(从一堆单词中重新排列文本布局)

c++ - boost python链接

c++ - 计算将 n 划分为正整数之和的方法数 c++

python - 使图像背景透明

image-processing - OpenCV中是否有其他方法可以进行形态学操作?