先介紹一下工程文件的布局,引入svm.cpp和main.cpp.
image
dealimage = dealimage.reshape(1, 1);//圖片序列化
trainingData.push_back(dealimage);//序列化后的圖片依次存入
dealimage是讀入的圖片數(shù)據(jù),進(jìn)行了resize成同一尺度。
trainingData是一個(gè)mat類型的數(shù)據(jù),尺寸為 圖片張數(shù)*圖片像素點(diǎn)數(shù)。
在進(jìn)行內(nèi)存分配,相關(guān)的結(jié)構(gòu)體都能在svm.h中找到
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
struct svm_parameter param; // set by parse_command_line
struct svm_problem prob; // set by read_problem
struct svm_model *model;
struct svm_node *x_space;
prob.l = trainingData.rows;
prob.y = Malloc(double, (prob.l));
prob.x = Malloc(svm_node*, (prob.l ));
for (int i = 0; i < trainingData.rows; i++)
{
x_space = Malloc(svm_node, (trainingData.cols + 1));//這里要特別注意??! 要加一個(gè)存-1
for (int j = 0; j < trainingData.cols; j++)
{
struct svm_node x ;
ostringstream uchar2d;
x.index = j + 1;
x.value = trainingData.at<uchar>(i, j);
x_space[j] = x;
}
struct svm_node x;
x.index = -1;//!!!一定要有存-1的步驟
x_space[trainingData.cols] = x;
prob.x[i] = x_space;
prob.y[i] = labels[i];
}
這里有一個(gè)需要注意的地方,最后一個(gè)index需要存-1,這是因?yàn)閟vm.cpp在計(jì)算時(shí),會(huì)有下面一個(gè)判斷
double Kernel::dot(const svm_node *px, const svm_node *py)
{
double sum = 0;
while(px->index != -1 && py->index != -1)
{
if(px->index == py->index)
{
sum += px->value * py->value;
++px;
++py;
}
else
{
if(px->index > py->index)
++py;
else
++px;
}
}
return sum;
}