opencv-minAreaRect包覆指定轮廓的最小斜矩形

 21.jpg

 

 

#include<opencv2/opencv.hpp>
#include<iostream>

int main(int argc, char** argv) {

    cv::Mat src = cv::imread("D:/bb/tu/21.jpg");
    
    cv::Mat bin_img;
    cvtColor(src, bin_img, cv::COLOR_BGR2GRAY);
    threshold(bin_img, bin_img, 100, 255, cv::THRESH_BINARY_INV);//将原图转换为二值图像
     
    std::vector<std::vector<cv::Point> > contours;
    std::vector<cv::Vec4i> hierarchy;
    findContours(bin_img, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);//寻找轮廓

    for (int i = 0; i < contours.size(); i++) {
        cv::drawContours(src, contours, i, cv::Scalar(0, 0, 255), 2, 8, hierarchy);//绘制轮廓
    }
       
    cv::Point2f pts[4];
    for (int i = 0; i < contours.size(); i++) {
        cv::RotatedRect rects = minAreaRect(contours[i]);  //包覆指定轮廓的最小斜矩形

        rects.points(pts);//返回旋转矩阵的四个顶点
        for (int i = 0; i < 4; i++) {   //画出斜矩形
            line(src, pts[i], pts[(i + 1)%4], cv::Scalar(0, 255, 255), 2);
            std::cerr << pts[i] << std::endl;
        }
    }

   imshow("src", src);


    cv::waitKey(0);
    return 0;
}

 

  

 

posted @ 2022-01-19 10:58  天子骄龙  阅读(179)  评论(0编辑  收藏  举报