opencv光流的对象跟踪

opencv 专栏收录该内容
24 篇文章 0 订阅

在这里插入图片描述


#include <QCoreApplication>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;


Mat frame,gray;
Mat prev_frame,prev_gray;

vector<Point2f> features;//角点检测 特征数据

vector<Point2f>iniPoints;//初始化特征

vector<Point2f> fpts[2];//保存当前帧的和前一帧的特征点位置

vector<uchar> status;//特征点踪跟
vector<float> errors;//跟踪时的误差

void detectFeature(Mat &inframe,Mat&ingray)
{
    double maxCorners=5000;
    double qualitylevel=0.01;
    double minDistance=10;
    double blockSize=3;

    goodFeaturesToTrack(ingray,features,maxCorners,qualitylevel,minDistance,Mat(),blockSize,false,0.04);
      printf("ddddddddddddddddddddddd\n");
}

void DrawFeature(Mat &inframe)
{

    for(int i=0;i<fpts[0].size();i++)
    {

        circle(inframe,fpts[0][i],2,Scalar(0,0,255),2,8,0);
    }
}
void drawTrackLine()
{
    for(int i=0;i<fpts[1].size();i++)
    {
        line(frame,iniPoints[i],fpts[1][i],Scalar(0,155,0),2,8,0);

        circle(frame,fpts[1][i],2,Scalar(0,0,255),2,8,0);
    }
}

void KLTrackFeature(){

    calcOpticalFlowPyrLK(prev_gray,gray,fpts[0],fpts[1],status,errors);
    int k=0;
    for(int i=0;i<fpts[1].size();i++)
     {

        double dist=abs(fpts[0][i].x-fpts[1][i].x) + abs(fpts[0][i].y-fpts[1][i].y);

        if(dist>2 &&status[i])
        {

            iniPoints[k]=iniPoints[i];
            fpts[1][k++]=fpts[1][i];

           }
    }

    iniPoints.resize(k);
    fpts[1].resize(k);
    drawTrackLine();
    std::swap(fpts[1],fpts[0]);

}

 //光流对象跟踪
int main()
{
    VideoCapture capture;
   // capture.open("../image/1113.jpg")
      capture.open(0);
    if(!capture.isOpened())
    {
         printf("could not load video ...");
         return;
    }


      Mat Mask;
      Mat kernel=getStructuringElement(MORPH_RECT,Size(3,3),Point(-1,-1));
      while (capture.read(frame)) {
            cvtColor(frame,gray,CV_BGR2GRAY);
            if(fpts[0].size() < 40)
            {
                detectFeature(frame,gray);
                fpts[0].insert(fpts[0].end(),features.begin(),features.end());
                iniPoints.insert(iniPoints.end(),features.begin(),features.end());

            }
            else
            {
                printf("ttttttttttttttttttttttttttttttttttttttttttttt\n");
            }


            if(prev_gray.empty())
            {
               gray.copyTo(prev_gray);
            }
            KLTrackFeature();
            DrawFeature(frame);

            //更新前一帧数据
            gray.copyTo(prev_gray);
            frame.copyTo(prev_frame);

            imshow("frame",frame);
              char c=waitKey(30);
              if(c==27)
              {
                  break;
              }
      }

      capture.release();
return 0;
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值