Opencv3.1 实现物体跟踪

在本教程中,给大家介绍基于opencv3.1的目标跟踪的API, 我们将学习如何以及何时使用OpenCV 3.1中提供的6种不同的跟踪器-BOOSTING,MIL,KCF,TLD,MEDIANFLOW和GOTURN。 

#include 
#include 
#include 

#include 

#include 

void DataPrepare::openCameraAndPreview()
{
	Mat input_image;
	VideoCapture cam(0);

	if (!cam.isOpened()) exit(0);



	//cam.set(CV_CAP_PROP_FRAME_WIDTH, 864);
	//cam.set(CV_CAP_PROP_FRAME_HEIGHT, 480);


	double dWidth = cam.get(CV_CAP_PROP_FRAME_WIDTH); //输入流的宽
	double dHeight = cam.get(CV_CAP_PROP_FRAME_HEIGHT); //输入流的高
	cout << "Frame size : " << dWidth << " x " << dHeight << endl;
	namedWindow("摄像头");


	int detect = true;
	Ptr tracker = Tracker::create("BOOSTING");   //工程模式 创建不同的track:BOOSTING,MIL,KCF,TLD,MEDIANFLOW和GOTURN。 
//只需要执行两个方法, 1. init 初始化最初要跟踪的区域   2.update 有新的数据来之后更新 跟踪区域的位置实现跟踪
/*多目标跟踪使用的是MultiTracker,如MultiTracker myTracker("KCF"),
	注意两点,添加目标用其成员函数myTracker.add(Mat src, Rect2d roi),
	获得跟踪结果使用myTracker.update(Mat src, vector targets),
	跟踪结果的序号即vector的序号。*/

	while (true) {
		cam >> input_image;
		double t0 = (double)cvGetTickCount();
		Rect2d face;
		if (detect)
		{
			if (faceDetect(input_image, face))
			{
				detect = false;
				cout << face.x << "  " << face.y << "  " << face.width <<"  "<< face.height << endl;
				tracker->init(input_image, face);
			}
		}
		else 
		{
			//使用物体跟踪
			//cout << face.x << face.y << face.width << face.height << endl;
			tracker->update(input_image, face);
		}
		double t1 = (double)cvGetTickCount();
		//cout << "cost is: " << ((t1 - t0) / ((double)cvGetTickFrequency() * 1000 * 1000)) * 1000 << "ms" << endl;
		cv::rectangle(input_image, face, Scalar(255,0,0));
		imshow("input image", input_image);
		if (27 == waitKey(30))
		{
			break;
		}
	}
	cam.release();
	
}	注意两点,添加目标用其成员函数myTracker.add(Mat src, Rect2d roi),
	获得跟踪结果使用myTracker.update(Mat src, vector targets),
	跟踪结果的序号即vector的序号。*/

	while (true) {
		cam >> input_image;
		double t0 = (double)cvGetTickCount();
		Rect2d face;
		if (detect)
		{
			if (faceDetect(input_image, face))
			{
				detect = false;
				cout << face.x << "  " << face.y << "  " << face.width <<"  "<< face.height << endl;
				tracker->init(input_image, face);
			}
		}
		else 
		{
			//使用物体跟踪
			//cout << face.x << face.y << face.width << face.height << endl;
			tracker->update(input_image, face);
		}
		double t1 = (double)cvGetTickCount();
		//cout << "cost is: " << ((t1 - t0) / ((double)cvGetTickFrequency() * 1000 * 1000)) * 1000 << "ms" << endl;
		cv::rectangle(input_image, face, Scalar(255,0,0));
		imshow("input image", input_image);
		if (27 == waitKey(30))
		{
			break;
		}
	}
	cam.release();
	
}

 

你可能感兴趣的:(opencv,跟踪)