MeanShift算法:跟踪图像高密度区域,均值漂移,大小变化无法跟踪
CAMShift算法:可以跟踪大小变化,通过改变模型大小匹配
#include
#include
#include
#include
using namespace cv;
using namespace std;
int smin = 15;
int vmin = 40;
int vmax = 256;
int bins = 16;
int main(int argc, char** argv)
{
VideoCapture capture;
capture.open("./video/balltest.mp4");
if(!capture.isOpened())
{
printf("[%s][%d]could not find video data file...\n",__FUNCTION__,__LINE__);
return -1;
}
bool firstRead = true;
float hrange[] = {0,180};
const float* hranges = hrange;
Rect selection;
Mat frame;
Mat hsv,hue,mask,hist,backprojection;
Mat drawImg = Mat::zeros(300,300,CV_8UC3);
bool havedest = true;//用来处理前几针没有目标物体
while(capture.read(frame))
{
if(havedest == false)
{
imshow("input",frame);
if(waitKey(200) == 'h')
{
havedest = true;
}
else
{
continue;
}
}
if(firstRead)
{
//区域选择
printf("[%s][%d]Please choice roi\n",__FUNCTION__,__LINE__);
Rect2d first = selectROI("input",frame);
selection.x = first.x;
selection.y = first.y;
selection.width = first.width;
selection.height = first.height;
printf("[%s][%d]ROI.x=%d,ROI.y= %d,width = %d,height = %d\n",__FUNCTION__,__LINE__,
selection.x,selection.y,selection.width,selection.height);
}
//转化为HSV色彩空间
cvtColor(frame,hsv,COLOR_BGR2HSV);
inRange(hsv,Scalar(0,smin,vmin),Scalar(180,vmax,vmax),mask);
hue = Mat(hsv.size(),hsv.depth());
int channels[] = {0,0};
mixChannels(&hsv, 1, &hue, 1,channels, 1);
if(firstRead)
{
//计算直方图
Mat roi(hue,selection);
Mat maskroi(mask,selection);
calcHist(&roi,1,0,maskroi,hist,1,&bins,&hranges);
normalize(hist,hist,0,255,NORM_MINMAX);
//画直方图
int binw = drawImg.cols/bins;
Mat colorIndex = Mat(1,bins,CV_8UC3);
for(int i=0;i (0,i) = Vec3b(saturate_cast(i*180/bins),255,255);
}
cvtColor(colorIndex,colorIndex,COLOR_HSV2BGR);
for(int i=0;i < bins;i++)
{
int val = saturate_cast(hist.at(i)*drawImg.rows/255);
rectangle(drawImg,Point(i*binw,drawImg.rows),Point((i+1)*binw,drawImg.rows-val),\
Scalar(colorIndex.at(0,i)),-1,8,0);
}
firstRead = false;
}
//跟踪
calcBackProject(&hue,1,0,hist,backprojection,&hranges);//反向映射图
backprojection &=mask;
RotatedRect trackBox = CamShift(backprojection,selection,TermCriteria((TermCriteria::COUNT|TermCriteria::EPS),10,1));
//画出位置
ellipse(frame,trackBox,Scalar(0,0,255),3,8);
//imshow("drawImg",drawImg);
//imshow("hsv",hsv);
imshow("input",frame);
if(27 == waitKey(30))
{
break;
}
}
capture.release();
return 0;
}
效果动图: