How to remove background image with Opencv

谁说胖子不能爱 提交于 2019-12-01 06:55:45

You could try cv:inRange() for color based threshold.

cv::Mat image = cv::imread(argv[1]);
if (image.empty())
{
    std::cout << "!!! Failed imread()" << std::endl;
    return -1;
}

cv::Mat threshold_image;

// MIN B:77 G:0 R:30    MAX B:130 G:68 R:50
cv::inRange(image, cv::Scalar(77, 0, 30), 
                   cv::Scalar(130, 68, 50), 
                   threshold_image);

cv::bitwise_not(threshold_image, threshold_image); 

cv::imwrite("so_inrange.png", threshold_image);

int erode_sz = 4;
cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE,
                                   cv::Size(2*erode_sz + 1, 2*erode_sz+1),
                                   cv::Point(erode_sz, erode_sz) );

cv::erode(threshold_image, threshold_image, element);
cv::imwrite("so_erode.png", threshold_image);

cv::dilate(threshold_image, threshold_image, element);
cv::imwrite("so_dilate.png", threshold_image);

cv::imshow("Color Threshold", threshold_image);
cv::waitKey();

You could also execute cv::blur(threshold_image, threshold_image, cv::Size(3, 3)); after cv::bitwise_not() to get a slightly better result.

Have fun changing the code around.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!