【问题标题】:Make a class using the VideoCapture class使用 VideoCapture 类创建一个类
【发布时间】:2016-01-21 13:10:15
【问题描述】:

对于定义类非常陌生,我遇到了在自制类中定义 VideoCapture 对象的问题。请参阅下面的代码。 我尝试创建一个包含有关视频文件的所有信息的类。所以我初始化了 videoCapture 对象。哪个工作正常,但是在“构造函数”(fName::setAviName)完成它的工作并且我调用类的另一个函数(fAvi.GetNumFrames())之后,VideoCapture 对象变成了一个 NULL 指针。 显然,当我的“构造函数”完成时,VideoCapture 对象被销毁。该类的其他私有变量工作正常。

尝试使用“共享指针”解决问题,但没有成功。

问题清楚了吗?这可能是我想做的吗?如何?还是我不应该打扰?

非常感谢,

DS

#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;

class fName
{
    std::string d_AvifName;  // name of the Avi file
    std::shared_ptr<VideoCapture> d_capture;

public:
    int setAviName(string const &fName);  //sets name in class
    int const GetNumFrames() const;
};


// functions: --------------------------------------------------

int fName::setAviName(std::string const &fName)
{  //sets AVI name in class and opens video stream

    VideoCapture d_capture(fName);

    if(!d_capture.isOpened()){  // check if succeeded
        d_AvifName = "No AVI selected";
        return (-1);
    }
    else{
        d_AvifName = fName;
        return(1);
    }

}

int const fName::GetNumFrames() const
{
    cout << d_capture->get(CV_CAP_PROP_FRAME_COUNT) << endl;
    return d_capture->get(CV_CAP_PROP_FRAME_COUNT);
};


int main(int argc, char *argv[])

{

    fName fAvi;

    int IsOK = fAvi.setAviName("/Users/jvandereb/Movies/DATA/Verspringen/test_acA1300-30gc-cam5_000035.avi");
    if (IsOK)
    cout << fAvi.GetNumFrames() << endl;

}

【问题讨论】:

  • d_capture inside setAviName 不引用类成员,它是一个自动变量,在函数返回时被销毁。

标签: c++ opencv


【解决方案1】:

您的函数fName::setAviName 创建了一个同名的新局部变量d_capture,因此未设置全局d_capture

您可以创建一个非指针实例,而不是使用 shared pointer

class fName
{
    std::string d_AvifName;  // name of the Avi file
    VideoCapture d_capture;

public:
    fName(std::string const &fName);
    int setAviName(std::string const &fName);  //sets name in class
    int const GetNumFrames() const;
};

我还建议创建一个真正的构造函数:

fName::fName(std::string const &fName) 
{
    if (!setAviName(fName)) {
       //throw some exception for example
    }
}

然后你需要更改setAviName,你可以使用open

int fName::setAviName(std::string const &fName)
{  //sets AVI name in class and opens video stream
    if(!d_capture.open(fName)){  // open and check if succeeded
        d_AvifName = "No AVI selected";
        return (-1);
    }
    else{
        d_AvifName = fName;
        return(1);
    }
}

您还需要更改GetNumFrames,因为d_capture 不再是指针:

int const fName::GetNumFrames() const
{
    cout << d_capture.get(CV_CAP_PROP_FRAME_COUNT) << endl;
    return d_capture.get(CV_CAP_PROP_FRAME_COUNT);
};

【讨论】:

  • 太棒了。非常感谢!!也很快:) 我花了一段时间才发现我错了。我认为是这样的:一旦构造了类,(真正的:)构造函数就会初始化私有成员,然后只需要打开视频流。 (?)在另一个成员函数中使用一个成员函数(这种情况下是构造函数)是正常的编码方式吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
相关资源
最近更新 更多