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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

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

效果

 

### 使用 OpenCV 对图像中的框进行旋转 对于图像处理任务,特别是当涉及到对特定区域(如矩形框)执行旋转变换时,可以遵循一系列具体的操作流程。为了实现这一目标,在获取到待旋转的矩形框位置之后,应该计算该矩形框的中心点作为旋转中心[^1]。 创建用于描述所需旋转特性的二维旋转矩阵是必要的步骤之一。这可以通过调用 `cv2.getRotationMatrix2D` 函数来完成,此函数接收三个参数:旋转中心坐标旋转角度以及缩放因子[^3]。一旦拥有了这个旋转矩阵,则可利用 `cv2.warpAffine` 方法将定义好的仿射变换应用至整个图像或是指定区域内,从而达到仅对该部分实施旋转的效果。 下面给出一段 Python 代码示例,展示如何使用上述提及的技术手段针对给定边界框内的对象实行精确的角度调整: ```python import cv2 import numpy as np def rotate_box(image, box_points, angle): # 计算包围盒的最小面积矩形及其属性 rect = cv2.minAreaRect(box_points) # 获取矩形四个顶点坐标并转换成整数列表形式 points = cv2.boxPoints(rect).astype(int) # 提取矩形中心点 (cx,cy),宽高(w,h) 和旋转角 theta ((cx, cy), (width, height), _) = rect # 构建围绕着矩形中心点顺时针方向旋转angle度数的变换矩阵M M = cv2.getRotationMatrix2D((cx, cy), angle, scale=1.0) # 应用仿射变换于原始图片之上获得新的已旋转版本img_rotated img_rotated = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) # 将原矩形框按照相同方式映射回新图中对应的位置pts_transformed pts_float = np.float32([points]) pts_transformed = cv2.transform(pts_float, M)[0].reshape(-1, 2) return img_rotated, pts_transformed.astype(int) # 测试案例 if __name__ == "__main__": # 加载测试图像 img = cv2.imread('example.jpg') # 定义要旋转的目标物体所在的矩形框四个顶点坐标数组 bbox_coords = [[578, 93], [642, 87], [649, 150], [585, 156]] # 执行旋转操作并将结果可视化显示出来 rotated_image, transformed_bbox = rotate_box(img, np.array(bbox_coords), -45) # 绘制原来的bbox和经过旋转后的bbox以便对比查看效果 for p in bbox_coords: cv2.circle(img, tuple(p), radius=5, color=(0, 0, 255), thickness=-1) for t_p in transformed_bbox.tolist(): cv2.circle(rotated_image, tuple(t_p), radius=5, color=(0, 255, 0), thickness=-1) cv2.imshow("Original Image", img) cv2.imshow("Rotated Box Result", rotated_image) cv2.waitKey(0) ``` 这段程序展示了怎样通过构建自定义函数 `rotate_box()` 来接受输入图像、表示感兴趣区间的多边形轮廓数据结构以及期望施加的旋转量;最终返回经由所设定规则改变姿态后的新图形连同更新过坐标的边界线段集合[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值