我使用 Opencv 编写了一个 Android 应用程序,我的图像处理算法需要对检测到的矩形进行正确的旋转,因此作为该过程的开始,我
- 将最大的矩形检测为
RotatedRect
。 - 获取矩形的旋转角度和中心。
- 使用
getRotationMatrix2D
创建旋转矩阵 - 使用
warpAffine
执行仿射变换 - 使用
getRectSubPix
提取检测到的矩形
孔处理工作正常,但对象倾斜有问题。
当对象逆时针旋转时,歪斜校正效果很好,但是如果顺时针旋转,矩形会旋转 90 度。
需要说明的是,因为Opencv相机的方向错误,所以我首先在矩形旋转角度上加上了-90。
这是我的代码
/* *******************************************************************************************
* get angle and size from the rotated rect
*******************************************************************************************/
double rect_angle = rbox.angle - 90.0;
Size rect_size = rbox.size;
/* *******************************************************************************************
* correct the orientation
*******************************************************************************************/
double d = rect_size.width;
rect_size.width = rect_size.height;
rect_size.height = d;
M = Imgproc.getRotationMatrix2D(rbox.center, rect_angle, 1.0);
Imgproc.warpAffine(origMat, rotated, M, origMat.size());
/* *******************************************************************************************
* crop the resulting image
*******************************************************************************************/
if (rect_size.width > 75 && rect_size.height > 75)
Imgproc.getRectSubPix(rotated, new Size(rect_size.width - 75, rect_size.height - 75), rbox.center, rotated);
/* *******************************************************************************************
* resize the result image because rotated has the size of the rect not the original image
* which cause the preview camera to be black because of wrong dimensions
*******************************************************************************************/
Imgproc.resize(rotated, rotated, origMat.size());
这是对象顺时针旋转时的结果图
这是对象逆时针旋转的结果图像
这是原图
我应该提一下,当对象不旋转时,角度为 -90 如果顺时针旋转,角度趋向于 -179,如果逆时针旋转,则角度变为 -179 并趋向于 -90。
我试过这样设置条件
if (rbox.angle < -90.0) {
rect_angle -= 90.0;
}
但没有任何效果。
我知道这是一个数学问题,但我找不到实现它的方法,我希望你们能帮我解决这个问题。
最佳答案
对于大家关心的答案,我找到了解决办法。
我研究的是检测到的矩形的宽度和高度,而不是角度。
所以在创建旋转矩阵之前我添加了这个测试代码
if (rbox.size.width < rbox.size.height) {
rect_angle += 90.0;
double d1 = rect_size.height;
rect_size.height = rect_size.width;
rect_size.width = d1;
}
关于android - 如何使用 OpenCV 校正 RotatedRect 偏斜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491884/