OpenCV RotatedRect angle is wrong

本文提供了一种改进的方法来计算旋转矩形中较长边与垂直线之间的角度,包括使用自定义函数进行角度调整。

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

Improving on the answer of @Adam Goodwin i want to add my little code that changes the behaviour a little bit:

I wanted to have the angle between the longer side and vertical (to me it is the most natural way to think about rotated rectangles):

Behold my Paint skills

If you need the same, just use this code:

void printAngle(RotatedRect calculatedRect){
    if(calculatedRect.size.width < calculatedRect.size.height){
        printf("Angle along longer side: %7.2f\n", calculatedRect.angle+180);
    }else{
        printf("Angle along longer side: %7.2f\n", calculatedRect.angle+90);
    }
}

To see it in action just insert it in Adam Goodwins code:

printf("Angle given by minAreaRect: %7.2f\n", calculatedRect.angle);
printAngle(calculatedRect);
printf("---\n");
原文
### OpenCVRotatedRect 的使用方法 在 OpenCV 中,`RotatedRect` 是用来描述旋转矩形的重要结构体。它包含了三个核心属性:中心点 `(center)`、大小 `(size)` 和旋转角度 `(angle)`。通过这些属性,可以方便地表示任意方向上的矩形区域。 #### 属性说明 - **Center**: 表示旋转矩形的几何中心,是一个二维浮点数坐标 `(x, y)`。 - **Size**: 定义旋转矩形的宽度和高度 `(width, height)`,同样为浮点数值。 - **Angle**: 描述旋转矩形相对于水平轴的角度,单位为度数。正角度表示逆时针旋转[^1]。 下面提供一段完整的 C++ 示例代码来展示如何创建并绘制一个 `RotatedRect` 对象: ```cpp #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main() { // 创建一幅空白图像 Mat image = Mat::zeros(300, 300, CV_8UC3); // 定义旋转矩形 Point2f center(image.cols / 2.0f, image.rows / 2.0f); // 中心点 Size2f size(100, 50); // 长宽 float angle = 45.0; // 旋转角度 RotatedRect rect(center, size, angle); // 绘制旋转矩形 vector<Point2f> points; rect.points(points); // 获取四个顶点 for (int i = 0; i < 4; ++i) { line(image, points[i], points[(i + 1) % 4], Scalar(0, 255, 0), 2); } // 显示结果 imshow("Rotated Rect", image); waitKey(0); return 0; } ``` 在这段代码中,我们首先定义了一个 `RotatedRect` 实例,并设置了它的中心位置、尺寸以及旋转角度。接着调用了成员函数 `points()` 来获取构成该矩形的四个顶点坐标,最后利用这些顶点画出了实际的图形轮廓[^1]。 另外值得注意的是,在某些情况下可能还需要计算最小外包络矩形或者是将当前形状适配到特定比例下等情况,则需要用到额外辅助工具比如 contourArea 或 boundingRect 等功能配合完成相应任务[^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值