繁体   English   中英

查找并绘制最大的矩形 OpenCV

[英]Find and draw largest rect OpenCV

我需要在这张图片上找到最大的轮廓/矩形,它应该是卡片。图片说明

我尝试使用以下代码,但没有绘图:

int largest_area=0;
int largest_contour_index=0;
cv::Rect bounding_rect;

Mat thr(src.rows,src.cols,CV_8UC1);
Mat dst(src.rows,src.cols,CV_8UC1,Scalar::all(0));
cvtColor(src,thr,CV_BGR2GRAY); //Convert to gray
threshold(thr, thr,25, 255,THRESH_BINARY); //Threshold the gray

vector<vector<cv::Point>> contours; // Vector for storing contour
vector<Vec4i> hierarchy;

findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image

for( int i = 0; i< contours.size(); i++ ) // iterate through each contour.
{
    double a=contourArea( contours[i],false);  //  Find the area of contour
    if(a>largest_area){
        largest_area=a;
        largest_contour_index=i;                //Store the index of largest contour
        bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
    }

}

Scalar color( 255,255,255);
drawContours( dst, contours,largest_contour_index, color, CV_FILLED, 8, hierarchy ); // Draw the largest contour using previously stored index.
rectangle(src, bounding_rect,  Scalar(0,255,0),1, 8,0);

有人可以为我提供一个使用此图像查找最大矩形的示例吗?

  1. 您可以通过提高阈值来尝试自己。

  2. 在这里,您正在找到阈值图像上的最大轮廓,因此在threshold()使用imshow()显示thr并查看发生了什么,以及它的外观。

通过将阈值增加到稍高的值来查看结果。

threshold(thr, thr,100, 255,THRESH_BINARY); //Threshold the gray

阈值图像

在此处输入图片说明

最大轮廓的边界矩形

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM