C++ OpenCV绘制轮廓和裁剪
我是OpenCV的新手。首先,将一个物体放在一张白纸上,然后使用机器人相机拍摄一张照片。在下一步中,我将尝试使用OpenCV(查找轮廓并绘制轮廓)提取放置在白皮书上的对象。我想在我的机器人项目中使用这个对象 示例图像: 这是我尝试的代码:C++ OpenCV绘制轮廓和裁剪,c++,opencv,C++,Opencv,我是OpenCV的新手。首先,将一个物体放在一张白纸上,然后使用机器人相机拍摄一张照片。在下一步中,我将尝试使用OpenCV(查找轮廓并绘制轮廓)提取放置在白皮书上的对象。我想在我的机器人项目中使用这个对象 示例图像: 这是我尝试的代码: int main(int argc, char* argv[]){ int largest_area=0; int largest_contour_index=0; Rect bounding_rect; // read
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;
}
intmain(intargc,char*argv[]){
int最大面积=0;
int最大轮廓指数=0;
矩形边界;
//从控制台读取文件
Mat img0=imread(argv[1],1);
Mat-img1;
CVT颜色(img0、img1、CV_rgb2灰色);
//坎尼过滤器
Canny(img1,img1,100200);
//找到轮廓
矢量<矢量>等高线;
findContours(img1、等高线、等高线图、等高线图、等高线链图、等高线图);
printf(“%ld\n”,contours.size());
对于(size_t i=0;i最大面积)
{
最大面积=面积;
最大轮廓指数=i;//存储最大轮廓指数
bounding_rect=boundingRect(轮廓[i]);//查找最大轮廓的边界矩形
}
}
cout在源图像上应用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);
选择合适的矩形尺寸应该会从图像中删除白纸外的区域我已经编辑了我的问题并添加了代码。我想是的,我已经尝试在我的问题中澄清。如果您有任何问题,您可以问我是否仍然不清楚。谢谢您更正我的问题和我的英语@Alexey KukanovCan有人帮我吗?我不能继续我的项目,因为我被困在这个阶段。