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; } } }