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;
}
`
謝謝,但我又遇到了另一個問題。我注意到我也檢測到硬幣的內部輪廓,但我只想檢測外部輪廓並製作矩形框。請給我一些解決方案。 – user2529081
更多模糊您的圖片。 – baci
非常感謝,它非常有幫助。我想用長方形來測量圖像的高度和寬度。有任何想法或解決方案嗎? – user2529081