我使用自己的正负样本,基于HOG特征训练了一个CvSVM模型:
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::RBF;
CvSVM svm;
svm.train_auto(descriptors, labels, cv::Mat(), cv::Mat(), params,
SVM_CROSS_VALIDATION_K);
我可以很好地使用分类图像:
cv::HOGDescriptor hog;
hog.winSize = cv::Size(HOG_PARAMS.width(), HOG_PARAMS.height());
//compute the HOG features
hog.compute(image, ders,
cv::Size(HOG_PARAMS.stride(),HOG_PARAMS.stride()),
cv::Size(0,0), locs);
//convert the feature to a Mat
cv::Mat desc_mat;
desc_mat.create(ders.size(), 1, CV_32FC1);
for(unsigned int i = 0; i < ders.size(); i++)
desc_mat.at<float>(i, 0) = ders[i];
float response = svm.predict(desc_mat);
现在我想使用HOGDescriptor::detectMultiScale()函数在图像中检测感兴趣的物体。为了将CvSVM转换为HOGDescriptor所需的原始形式,我使用了https://dev59.com/bm_Xa4cB1Zd3GeqP1n52#17118561建议的方法:
detector_svm.h:
#ifndef DETECTOR_SVM_H
#define DETECTOR_SVM_H
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>
class Detector_svm : public CvSVM
{
public:
std::vector<float> get_primal_form() const;
};
#endif //DETECTOR_SVM_H
detector_svm.cpp:
#include "detector_svm.h"
std::vector<float> Detector_svm::get_primal_form() const
{
std::vector<float> support_vector;
int sv_count = get_support_vector_count();
const CvSVMDecisionFunc* df = decision_func;
const double* alphas = df[0].alpha;
double rho = df[0].rho;
int var_count = get_var_count();
support_vector.resize(var_count, 0);
for (unsigned int r = 0; r < (unsigned)sv_count; r++)
{
float myalpha = alphas[r];
const float* v = get_support_vector(r);
for (int j = 0; j < var_count; j++,v++)
{
support_vector[j] += (-myalpha) * (*v);
}
}
support_vector.push_back(rho);
return support_vector;
}
然而,当我尝试设置SVM检测器时。
HOGDescriptor hog;
hog.setSVMDetector(primal_svm); //primal_svm is a std::vector<float>
我遇到了失败的断言:
OpenCV Error: Assertion failed (checkDetectorSize()) in setSVMDetector, file /home/username/libs/OpenCV-2.3.1/modules/objdetect/src/hog.cpp, line 89
terminate called after throwing an instance of 'cv::Exception'
what(): /home/username/libs/OpenCV-2.3.1/modules/objdetect/src/hog.cpp:89: error: (-215) checkDetectorSize() in function setSVMDetector
我已经尝试使用OpenCV 2.3.1和2.4.7运行这个程序,但结果是一样的。我做错了什么?