opencv学习日记——对多个轮廓进行多边形逼近
图像处理结果
代码部分
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void drawapp ( Mat result, Mat img)
{
for ( int i = 0 ; i < result. rows; i++ )
{
if ( i == result. rows - 1 )
{
Vec2i point1 = result. at< Vec2i> ( i) ;
Vec2i point2 = result. at< Vec2i> ( 0 ) ;
line ( img, point1, point2, Scalar ( 0 , 0 , 255 ) , 2 , 8 , 0 ) ;
break ;
}
Vec2i point1 = result. at< Vec2i> ( i) ;
Vec2i point2 = result. at< Vec2i> ( i + 1 ) ;
line ( img, point1, point2, Scalar ( 0 , 0 , 255 ) , 2 , 8 , 0 ) ;
}
}
int main ( )
{
Mat img = imread ( "自定义.png" ) ;
if ( img. empty ( ) )
{
cout << "输入为空" ;
return - 1 ;
}
Mat canny;
Canny ( img, canny, 150 , 300 ) ;
Mat kernel = getStructuringElement ( 0 , Size ( 3 , 3 ) ) ;
dilate ( canny, canny, kernel) ;
vector< vector< Point>> contours;
vector< Vec4i> hierachy;
findContours ( canny, contours, hierachy, 0 , 2 , Point ( ) ) ;
for ( int t = 0 ; t < contours. size ( ) ; t++ )
{
RotatedRect rrect = minAreaRect ( contours[ t] ) ;
Point2f center = rrect. center;
circle ( img, center, 2 , Scalar ( 0 , 255 , 0 ) , 2 , 8 , 0 ) ;
Mat result;
approxPolyDP ( contours[ t] , result, 4 , true ) ;
drawapp ( result, img) ;
cout << "corners: " << result. rows << endl;
}
imshow ( "img" , img) ;
waitKey ( 0 ) ;
return 0 ;
}