C++实现外接矩形

flyfish

外接矩形是旋转矩形或者水平矩形
其中旋转矩形是最小外接矩形
原图
C++实现外接矩形-LMLPHP

结果图

红色点是4点的坐标
该点坐标的最小外接矩形是绿色框
外接水平矩形是蓝色框
C++实现外接矩形-LMLPHP
代码实现

版本 opencv-4.6.0

#include <opencv2/opencv.hpp>

int main(int argc, char** argv)
{
    // 输入一组坐标点
    std::vector<cv::Point2f> points;
    points.push_back(cv::Point2f(50, 100));
    points.push_back(cv::Point2f(150, 200));
    points.push_back(cv::Point2f(200, 300));
    points.push_back(cv::Point2f(100, 400));

    // 计算最小外接矩形
    cv::RotatedRect rotated_rect = cv::minAreaRect(points);


    std::string  imagepath="./1.jpg";
    cv::Mat image = cv::imread(imagepath, 1);

    cv::Point2f vertices[4];
    rotated_rect.points(vertices);
    for (int i = 0; i < 4; ++i)
    {
        cv::line(image, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 2);
        cv::circle(image, points[i], 5, cv::Scalar(0, 0, 255), 2);
    }

    cv::Rect bound_rect = cv::boundingRect(points);
    cv::rectangle(image, bound_rect, cv::Scalar(255,0,0), 2);

    cv::imshow("Enclosing Rectangle", image);
    cv::waitKey(0);


    return 0;
}

主要函数是boundingRectminAreaRect

07-26 12:40