断言失败(Layer_sizes!= 0)CvANN_MLP :: predict

时间:2015-05-15 11:59:16

标签: opencv

我正在尝试使用我已经制作的.xml文件将classify函数分类为输入图像。 这是人工神经网络(ANN)的培训 我不知道出了什么问题 我正在尝试编写与“opencv实用项目”这本书完全相同的代码 github提供的完整代码: https://github.com/MasteringOpenCV/code/tree/master/Chapter5_NumberPlateRecognition

从技术上讲,我用自己的方式从全貌中提取数字段 我创建了ocr.xlm文件。

我真的不知道为什么当我尝试对输入分段图像(Mat输入数组)进行分类时,我看到错误:断言失败(Layer_sizes!= 0)CvANN_MLP :: predict

这是我的代码

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;
}

我在我的主要代码中将calssify称为:

int character = classify(roiResized);

我真的很感谢你的帮助。有什么建议吗?

1 个答案:

答案 0 :(得分:-1)

我知道这篇文章很老,但答案对其他人来说很有用。 在使用预测之前,您必须在神经元网络中添加图层。

例如:

// 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