使用OpenCV的对象跟踪脚本中的慢速视频

Slow Video in Object Tracking Script using OpenCV

本文关键字:视频 跟踪 OpenCV 对象 使用 脚本      更新时间:2023-10-16

我在openCV和C++中编写了一个简短的例程,用网络摄像头跟踪对象。网络摄像头的配方很快,没有滞后,但在周末下班之前,我录制了一个典型的序列,用作周一之前的测试模板。这和相应的代码变化以某种方式使视频以非常慢的动作回放。这是打开"Test.avi"的代码,大约20秒长,而不是从网络摄像头上运行恒定的流:

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
Mat drawBoundingBoxes (Mat canvasImage, vector<vector<Point>> contours);
int main(int argc, char** argv[])
{
    Mat frame;
    Mat back;
    Mat fGround;
    BackgroundSubtractorMOG2 bGround;
    bGround.nmixtures = 3;
    //bGround.nShadowDetection = 0;
    bGround.fTau = .5;
    VideoCapture cap;
    cap.open("Test.avi");
    if (!cap.isOpened())
    {
        cout << "Can't open video" << endl;
        return -1;
    }
    vector<vector<Point>> contours;
    namedWindow("video", CV_WINDOW_AUTOSIZE);
    while (true)
    {
        static int count = 1;
        cap >> frame;
        if (frame.empty())
            break;
        bGround.operator()(frame, fGround);
        bGround.getBackgroundImage(back);
        erode(fGround, fGround, Mat(), Point(-1,-1), 2, BORDER_DEFAULT);
        dilate(fGround, fGround, Mat(), Point(-1,-1), 10, BORDER_DEFAULT);
        if (count > 50)
        {
            findContours(fGround, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
            drawContours(frame, contours, -1, Scalar(239,255,0), 2);
            drawBoundingBoxes(frame, contours);
        }
        imshow("video", frame);
        if(waitKey(30) >= 0) 
            break;
        count++;
    }
    return 0;
}
Mat drawBoundingBoxes (Mat canvasImage, vector<vector<Point>> contours)
{
    vector<Rect> boundRect(contours.size());
    for (int i=0; i<contours.size(); i++)
    {
        boundRect[i] = boundingRect(contours[i]);
        rectangle(canvasImage, boundRect[i], Scalar(153,0,76), 2, 8, 0);
    }
    return canvasImage;
}

有什么想法吗?内存在哪里泄漏?谢谢,

-Tony

我相信您录制的视频的帧速率高于您的电脑实时处理的帧速。这不是网络摄像头的问题,因为它只是掉帧。您可以尝试减少waitKey()过程中的延迟,看看这是否有帮助。