c++ - OpenCV绘制轮廓和裁剪

标签 c++ opencv

我是 OpenCV 的新手。首先,将物体放在白纸上,然后使用机器人相机拍摄照片。在下一步中,我尝试使用 OpenCV 提取放置在白纸上的对象(查找轮廓并绘制轮廓)。我想将此对象用于我的机器人项目。

示例图片:

example image

这是我试过的代码:

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;
}

这会为照片中的所有对象绘制轮廓。但是我怎样才能只提取白纸上的对象呢?例如在这张图片中:

this image

我只想从图像中裁剪卡片,但我不知道如何进行。谁能帮帮我?

最佳答案

如图所示在源图像上应用 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/

相关文章:

c++ - OpenCV 识别此图像中的线条

c++ - 如何防止图标被突出显示?

c++ - 读取一个bmp文件数据并写入另一个bmp

linux - 使用静态 OpenCV 库交叉编译 ARM 时出现 undefined reference

opencv - 使用 OpenCV 最大化期望在人身上画椭圆

opencv - WIN7下打开NamedWindow时Open CV崩溃

c++ - 在 C++ 中处理几乎所有的异常

由于权限错误,C++ 编译器输出未运行

c++ - 如何复制精确的字符数c字符串

OpenCV 3.4 : OpenCL on RaspberryPi 4 GPU