运动目标检测之光流法(3):金字塔Lucas-Kanade算法c++实现

#前言

起初是用的python跑了光流法和差分法的代码,后来换用c++。

vs code配置c/c++环境比较麻烦,就换用了vs studio。

在vs studio中配置opencv环境:

​​​​​​VS配置永久OpenCV(小萌轻松操作):超细致_矮矮的小胖子的博客-CSDN博客_vs配置opencv

#LK金字塔算法的C语言代码

参考链接:opencv3/C++光流点追踪_阿卡蒂奥的博客-CSDN博客

但是这个原代码我跑着有点问题,修改了一部分,如下:

#include
using namespace cv;

//光流跟踪
Mat frame, gray, pr_frame, pr_gray;
std::vector inPoints;
std::vector fpts[2];
void trackFeature();

int main()
{
    VideoCapture capture;
    capture.open(0);
    if (!capture.isOpened())
    {
        printf("can not open the camear......\n");
        return -1;
    }
    namedWindow("input", WINDOW_AUTOSIZE);
    namedWindow("output", WINDOW_AUTOSIZE);

    while (capture.read(frame))
    {
        cvtColor(frame, gray, COLOR_BGR2GRAY);
        if (fpts[0].size() < 40)
        {
            imshow("input", frame);
            std::vector features;
            //角点检测
            goodFeaturesToTrack(gray, features, 300, 0.01, 10);
            fpts[0].insert(fpts[0].end(), features.begin(), features.end());
            inPoints.insert(inPoints.end(), features.begin(), features.end());
        }
        else
            printf("object tracking......\n");
        if (pr_gray.empty())
            gray.copyTo(pr_gray);
        trackFeature();
        for (int i = 0; i < fpts[0].size(); i++)
            circle(frame, fpts[0][i], 2, Scalar(0, 255, 0), 2, 8, 0);
        gray.copyTo(pr_gray);
        frame.copyTo(pr_frame);
        imshow("output", frame);
        waitKey(1);
    }
    waitKey(0);
    capture.release();
    return 0;
}


void trackFeature()
{
    std::vector status;
    std::vector errors;
    //计算稀疏特征集的光流
    calcOpticalFlowPyrLK(pr_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])
        {
            inPoints[k] = inPoints[i];
            fpts[1][k++] = fpts[1][i];
        }
    }
    inPoints.resize(k);
    fpts[1].resize(k);
    //绘制光流轨迹
    RNG rng(0);
    for (int i = 0; i < fpts[1].size(); i++)
    {
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        line(frame, inPoints[i], fpts[1][i], color, 2);
        circle(frame, fpts[1][i], 2, Scalar(0, 255, 255), 2);
    }
    std::swap(fpts[1], fpts[0]);
}

你可能感兴趣的:(目标检测)