#include<opencv2\opencv.hpp>
#include<opencv2\video.hpp>
#include<iostream>
using namespace cv;
using namespace std;
//-----------------------------全局变量声明-------------------------
Mat img;
Rect box;
Point origin;
bool drawing_box;
int trackcount;
//--------------------------------全局函数声明-----------------------
static void onmouse(int event, int x, int y, int flags, void*);
int main()
{ //视频路径
const string cappath = "C:\\Users\\Administrator\\Desktop\\vs实验文件夹\\opencv\\opencv\\test.avi";
VideoCapture cap(cappath);
int hsize = 16;
float hrange[] = { 0,180 };
int vmin = 10, vmax = 255, smin = 30;
//反射投影
bool backprojMode = false;
const float *phrange = hrange;
if (!cap.isOpened())
{
return -1;
}
BackgroundSubtractorMOG2 mog;
Mat foreground, background;
namedWindow("meanShift demo", 1);
setMouseCallback("", onmouse, 0);
Mat dst;
Mat hsv, hue, hist, backproj, mask, frame;
Rect trackWindow;
while (1)
{
cap >> frame;
if (!cap.read(frame))
{
cout << "end" << endl;
break;
}
setMouseCallback("meanShift demo", onmouse, 0);
createTrackbar("Vmin:", "meanShift demo", &vmin, 255, 0);
createTrackbar("Vmax:", "meanShift demo", &vmax, 255, 0);
createTrackbar("Smin:", "meanShift demo", &smin, 255, 0);
frame.copyTo(img);
if (trackcount)
{
cvtColor(img, hsv, CV_BGR2HSV);
inRange(hsv, Scalar(0, smin, vmin), Scalar(180, 255, vmax), mask);
int ch[] = { 0, 0 };
hue.create(hsv.size(), hsv.depth());//hue初始化为与hsv大小深度一样的矩阵
mixChannels(&hsv, 1, &hue, 1, ch, 1);
Mat roi(hue, box), maskroi(mask, box);
calcHist(&roi, 1, 0, maskroi, hist, 1,& hsize, &phrange,true,false);
normalize(hist, hist, 0, 255, CV_MINMAX);
trackWindow = box;
calcBackProject(&hue, 1, 0, hist, backproj, &phrange, 1);
backproj &= mask;
meanShift(backproj, trackWindow, TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1));
if (backprojMode)
{
cvtColor(backproj, img, CV_HSV2BGR);
}
rectangle(img, trackWindow, Scalar(0, 0, 255), 1, 8, 0);
}
mog(img, foreground, -1);
imshow("前景", foreground);
mog.getBackgroundImage(background);
imshow("2", background);
imshow("meanShift demo", img);
char c = waitKey(10);
if (c=='q')
{
return -1;
}
if (c=='p')
{
waitKey(0);
}
}
return 0;
}
static void onmouse(int event, int x, int y, int flags, void*)
{
if (drawing_box)//通过if里面代码就可以确定所选择的矩形区域
{
box.x = min(x, origin.x);
box.y = min(y, origin.y);
box.width = abs(x - origin.x);
box.height = abs(y - origin.y);
box &= Rect(0, 0, img.cols, img.rows);//交集
rectangle(img, box, Scalar(0, 0, 255), 1, 8, 0);
imshow("meanShift demo", img);
}
switch (event)
{
case CV_EVENT_LBUTTONDOWN:
drawing_box = true;
box = Rect(x, y, 0, 0);
origin = Point(x, y);
break;
case CV_EVENT_LBUTTONUP:
if (box.area() > 0)
{
trackcount = 1;
}
drawing_box = false;
}
}
opencv实现meanshift+GMM单目标追踪
最新推荐文章于 2022-06-25 22:31:42 发布