opencv3/C++关于移动对象的轮廓的跟踪详解
作者:阿卡蒂奥
今天小编就为大家分享一篇opencv3/C++关于移动对象的轮廓的跟踪详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
使用opencv提供的背景去除算法(KNN或高斯混合模型GMM)去除背景,然后将获取的目标二值化后通过筛选目标轮廓获得目标位置。
#include<opencv2/opencv.hpp> using namespace cv; //基于移动对象的轮廓的跟踪 int main() { Mat frame; bool flag = true; VideoCapture capture; capture.open(0); if (!capture.isOpened()) { printf("can not open ......\n"); return -1; } namedWindow("mask", WINDOW_AUTOSIZE); namedWindow("output", WINDOW_AUTOSIZE); Ptr<BackgroundSubtractor> pKNN = createBackgroundSubtractorKNN(); //Ptr<BackgroundSubtractor> pMOG2 = createBackgroundSubtractorMOG2(); while (capture.read(frame)) { Mat KNNMask; std::vector<std::vector<Point>>contours; pKNN->apply(frame, KNNMask); //(*pMOG2).apply(frame, mogMask); threshold(KNNMask, KNNMask, 100, 255, THRESH_BINARY); Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); morphologyEx(KNNMask, KNNMask, MORPH_OPEN, kernel, Point(-1,-1)); findContours(KNNMask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0,0)); for (int i = 0; i < contours.size(); i++) { //轮廓面积 double area = contourArea(contours[i]); //轮廓外接矩阵 Rect rect = boundingRect(contours[i]); if (area < 500 || rect.width < 50 || rect.height < 50) continue; rectangle(frame, rect, Scalar(0,255,255),2); putText(frame, "Target", Point(rect.x, rect.y), CV_FONT_NORMAL, FONT_HERSHEY_PLAIN, Scalar(0,255,0),2,8); } imshow("mask",KNNMask); imshow("output",frame); waitKey(1); } return 0; }
以上这篇opencv3/C++关于移动对象的轮廓的跟踪详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。