[英]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);
有人可以為我提供一個使用此圖像查找最大矩形的示例嗎?
您可以通過提高閾值來嘗試自己。
在這里,您正在找到閾值圖像上的最大輪廓,因此在threshold()
使用imshow()
顯示thr
並查看發生了什么,以及它的外觀。
通過將閾值增加到稍高的值來查看結果。
threshold(thr, thr,100, 255,THRESH_BINARY); //Threshold the gray
閾值圖像
最大輪廓的邊界矩形
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.