OpenCV图像分割Grabcut算法

前言

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;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知来者逆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值