Ask Your Question
2

Drawing the Rectangle around the line

asked 2018-05-29 04:56:34 -0600

vps gravatar image

updated 2020-10-21 12:47:14 -0600

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.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
5

answered 2018-12-29 16:59:30 -0600

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;
}
edit flag offensive delete link more

Comments

Thank you for the answer.

vps gravatar imagevps ( 2019-01-10 05:00:32 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-05-29 04:56:34 -0600

Seen: 1,954 times

Last updated: Dec 29 '18