[英]OpenCV draw contour and crop
我是OpenCV的新手。 首先,將物體放在白紙上,然后使用機器人照相機拍攝照片。 在下一步中,我嘗試使用OpenCV(查找輪廓並繪制輪廓)提取放置在白皮書上的對象。 然后,我想將此對象用於我的機器人項目。
示例圖片:
這是我嘗試的代碼:
int main(int argc, char* argv[]){
int largest_area=0;
int largest_contour_index=0;
Rect bounding_rect;
// read the file from console
Mat img0 = imread(argv[1], 1);
Mat img1;
cvtColor(img0, img1, CV_RGB2GRAY);
// Canny filter
Canny(img1, img1, 100, 200);
// find the contours
vector< vector<Point> > contours;
findContours(img1, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
printf("%ld\n", contours.size());
for( size_t i = 0; i< contours.size(); i++ ) // iterate through each contour.
{
double area = contourArea(contours[i]); // Find the area of contour
if(area > largest_area)
{
largest_area = area;
largest_contour_index = i; //Store the index of largest contour
bounding_rect = boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
}
}
cout << "contour " << contours.size() << endl;
cout << "largest contour " << largest_contour_index << endl;
Scalar color = Scalar(0,0,255);
drawContours(img0, contours, -1, color);
Mat roi = Mat(img0, bounding_rect);
// show the images
imshow("result", img0);
imshow("roi",roi);
imwrite("result.png",roi);
waitKey();
return 0;
}
這將為照片中的所有對象繪制輪廓。 但是,如何僅提取白皮書上的對象? 例如此圖像:
我只想從圖像中裁剪卡,但不知道如何進行。 誰能幫我嗎?
如圖所示,在源圖像上應用ROI:
Rect r=Rect(200,210,350,300)
/*create a rectangle of width 350 and height 300 with x=200 and y=210 as top-left vertex*/
Mat img_roi=src(r);
選擇適當的矩形尺寸應從圖像中刪除白紙以外的區域
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.