OpenCV之求多边形最小外接矩形中心点坐标及旋转度数

该博客介绍了如何使用OpenCV库进行二值图像处理,找到图像中的轮廓,并对轮廓进行排序和过滤。通过`findContours`函数获取轮廓,然后计算并绘制每个轮廓的边界框和最小外接矩形。重点关注大尺寸对象,忽略小对象,输出形心坐标。

代码

#include <opencv2\opencv.hpp>
#include <vector>  
#include <algorithm> 

using namespace cv;
using namespace std;

Mat toBinary(Mat src);
bool ascendSort(vector<Point> a, vector<Point> b);
Mat getContour(Mat src, Mat binary);

Mat srcImage, binaryImage, contourImage;

int main()
{
	srcImage = imread("222.png");//input image
	/*namedWindow("srcImage", 0);
	imshow("srcImage", srcImage);*/

	binaryImage = toBinary(srcImage);//convert to binary image
	/*namedWindow("binaryImage", 0);
	imshow("binaryImage", binaryImage);*/

	contourImage = getContour(srcImage, binaryImage);
	namedWindow("contourImage", 0);
	imshow("contourImage", contourImage);

	waitKey(0);
	return 0;
}

Mat toBinary(Mat src)
{
	Mat temp = src.clone();
	int thresh = 200, maxValue = 255;
	cvtColor(temp, temp, COLOR_BGR2GRAY);//convert to gray image
	threshold(temp, temp, thresh, maxValue, THRESH_BINARY);//binary processing
	return temp;
}

bool ascendSort(vector<Point> a, vector<Point> b)
{
	return a.size() > b.size();
}

Mat getContour(Mat src, Mat binary)
{
	Mat temp = src.clone();
	vector< vector< Point> > contours;//save all contours data
	vector<Vec4i> hierarchy;
	findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_NONE);//find contours
	//sort(contours.begin(), contours.end(), ascendSort);//ascending sort
	vector< vector<Point> >::iterator itc = contours.begin(); //iterator of contour vector
	int i = 0;
	while (itc != contours.end())
	{
		if (itc->size() > 150)//ignore the small object
		{
			if (i > 0)
			{
				Rect rect = boundingRect(*itc);//get the rectangle bounding
				rectangle(temp, rect, { 0, 0, 255 }, 2, 8);//draw the rectangle
				RotatedRect resultRect;
				resultRect = minAreaRect(*itc);//get the min area rectangle   
				Point2f pt[4];
				resultRect.points(pt);//get the coordinate of vertex
				//draw the min area rectangle
				line(temp, pt[0], pt[1], Scalar(255, 0, 0), 2, 8);
				line(temp, pt[1], pt[2], Scalar(255, 0, 0), 2, 8);
				line(temp, pt[2], pt[3], Scalar(255, 0, 0), 2, 8);
				line(temp, pt[3], pt[0], Scalar(255, 0, 0), 2, 8);
				circle(temp, resultRect.center, 5, Scalar(0, 255, 0), -1, 8, 0);

				cout << "**************形心*************" << endl;
				cout << "X坐标:" << resultRect.center.x << "   Y坐标:" << resultRect.center.y << "   偏转角度:" << resultRect.angle << endl;
				cout << "*******************************" << endl;
			}
			i++;
		}
		++itc;
	}

	return temp;
}

效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值