From 4d7ce375fc76a5ce51b244866e1f67b5621ef4e9 Mon Sep 17 00:00:00 2001 From: Vincent Rabaud Date: Mon, 8 Dec 2025 09:44:02 +0100 Subject: [PATCH] Increase minAreaRect accuracy Just keep doubles all the way and avoid arithmetic with CV_PI/2 --- modules/imgproc/src/rotcalipers.cpp | 10 +++++----- modules/imgproc/test/test_convhull.cpp | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/imgproc/src/rotcalipers.cpp b/modules/imgproc/src/rotcalipers.cpp index d906258650..e28058b199 100644 --- a/modules/imgproc/src/rotcalipers.cpp +++ b/modules/imgproc/src/rotcalipers.cpp @@ -365,7 +365,7 @@ cv::RotatedRect cv::minAreaRect( InputArray _points ) Mat hull; Point2f out[3]; RotatedRect box; - box.angle = -(float)CV_PI / 2; // default angle for box without rotation and single point + double angle = -CV_PI / 2; // default angle for box without rotation and single point static const bool clockwise = false; convexHull(_points, hull, clockwise, true); @@ -390,7 +390,7 @@ cv::RotatedRect cv::minAreaRect( InputArray _points ) if (out[1].x == 0.f && out[1].y > 0.f) std::swap(box.size.width, box.size.height); else - box.angle += (float)atan2( (double)out[1].y, (double)out[1].x ); + angle = -atan2( (double)out[1].x, (double)out[1].y ); } else if( n == 2 ) { @@ -406,12 +406,12 @@ cv::RotatedRect cv::minAreaRect( InputArray _points ) } else if (dy < 0) { - box.angle = (float)atan2( dy, dx ); + angle = atan2( dy, dx ); std::swap(box.size.width, box.size.height); } else if (dy > 0) { - box.angle += (float)atan2( dy, dx ); + angle = -atan2( dx, dy ); } } else @@ -420,7 +420,7 @@ cv::RotatedRect cv::minAreaRect( InputArray _points ) box.center = hpoints[0]; } - box.angle = (float)(box.angle*180/CV_PI); + box.angle = (float)(angle*180/CV_PI); CV_DbgCheckGE(box.angle, -90.0f, ""); CV_DbgCheckLT(box.angle, 0.0f, ""); return box; diff --git a/modules/imgproc/test/test_convhull.cpp b/modules/imgproc/test/test_convhull.cpp index 774bee7af6..24c1604d2a 100644 --- a/modules/imgproc/test/test_convhull.cpp +++ b/modules/imgproc/test/test_convhull.cpp @@ -1279,7 +1279,7 @@ INSTANTIATE_TEST_CASE_P(Imgproc, minAreaRect_of_line, testing::Values( std::make_tuple(Point2f(10, 15), Point2f(10, 25), Point2f(10, 20), Size2f(10, 0), -90.f), std::make_tuple(Point2f(450, 500), Point2f(508, 500), Point2f(479, 500), Size2f(0, 58), -90.f), - std::make_tuple(Point2f(10, 20), Point2f(13, 16), Point2f(11.5, 18), Size2f(5, 0), -53.1301002f), + std::make_tuple(Point2f(10, 20), Point2f(13, 16), Point2f(11.5, 18), Size2f(5, 0), -53.1301041f), std::make_tuple(Point2f(9, 19), Point2f(4, 7), Point2f(6.5, 13), Size2f(0, 13), -22.6198654f) ));