First time here? Check out the FAQ!

Ask Your Question
2

Drawing the Rectangle around the line

asked May 29 '18

vps gravatar image

updated Oct 21 '0

Hi All, As shown in the picture. I have two end point of line. I want to draw the rectangle by considering these points are the middle points of the two sides. It will be great, if anyone suggest me the easy way. image description

Thank you.

Preview: (hide)

1 answer

Sort by » oldest newest most voted
5

answered Dec 29 '18

using minAreaRect you can find a RotatedRect for a line.

and you can change width or height of the RotatedRect

this is output of the code below:

image description

#include <opencv2/imgproc.hpp> 
#include <opencv2/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    // create a Mat
    Mat img(400, 400, CV_8UC3, Scalar(127, 127, 127));

    // 4 point for 2 lines
    Point2f pt1(100, 100), pt2(100, 200), pt3(300, 100), pt4(200, 300);

    // visualize lines and points
    line(img, pt1, pt2, Scalar(0, 255, 0), 2);
    line(img, pt3, pt4, Scalar(0, 255, 0), 2);

    circle(img, pt1, 2, Scalar(255, 0, 0), 2);
    circle(img, pt2, 2, Scalar(255, 0, 0), 2);
    circle(img, pt3, 2, Scalar(255, 0, 0), 2);
    circle(img, pt4, 2, Scalar(255, 0, 0), 2);

    // find RotatedRect for lines
    vector<Point2f> pts1, pts2;
    pts1.push_back(pt1);
    pts1.push_back(pt2);
    pts2.push_back(pt3);
    pts2.push_back(pt4);

    RotatedRect rr1 = minAreaRect(pts1);
    RotatedRect rr2 = minAreaRect(pts2);

    // change width or height of the RotatedRect
    if(rr1.size.width)
        rr1.size.height = 20;
    else
        rr1.size.width = 20;

    if (rr2.size.width)
        rr2.size.height = 20;
    else
        rr2.size.width = 20;

    cout << rr1.size << endl;
    cout << rr2.size;

    // Draw the RotatedRect
    Point2f vtx[4];

    rr1.points(vtx);
    for (int i = 0; i < 4; i++)
        line(img, vtx[i], vtx[(i + 1) % 4], Scalar(0, 0, 255), 1);

    rr2.points(vtx);
    for (int i = 0; i < 4; i++)
        line(img, vtx[i], vtx[(i + 1) % 4], Scalar(0, 0, 255), 1);

    imshow("RotatedRect Demo", img);
    waitKey(0);

    return 0;
}
Preview: (hide)

Comments

Thank you for the answer.

vps gravatar imagevps (Jan 10 '19)edit

Question Tools

1 follower

Stats

Asked: May 29 '18

Seen: 2,073 times

Last updated: Dec 29 '18