opencv利用多边形逼近原理识别多边形和圆


#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值