OpenCV:绘制旋转矩形区域

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sss_369/article/details/84402370

问题:

给定4个点,求最小外接矩形,然后在图像中绘制出旋转矩形区域。

程序:

Point p1(800,400), p2(1100,605), p3(902,970), p4(802,780);//4个点
vector<Point> vec_pts;
vec_pts.push_back(p1);
vec_pts.push_back(p2);
vec_pts.push_back(p3);
vec_pts.push_back(p4);
RotatedRect rect = minAreaRect(vec_pts);//外接矩形
Point2f vertices[4];
rect.points(vertices);//外接矩形的4个顶点
for (int i = 0; i < 4; i++)//绘制外接矩形
    line(dst, vertices[i], vertices[(i + 1) % 4], Scalar(255, 0, 0));

示例:
 

#include <opencv2/opencv.hpp> 
#include <iostream>  
 
using namespace std;
using namespace cv;
 
int main()
{
    Mat image_source = imread("1.bmp", 0);
    imshow("source image", image_source );
    vector<Point> vec_pts;
    Point p1(800,400), p2(1100,605), p3(902,970), p4(802,780);//随意给了4个点
    vec_pts.push_back(p1);
    vec_pts.push_back(p2);
    vec_pts.push_back(p3);
    vec_pts.push_back(p4);
    RotatedRect rect = minAreaRect(vec_pts);//外接矩形
    Point2f vertices[4];
    rect.points(vertices);//外接矩形的4个顶点
    for (int i = 0; i < 4; i++)//画矩形
        line(image_source , vertices[i], vertices[(i + 1) % 4], Scalar(255, 0, 0));
 
    imshow("rotation rect", imageSource);
    Point2f center = rect.center;//外接矩形中心点坐标
    Mat rot_mat = getRotationMatrix2D(center, rect.angle, 1.0);//求旋转矩阵
    Mat rot_image;
    Size dst_sz(imageSource.size());
    warpAffine(imageSource, rot_image, rot_mat, dst_sz);//原图像旋转
    imshow("rot_image", rot_image);
    Mat result1 = rot_image(Rect(center.x - (rect.size.width / 2), 
                                 center.y - (rect.size.height/2), 
                                 rect.size.width, 
                                 rect.size.height));//提取ROI
    imshow("result", result1);
 
    waitKey(0);
    return 0;
}


参考文章

1. https://blog.csdn.net/flyyufenfei/article/details/79781194

猜你喜欢

转载自blog.csdn.net/sss_369/article/details/84402370
今日推荐