Opencv实现去除背景留下前景

最近要用DN跑UCF101数据集,看了王东曙教授的论文 Developmental Network: An Internal Emergent Object Feature Learning

里面用抑制了背景的人脸图像给DN去做识别,有93.51%的识别率。然后就想着用抑制了背景的UCF101数据集给DN做动作识别

会怎么样。

 

抑制了背景的人脸如下图:


Opencv实现去除背景留下前景_第1张图片

实验结果如下图:

Opencv实现去除背景留下前景_第2张图片

 

然后就想用DN跑UCF101试试效果。下面进入正题:

opencv函数太多了,不过常用的还是应该记住。

1、 line() 函数

void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
/**参数含义:  

img: on which you are going to draw.

pt1: start point of the line

pt2: end point of the line

color: the color of the line you are going to draw

thickness: the width of the line

lineType: the type of the line .(smooth or Anti-sawtooth)

shift:decimal number of the cordinate */

 

2、cvSetMouseCallback()

void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param=NULL ); 

window_name: 回调函数需要注册到的窗口的name,也就是产生事件的window

on_mouse: 指定窗口里每次鼠标事件发生的时候,被调用的函数指针(注:这个变量是一个函数指针(地址))

 

3、实验效果

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
using namespace cv;

CvPoint prev_pt = { -1, -1 };
Mat img;

Mat img_mask;
Mat dst;

void on_mouse(int event, int x, int y, int flags, void*)
{
	if (!img.data)
		return;
	if (event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON))  //判断事件为松开鼠标左键或者不是左拖拽
	{
		prev_pt = cvPoint(-1, -1);
	}
	else if (event == CV_EVENT_LBUTTONDOWN)  //判断为按下左键
	{
		prev_pt = cvPoint(x, y);
	}
	else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))  //判断移动鼠标并且左拖拽
	{
		CvPoint pt = cvPoint(x, y);
		if (prev_pt.x < 0)
		{
			prev_pt = pt;
		}
		line(img_mask, prev_pt, pt, Scalar(0), 2, 8, 0); //模板上划线
		line(img, prev_pt, pt, Scalar::all(255), 2, 8, 0);          //原图上划线
		prev_pt = pt;
		imshow("image", img);





	}
	if (event == CV_EVENT_RBUTTONUP)  //如果鼠标右键点击图片
	{

		floodFill(img_mask, Point(x, y), Scalar(0));//填充抠图模板
													/*imshow("img_mask", img_mask);*/
		img.copyTo(dst, img_mask);
		imshow("dst", dst);
		imwrite("E:/Cpp_Test/get_foreground/ConsoleApplication2/image_mask.png", img_mask);

	}

}



int main(int argc, char * argv[])
{

	Mat image = imread("E:/Cpp_Test/get_foreground/ConsoleApplication2/gray.png");
	image.copyTo(img);

	//将模板设置成白色
	img_mask.create(img.rows, img.cols, CV_8U);
	img_mask.setTo(Scalar(255));
	
	//显示原图
	imshow("image", img);


	////显示模板原图
	//imshow("watershed transform", img_mask);

	//鼠标回调函数
	cvSetMouseCallback("image", on_mouse, 0);



	waitKey(0);
	imwrite("E:/Cpp_Test/get_foreground/ConsoleApplication2/image.png",img);
	return 0;
}

 

Opencv实现去除背景留下前景_第3张图片

 

你可能感兴趣的:(MachineLearning)