Search code examples
c++opencvbounding-box

Is there a way to use minAreaRect from OpenCV with double?


I'm working within a 3D environment and a camera so that I have some 3D coordinates on one side and playing around with OpenCV on the other side.

I need to find a minimal bounding rectangle to a polygon, considering 2D coordinates and would like to use OpenCV for that.

The issue is that my coordinates are represented in double.

I tried:

  std::vector<cv::Point2d> poly {{1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6}, {7.7, 8.8}};
  cv::RotatedRect box = cv::minAreaRect(poly); // crashes here

  cv::Point2f corners[4];
  box.points(corners);

but got the following error:

OpenCV Error: Assertion failed (points.checkVector(2) >= 0 && (points.depth() == CV_32F || points.depth() == CV_32S)) in minAreaRect, file /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/contours.cpp, line 1913

If I use some Point instead of Point2d the coordinates of the resulted rectangle are truncated

// narrowing conversions
std::vector<cv::Point2d> poly {{1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6}, {7.7, 8.8}};
cv::RotatedRect box = cv::minAreaRect(poly);

cv::Point2f corners[4];
box.points(corners);

I'm not hundred percent sure if I'm using OpenCV the right way but I stumbled upon this and would like to avoid writing my own Rotating Calipers function.

Thanks !


Solution

  • minAreaRect accepts only Point or Point2f, i.e. points of type CV_32S or CV_32F.

    If float points have enough accuracy for you, you can use Point2f instead of Point2d:

    std::vector<cv::Point2f> poly{ { 1.1f, 2.2f }, { 3.3f, 4.4f }, { 5.5f, 6.6f }, { 7.7f, 8.8f } };
    cv::RotatedRect box = cv::minAreaRect(poly); // now it works!