提取轮廓在OpenCV里有一个函数 cvFindContours
int cvFindContours( CvArr* image, CvMemStorage* storage, CvSeq** first_contour,int header_size=sizeof(CvContour),int mode=CV_RETR_LIST,int method=CV_CHAIN_APPROX_SIMPLE, CvPoint offset=cvPoint(0,0) );
测试代码:
// DetectSquare.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
// This is a demo introduces you to reading a video and camera
#include <iostream>
#include <string>
#include <sstream>
// OpenCV includes
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp> // for camera
using namespace std;
using namespace cv;
double angle(Point pt1, Point pt2, Point pt0) {// finds a cosine of angle between vectors from pt0->pt1 and from pt0->pt2
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
double ratio;//边长平方的比
ratio = (dx1*dx1 + dy1 * dy1) / (dx2*dx2 + dy2 * dy2);
//if (ratio<0.8 || 1.2<ratio) {//根据边长平方的比过小或过大提前淘汰这个四边形,如果淘汰过多,调整此比例数字
// // Log("ratio\n");
// return 1.0;//根据边长平方的比过小或过大提前淘汰这个四边形
//}
return (dx1*dx2 + dy1 * dy2) / sqrt((dx1*dx1 + dy1 * dy1)*(dx2*dx2 + dy2 * dy2) + 1e-10);
}
void findSquares(const Mat& gray0, vector<vector<Point> >& squares) {// returns sequence of squares detected on the gray0. the sequence is stored in the specified memory storage
squares.clear();
#define N 6
Mat pyr, gray1, timg;
// down-scale and upscale the gray0 to filter out the noise
pyrDown(gray0, pyr, Size(gray0.cols / 2, gray0.rows / 2));
pyrUp(pyr, timg, gray0.size());
vector<vector<Point> > contours;
// try several threshold levels
for (int l = 0; l < N; l++) {
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
// if (l == 0 ) {//可试试不对l==0做特殊处理是否能在不影响判断正方形的前提下加速判断过程
// // apply Canny. Take the upper threshold from slider
//