Meanshift跟踪移动目标

利用Meanshift算法进行了移动目标跟踪,图片资源如下:

链接:https://yunpan.cn/cq9GfQDrsDL7r  密码:b135

红色方框为初始位置,绿色方框为跟踪到的位置。

Meanshift跟踪移动目标_第1张图片 Meanshift跟踪移动目标_第2张图片

#include <opencv2/opencv.hpp>
using namespace cv;

int histSize[1] = {256};
float hranges[2] = {0, 255};
const float* ranges[1] = {hranges};
int channels[1] = {0};

int main()
{
	VideoCapture cap("E:/Datasets/img%4d.jpg");
	Rect rect(200, 115, 45, 45);

	Mat frame, frameHSV, imgROI, dstHist, backproj;

	cap >> frame;
	cvtColor(frame, frameHSV, COLOR_RGB2HSV);
	imgROI = frameHSV(rect);
	calcHist(&imgROI, 1, channels, Mat(), dstHist, 1, histSize, ranges);
	normalize(dstHist, dstHist, 0.0, 1.0, NORM_MINMAX);

	rectangle(frame, rect, Scalar(0, 0, 255));
	imshow("Frame", frame);
	waitKey(0);

	while (true)
	{
		cap >> frame;
		if (frame.empty()) break;

		cvtColor(frame, frameHSV, COLOR_RGB2HSV);
		calcBackProject(&frameHSV, 1, channels, dstHist, backproj, ranges, 255.0);

		TermCriteria criteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.001);
		meanShift(backproj, rect, criteria);

		imgROI = frameHSV(rect);
		calcHist(&imgROI, 1, channels, Mat(), dstHist, 1, histSize, ranges);
		normalize(dstHist, dstHist, 0.0, 1.0, NORM_MINMAX);

		rectangle(frame, rect, Scalar(0, 255, 0));
		imshow("Frame", frame);

		waitKey(30);
	}

	return 0;
}


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