我是编程的新手,所以请帮助我。我想只检索一个物体的外轮廓,但问题是我有另一个轮廓像边框。如何在没有任何其他轮廓的情况下获得对象的唯一外轮廓?
示例图片:
这是我制作的代码:
// 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 :(得分:0)
默认情况下,边框外有0像素值=黑色。在阈值之后,你得到白色背景的黑色斑点。这就是为什么你有两个轮廓。选择其中一个解决方案: