opencv —— boundingRect、minAreaRect 尋找包裹輪廓的最小正矩形、最小斜矩形


尋找包裹輪廓的最小正矩形:boundingRect 函數

返回矩陣應滿足:① 輪廓上的點均在矩陣空間內。② 矩陣是正矩陣(矩形的邊界與圖像邊界平行)。

Rect boundingRect(InputArray points);

  • 唯一一個參數是輸入的二維點集,可以是 vector 或 Mat 類型。

 

代碼示例:

#include<opencv.hpp> #include<iostream>
using namespace cv; using namespace std; int main(){ Mat src = imread("C:/Users/齊明洋/Desktop/7.jpg"); imshow("src", src); Mat gray, bin_img; cvtColor(src, gray, COLOR_BGR2GRAY); //將原圖轉換為灰度圖
    imshow("gray", gray); //二值化
    threshold(gray, bin_img, 150, 255, THRESH_BINARY_INV); imshow("bin_img", bin_img); //尋找最外圍輪廓
    vector<vector<Point> >contours; findContours(bin_img, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); //繪制邊界矩陣
    RNG rngs = { 12345 }; Mat dst = Mat::zeros(src.size(), src.type()); for (int i = 0; i < contours.size(); i++) { Scalar colors = Scalar(rngs.uniform(0, 255), rngs.uniform(0, 255), rngs.uniform(0, 255)); drawContours(dst, contours, i, colors, 1); Rect rects = boundingRect(contours[i]); rectangle(dst, rects, colors, 2); } imshow("dst", dst); waitKey(0); }

效果演示:

 

尋找包裹輪廓的最小斜矩形:minAreaRect 函數

返回矩陣應滿足:① 輪廓上的點均在矩陣空間內。② 沒有面積更小的滿足條件的矩陣(與 boundingRect 返回結果的區別是:矩形的邊界不必與圖像邊界平行)。

需要補充的是,求點集的擬合橢圓(fitEllipse() https://www.cnblogs.com/bjxqmy/p/12354750.html)便是求斜矩陣內最大的橢圓(矩陣長寬分別做橢圓長軸、短軸)。

RotatedRect minAreaRect(InputArray points);

  • 唯一一個參數是輸入的二維點集,可以是 vector 或 Mat 類型。

 

代碼示例:

#include<opencv.hpp> #include<iostream> #include<vector>
using namespace cv; using namespace std; int main() { Mat src = imread("C:/Users/齊明洋/Desktop/7.jpg"); imshow("src", src); Mat gray, bin_img; cvtColor(src, gray, COLOR_BGR2GRAY); //將原圖轉換為灰度圖
    imshow("gray", gray); //二值化
    threshold(gray, bin_img, 150, 255, THRESH_BINARY_INV); imshow("bin_img", bin_img); //尋找最外圍輪廓
    vector<vector<Point> >contours; findContours(bin_img, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); //繪制最小邊界矩陣
    RNG rngs = { 12345 }; Mat dst = Mat::zeros(src.size(), src.type()); Point2f pts[4]; for (int i = 0; i < contours.size(); i++) { Scalar colors = Scalar(rngs.uniform(0, 255), rngs.uniform(0, 255), rngs.uniform(0, 255)); drawContours(dst, contours, i, colors, 1);
RotatedRect rects
= minAreaRect(contours[i]); rects.points(pts);//確定旋轉矩陣的四個頂點 for (int i = 0; i < 4; i++) { line(dst, pts[i], pts[(i + 1) % 4], colors, 2); } } imshow("dst", dst); waitKey(0); }

效果演示:

 

 

借鑒博客:https://www.cnblogs.com/little-monkey/p/7429579.html

http://www.pianshen.com/article/4286104294/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM