前言
1.OpenCV图像分割Grabcut算法主要功能是分割和抠图,就是把框着的目标抠出来,比如要分割出一个证件照的人的图像,只需要在目标外面画一个框,把目标框住,它就可以完成良好的分割。
2.算法运行的效果如下,如果想
代码
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
bool mouse_down = false, mouse_up = false;
cv::Point corner1, corner2;
cv::Rect rect;
cv::Mat src;
static void mouseCallback(int event, int x, int y, int, void*)
{
cv::Mat bg_model, fg_model, mask;
if (event == cv::EVENT_LBUTTONDOWN)
{
mouse_down = true;
corner1.x = x;
corner1.y = y;
}
if (event == cv::EVENT_LBUTTONUP)
{
if (abs(x - corner1.x) > 10 && abs(y - corner1.y) > 10)
{
mouse_up = true;
mouse_down = false;
corner2.x = x;
corner2.y = y;
}
else
{
mouse_down = false;
}
}
if (mouse_down == true && mouse_up == false)
{
cv::Point pt;
pt.x = x;
pt.y = y;
cv::Mat local_img = src.clone();
rectangle(local_img, corner1, pt, cv::Scalar(0, 0, 255), 3);
imshow("Cropping app", local_img);
}
if (mouse_down == false && mouse_up == true)
{
rect.width = abs(corner1.x - corner2.x);
rect.height = abs(corner1.y - corner2.y);
rect.x = std::min(corner1.x, corner2.x);
rect.y = std::min(corner1.y, corner2.y);
grabCut(src, mask, rect, bg_model, fg_model, 5, cv::GC_INIT_WITH_RECT);
compare(mask, cv::GC_PR_FGD, mask, cv::CMP_EQ);
cv::namedWindow("crop",0);
cv::Mat image_roi;
image_roi.create(src.size(), src.type());
image_roi.setTo(cv::Scalar(255, 255, 255));
src.copyTo(image_roi, mask);
cv::Mat crop(image_roi, rect);
cv::imshow("crop", crop);
mouse_down = false;
mouse_up = false;
}
}
int main()
{
src = cv::imread("12.jpg");
cv::namedWindow("cropping",0);
cv::imshow("cropping", src);
cv::setMouseCallback("cropping", mouseCallback);
cvWaitKey(0);
return 0;
}
来源:CSDN
作者:知来者逆
链接:https://blog.csdn.net/matt45m/article/details/103778232