-
-
#include <iostream>
-
#include <opencv2/opencv.hpp>
-
-
#define MATCHMETHOD TM_SQDIFF_NORMED//宏定义匹配模式
-
using
namespace cv;
-
using
namespace
std;
-
-
-
int main(int argc, char** argv)
-
{
-
Mat src = imread(
"几何.jpg");
-
Mat src_gray, binary;
-
Mat Triangle = src.clone(), Rect = src.clone(), Circlar = src.clone(), Pentagon = src.clone();
-
if (src.empty()) {
-
printf(
"Could not load image...");
-
return
-1;
-
}
-
cv::imshow(
"Input Image", src);
-
-
//二值化
-
cvtColor(src, src_gray, COLOR_BGR2GRAY);
-
threshold(src_gray, binary,
0,
255, THRESH_BINARY | THRESH_OTSU);
-
binary = ~binary;
-
cv::imshow(
"binary", binary);
-
//发现轮廓
-
vector<
vector<Point>> contours;
-
vector<Point> point;
-
vector<Vec4i> hireachy;
-
findContours(binary, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
-
int a=
0;
-
int b=
0;
-
int c=
0;
-
int d=
0;
-
//绘制出所有轮廓
-
for (
size_t t =
0; t < contours.size(); t++)
-
{
-
-
int epsilon =
0.01*arcLength(contours[t],
true);
-
approxPolyDP(contours[t], point, epsilon,
true);
-
if (point.size() ==
3)
-
{
-
drawContours(Triangle, contours, t, Scalar(
0,
0,
0),
2,
8, Mat(),
0, Point());
//dst必须先初始化
-
a++;
-
}
-
else
if (point.size() ==
4)
-
{
-
drawContours(Rect, contours, t, Scalar(
0,
0,
0),
2,
8, Mat(),
0, Point());
//dst必须先初始化
-
b++;
-
}
-
else
if (point.size() ==
5)
-
{
-
drawContours(Pentagon, contours, t, Scalar(
0,
0,
0),
2,
8, Mat(),
0, Point());
//dst必须先初始化
-
c++;
-
}
-
else
if (point.size()>=
10)
-
{
-
drawContours(Circlar, contours, t, Scalar(
0,
0,
0),
2,
8, Mat(),
0, Point());
//dst必须先初始化
-
d++;
-
}
-
-
-
}
-
cout <<
"三角形数目" << a <<
endl;
-
cout <<
"四边形数目" << b <<
endl;
-
cout<<
"五边形数目" << c<<
endl;
-
cout<<
"圆形形数目" << d<<
endl;
-
imshow(
"Triangle", Triangle);
-
imshow(
"Pentagon", Pentagon);
-
imshow(
"Rect", Rect);
-
imshow(
"Circlar", Circlar);
-
-
waitKey(
0);
-
-
return
0;
-
}
转载:https://blog.csdn.net/weixin_45790559/article/details/104413139
查看评论