我想在openv的FaceRecognizer类上做一个包装器。我把它命名为Identifier,这里是代码
头
class Identifier
{
public:
Identifier();
Identifier(const std::string& filename);
Identifier(const TrainData& trainData);
~Identifier();
void train(const TrainData& trainData);
private:
cv::Ptr<cv::FaceRecognizer> _model;
};
CPP
#include "Identifier.h"
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
Identifier::Identifier()
{
cout << "default constructorn";
if(_model.empty())
cout << "model has not been createdn";
}
Identifier::Identifier(const string& filename)
{
Identifier();
TrainData td;
td.load(filename);
if(_model.empty())
cout << "constructor model is emptyn";
train(td);
}
Identifier::~Identifier()
{
_model.delete_obj();
}
Identifier::Identifier(const TrainData& trainData)
{
Identifier();
train(trainData);
}
void Identifier::train(const TrainData& trainData)
{
cout << "train entern";
if(_model.empty())
cout << "model is emptyn";
vector<cv::Mat> images;
vector<int> labels;
for(int i = 0; i < trainData.size(); ++i)
{
Person curPerson = trainData[i];
vector<string> curPersonImages = curPerson.getImages();
int j = 0;
for(auto imagePath: curPersonImages)
{
cv::Mat mat = cv::imread(imagePath, CV_LOAD_IMAGE_GRAYSCALE);
images.push_back(mat);
labels.push_back(curPerson.getId());
}
}
cout << "heren"
<< images.size() << " - " << labels.size();
try
{
_model->train(images, labels);
} catch(cv::Exception& e)
{
cout << e.msg;
} catch(...)
{
cout << "something goes wrongn";
}
cout << "here 1n";
}
我有cv::Ptr的问题,因为我理解它是一种智能指针,但有一个问题,一旦我调用cv::createLBPHFaceRecognizer();在构造函数中,指针在下一个函数中释放,我的程序崩溃了,因为object_model是空的。有人能帮我吗?我如何在构造函数中初始化_model一次,然后在其他地方使用它?
我使用opencv v2.4.9, MinGW作为编译器
如果您想在参数化构造函数之前调用空构造函数,则必须这样做:
Identifier::Identifier()
: model_( cv::createLBPHFaceRecognizer() )
{
}
Identifier::Identifier(const string& filename)
: Identifier()
{
...
}
你的标识符();上面的调用生成一个本地副本,并删除它