先介绍一下工程文件的布局,引入svm.cpp和main.cpp.
image
dealimage = dealimage.reshape(1, 1);//图片序列化
trainingData.push_back(dealimage);//序列化后的图片依次存入
dealimage是读入的图片数据,进行了resize成同一尺度。
trainingData是一个mat类型的数据,尺寸为 图片张数*图片像素点数。
在进行内存分配,相关的结构体都能在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));//这里要特别注意!! 要加一个存-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];
}
这里有一个需要注意的地方,最后一个index需要存-1,这是因为svm.cpp在计算时,会有下面一个判断
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;
}
网友评论