我是 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);
选择适当的矩形尺寸应该从图像中移除白纸之外的区域
关于c++ - OpenCV绘制轮廓和裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35526720/