仅供参考:
C/C++ code?
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
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
squares.clear();
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
// 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
// // and set the lower to 0 (which forces edges merging)
// Canny(timg, gray1, 0, thresh, 5);
// // dilate canny output to remove potential
// // holes between edge segments
// dilate(gray1, gray1, Mat(), Point(-1,-1));
// } else {
// apply threshold if l!=0:
// tgray(x,y) = gray1(x,y) < (l+1)*255/N ? 255 : 0
gray1 = timg >= (l+1)*255/N;
// }
// find contours and store them all as a list
findContours(gray1, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
vector
// test each contour
for (size_t i = 0; i < contours.size(); i++ ) {
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);//0.02为将毛边拉直的系数,如果对毛边正方形漏检,可试试调大
// square contours should have 4 vertices after approximation
// relatively large area (to filter out noisy contours)
// and be convex.
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if (approx.size() == 4 && isContourConvex(Mat(approx))) {
double area;
area=fabs(contourArea(Mat(approx)));
if (4000.0// printf("area=%lg\n",area);
double maxCosine = 0.0;
for (int j = 2; j < 5; j++ ) {
// find the maximum cosine of the angle between joint edges
double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
maxCosine = MAX(maxCosine, cosine);
if (maxCosine==1.0) break;// //边长比超过设定范围
}
// if cosines of all angles are small
// (all angles are ~90 degree) then write quandrange
// vertices to resultant sequence
if (maxCosine < 0.1 ) {//四个角和直角相比的最大误差,可根据实际情况略作调整,越小越严格
squares.push_back(approx);
return;//检测到一个合格的正方形就返回
// } else {
// Log("Cosine>=0.1\n");
}
}
}
}
}
}
1、opencv中轮廓查找有内轮廓和外轮廓之分,具体可自行百度,查找图像的内外轮廓,画出最小外接矩,计算长宽比和轮廓面积,依次作为判定条件;2、不是很明白你的问题,颜色识别吗? 如果是的颜色识别的话可以吧RGB转到HSV空间。