15

I want to draw a rotated rectangle in opencv with c++. I use "rectangle" function like bellow:

rectangle(RGBsrc, vertices[0], vertices[2], Scalar(0, 0, 0),  CV_FILLED, 8, 0);

but this function draw an rectangle with 0 angle. How can i draw rotated rectangle with special angle in opencv with c++?

narges
  • 681
  • 2
  • 7
  • 26

2 Answers2

14

Since you want a filled rectangle, you should use fillConvexPoly:

// Include center point of your rectangle, size of your rectangle and the degrees of rotation  
void DrawRotatedRectangle(cv::Mat& image, cv::Point centerPoint, cv::Size rectangleSize, double rotationDegrees)
{
    cv::Scalar color = cv::Scalar(255.0, 255.0, 255.0); // white

    // Create the rotated rectangle
    cv::RotatedRect rotatedRectangle(centerPoint, rectangleSize, rotationDegrees);

    // We take the edges that OpenCV calculated for us
    cv::Point2f vertices2f[4];
    rotatedRectangle.points(vertices2f);

    // Convert them so we can use them in a fillConvexPoly
    cv::Point vertices[4];    
    for(int i = 0; i < 4; ++i){
        vertices[i] = vertices2f[i];
    }

    // Now we can fill the rotated rectangle with our specified color
    cv::fillConvexPoly(image,
                       vertices,
                       4,
                       color);
}
Jurjen
  • 1,376
  • 12
  • 19
11

The sample below demonstrates how to draw rotated rectangle in opencv c++.

Mat test_image(200, 200, CV_8UC3, Scalar(0));
RotatedRect rRect = RotatedRect(Point2f(100,100), Size2f(100,50), 30);
Point2f vertices[4];
rRect.points(vertices);
for (int i = 0; i < 4; i++)
    line(test_image, vertices[i], vertices[(i+1)%4], Scalar(0,255,0), 2);
Rect brect = rRect.boundingRect();
rectangle(test_image, brect, Scalar(255,0,0), 2);
imshow("rectangles", test_image);
waitKey(0);

The result is :
enter image description here

Reference:
OpenCV docs

alexander-liu7
  • 161
  • 1
  • 6