我正试图用我已经制作的.xml文件对我的输入图像进行分类。这是人工神经网络(ANN)的训练我不知道怎么了我正试图完全像书中"opencv的实际项目"一样编码。书的完整代码可在github:https://github.com/MasteringOpenCV/code/tree/master/Chapter5_NumberPlateRecognition
技术上我用我自己的方式从全图中提取数字段我创建了ocr。xlm文件。
我真的不知道为什么当我尝试对输入分割图像(Mat输入数组)进行分类时,我看到错误:断言失败(layer_size !=0) CvANN_MLP::预测
这是我的代码
char const strCharacters[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int const numCharacters = 9;
CvANN_MLP ann;
void train(Mat TrainData, Mat classes, int nlayers){
FileStorage fs;
fs.open("OCR.xml", FileStorage::READ);
Mat trainData;
fs["TrainingData"] >> trainData;
fs["classes"] >> classes;
Mat layers(1, 3, CV_32SC1);
layers.at<int>(0,0) = TrainData.cols;//input layer
layers.at<int>(1,0) = nlayers;//hidden layer
layers.at<int>(2,0) = numCharacters;//output layer
int buffer[] = { trainData.cols, 16, numCharacters };
ann.create(layers, CvANN_MLP::SIGMOID_SYM, 1, 1);
//Prepare trainClases
//Create a mat with n trained data by m classes
Mat trainClasses;
trainClasses.create(TrainData.rows, numCharacters, CV_32F);
for (int i = 0; i < trainClasses.rows; i++)
{
for (int k = 0; k < trainClasses.cols; k++)
{
//If class of data i is same than a k class
if (k == classes.at<int>(i))
trainClasses.at<float>(i, k) = 1;
else
trainClasses.at<float>(i, k) = 0;
}
}
Mat weights(1, TrainData.rows, CV_32FC1, Scalar::all(1));
//Learn classifier
ann.train(TrainData, trainClasses, weights);
}
int classify(Mat f){
float result = -1;
Mat output(1, numCharacters, CV_32FC1);
ann.predict(f, output);
Point maxLoc;
double maxVal;
minMaxLoc(output, 0, &maxVal, 0, &maxLoc);
//We need know where in output is the max val, the x (cols) is the class.
// result = output.at < float >(0, 0);
return maxLoc.x;
}
我在主代码中这样调用分类:
int character = classify(roiResized);
我真的很感激你的帮助。任何建议吗? 我知道这篇文章是旧的,但答案可能对其他人有用。在使用预测之前,必须在神经网络中添加层。
e。g:
// define the parameters for the neural network (MLP)
// set the network to be 3 layer 256->10->10
// - one input node per attribute in a sample
// - 10 hidden nodes
// - one output node per class
int layers_d[] = { attributes_per_sample, 10, number_of_classes};
CvMat* layers = cvCreateMatHeader(1,3,CV_32SC1);
cvInitMatHeader(layers, 1,3,CV_32SC1, layers_d);
// create the network using a sigmoid function with alpha and beta
// parameters 0.6 and 1 specified respectively (refer to manual)
CvANN_MLP* nnetwork = new CvANN_MLP;
nnetwork->create(layers, CvANN_MLP::SIGMOID_SYM, 0.6, 1);
来源:https://github.com/arnaudgelas/OpenCVExamples/blob/master/NeuralNetwork/NeuralNetwork.cpp