这道题目,采用博客方式回答比较容易说明。
问题:
对于这样的图片
如何寻找上面的矩形
思路:
这个矩形的面积在所有的图像中是最大的(除去整个图形轮廓以外),可以尝试从这个方面入手,再加上一些鲁壮的方法
#
include "stdafx.h"
# include <opencv2
/opencv.hpp
>
# include "GOCVHelper.h"
# include <iostream
>
using namespace cv;
using namespace std;
int main( int argc, const char
*
* argv )
{
Mat src = imread(
"card.png",IMREAD_COLOR);
Mat gray;
int imax =
0;
//代表最大轮廓的序号
int imaxcontour =
-
1;
//代表最大轮廓的大小
std :
:vector
<std
:
:vector
<Point
>>contours;
cvtColor(src,gray,COLOR_BGR2GRAY);
threshold(gray,gray, 100,
255,THRESH_OTSU);
bitwise_not(gray,gray); // 白色代表有数据
//寻找轮廓
findContours(gray,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
//冒泡排序,由大到小排序
VP vptmp;
for( int i =
1;i
<contours.size();i
++){
for( int j =contours.size()
-
1;j
>
=i;j
--){
if( contourArea(contours[j]) > contourArea(contours[j
-
1])){
//swap
vptmp = contours[j
-
1];
contours[j -
1]
= contours[j];
contours[j] = vptmp;
}
}
}
//找到最后结果的时候,添加一些判断
for ( int i =
0;i
<contours.size();i
++)
{
if (contourArea(contours[i]) < (src.rows
* src.cols)
/
8 )
{
drawContours(src,contours,i,Scalar( 0,
0,
255),
-
1);
break;
}
}
imshow( "结果",src);
waitKey();
return 0;
}
结果:
小结:
当然这里只是对最简单的模板图片进行了处理。如果在实际的摄像机拍摄的过程中,肯定会有其他的干扰,需要区别对待。