我试图训练一组分为8个分类器的图像。
我找到了许多关于如何训练SVM的答案,但大多数(有点全部)只使用了1-2个班级。
这是我到目前为止所做的事情(注意它只是崩溃而没有给我一个错误):
int num_files = 128;
std::ifstream file(filename.c_str(), ifstream::in);
int img_area = 200 * 200;
float labels[128];
Mat faceMatReshaped[128];
int incr = 0;
Mat image; //original immage
Mat roi;//Region Of Interest in the image a.k.a the detected face
Size size(200, 200);//the dst image size
string line, path, classlabel; //current line, image path, image label number
while (getline(file, line))
{
stringstream liness(line);
getline(liness, path, ';');
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty())
{
image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
//image = imread(path, CV_LOAD_IMAGE_COLOR);
vector< Rect_<int> > faces_c;
haar_cascade.detectMultiScale(image, faces_c); //detect face on the sample
if (faces_c.size() > 0)
{
roi = Mat(image, faces_c[0]);
Mat dst;//dst image
resize(roi, dst, size);//resize image
faceMatReshaped[incr] = dst.reshape(0, 1);
labels[incr] = (float)atoi(classlabel.c_str());
}
else
std::cout << "PASSED: " << path << std::endl;
incr++;
}
}
Mat labelsmat(128, 1, CV_32FC1, labels);
labelsmat.convertTo(labelsmat, CV_32FC1);
Mat new_image(128, img_area, CV_32FC1, faceMatReshaped); //CONVERT TO 32FC1
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::POLY;
params.gamma = 3;
params.degree = 3;
params.coef0 = 0;
params.C = 7;
params.nu = 0.0;
params.p = 0.0;
//Crash here
svm.train(new_image, labelsmat, Mat(), Mat(), params);
我认为我的标签阵列可能有误,但我不确定。
编辑:
我使用这段代码测试了labelsmat:
for (int i = 0; i<labelsmat.rows; i++)
for (int j = 0; j<labelsmat.cols; j++)
printf("labels(%d, %d) = %f \n", i, j, labelsmat.at<float>(i, j));
基本上我明白这个: 从0级到7级(总共8级) 从0到127(128行)
标签似乎是正确的,我猜的唯一一个就是1D Mat。我该如何检查它是否正确?