亲宝软件园·资讯

展开

opencv3/C++关于移动对象的轮廓的跟踪详解

人气:0

使用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++关于移动对象的轮廓的跟踪详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论