Java教程

day36:均值迁移法目标跟踪

本文主要是介绍day36:均值迁移法目标跟踪,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
根据差值法检测移动的物体需 要视频中只有物体移动,一 旦物体移动时背景 也发生移动, 那么 差值法将无法检测到正确的移动物体,因为图像中每个像素的像素值都发生了改变 并且,有时我 们不但需要检测到移动的物体 而且需要能够跟踪这个物体, 无论这个物体是静止还是移动的,都 可以直观地表示其在图像中的位置,进而分析其运动轨迹、运动状态等。

 

 

 

void visionagin:: Mymeanshiftfetect2()
{
	VideoCapture capture("C:\\Users\\86176\\Downloads\\visionimage\\detect.mp4");
	if (!capture.isOpened())
	{
		cout << "视频打开失败!";
	}
	//是否已计算目标区域直方图的标志
	int hascailbrated = 0;
	Mat frame;
	Mat frame_hsv;
	capture.read(frame);
	Rect roi = selectROI("截取ROI",frame, true, false);
	//定义计算直方图的参数
	const int* channels = { 0 };
	const int hsize = 16;
	const float hrange[] = { 0,180 };
	const float* totalrange[] = { hrange };
	Mat hist;
	Mat hue, backmat;
	while (true)
	{
		if (!capture.read(frame))
		{
			break;
		}
		cvtColor(frame, frame_hsv, COLOR_BGR2HSV);
		hue.create(frame_hsv.size(), frame_hsv.depth());
		int ch[] = { 0,0 };
		mixChannels(&frame_hsv, 1, &hue, 1, ch, 1);
		if (hascailbrated <= 0)
		{
			Mat roiimg(hue, roi);
			calcHist(&roiimg, 1,channels, roiimg, hist, 1, &hsize, totalrange);
			normalize(hist, hist, 0, 255, NORM_MINMAX);
			hascailbrated = 1;
		}

		//计算目标区域反向投影
		calcBackProject(&hue, 1, channels, hist, backmat, totalrange);
		//均值迁移法跟踪目标
		meanShift(backmat, roi, TermCriteria(TermCriteria::EPS | TermCriteria::COUNT, 10, 1));
		rectangle(frame, roi, Scalar(0, 0, 255), 3,LINE_AA);
		imshow("frame中目标", frame);
		int c = waitKey(50);
		if (27 == c)
		{
			break;
		}



	}
}

 2.自适应均值迁移法实现的目标跟踪

 

void visionagin::Mycamshift()
{
	VideoCapture capture("C:\\Users\\86176\\Downloads\\visionimage\\detect.mp4");
	if (!capture.isOpened())
	{
		cout << "open failed ! " << endl;
	}
	int ishisted = 0;
	Mat hist, frame, hsv, hue, backmat;
	//截取ROI
	capture.read(frame);
	Rect roi = selectROI("截取roi", frame, true, false);
	int histsize = 16;
	const int channels[] = { 0 };
	const float hrange[] = { 0,180 };
	const float* trange[] = { hrange };
	while (true)
	{
		if (!capture.read(frame))
		{
			break;
		}
		cvtColor(frame, hsv, COLOR_BGR2HSV);
		hue.create(hsv.size(), hsv.depth());
		int ch[] = { 0,0 };
		mixChannels(&hsv, 1, &hue, 1, ch, 1);
		
		if (ishisted <= 0)
		{
			Mat roiimg(hue, roi);
			calcHist(&roiimg, 1, channels,roiimg, hist, 1, &histsize, trange);
			normalize(hist, hist, 0, 255,NORM_MINMAX);
			ishisted = 1;
		}
		calcBackProject(&hue, 1, channels, hist, backmat, trange);
		RotatedRect box=CamShift(backmat, roi, TermCriteria(TermCriteria::COUNT | TermCriteria::EPS, 1, 10));
		//rectangle(frame, roi, Scalar(0, 0, 255), 3, LINE_AA);
		ellipse(frame, box, Scalar(0, 0, 255), 3);
		imshow("跟踪结果", frame);
		int c = waitKey(50);
		if (27 == c)
		{
			break;
		}
	}
}

这篇关于day36:均值迁移法目标跟踪的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!