原文見:http://blog.csdn.net/xiaowei_cqu/article/details/9027617
OpenCV的ml模塊實現了人工神經網絡(Artificial Neural Networks, ANN)最典型的多層感知器(multi-layer perceptrons, MLP)模型。由於ml模型實現的算法都繼承自統一的CvStatModel基類,其訓練和預測的接口都是train(),predict(),非常簡單。
下面來看神經網絡 CvANN_MLP 的使用~
定義神經網絡及參數:
可以直接定義CvANN_MLP神經網絡,並設置其參數。 BACKPROP表示使用back-propagation的訓練方法,RPROP即最簡單的propagation訓練方法。
使用BACKPROP有兩個相關參數:bp_dw_scale即bp_moment_scale:
使用PRPOP有四個相關參數:rp_dw0, rp_dw_plus, rp_dw_minus, rp_dw_min, rp_dw_max:
上述代碼中為其默認值。
設置網絡層數,訓練數據:
layerSizes設置了有三個隱含層的網絡結構:輸入層,三個隱含層,輸出層。輸入層和輸出層節點數均為5,中間隱含層每層有兩個節點。
create第二個參數可以設置每個神經節點的激活函數,默認為CvANN_MLP::SIGMOID_SYM,即Sigmoid函數,同時提供的其他激活函數有Gauss和階躍函數。
使用訓練好的網絡結構分類新的數據:
然后直接使用predict函數,就可以預測新的節點:
Mat sampleMat = (Mat_<float>(1,5) << i,j,0,0,0); Mat responseMat; bp.predict(sampleMat,responseMat);
完整程序代碼:
//The example of using BPNetwork in OpenCV //Coded by L. Wei #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/ml/ml.hpp> #include <iostream> #include <string> using namespace std; using namespace cv; int main() { //Setup the BPNetwork CvANN_MLP bp; // Set up BPNetwork's parameters CvANN_MLP_TrainParams params; params.train_method=CvANN_MLP_TrainParams::BACKPROP; params.bp_dw_scale=0.1; params.bp_moment_scale=0.1; //params.train_method=CvANN_MLP_TrainParams::RPROP; //params.rp_dw0 = 0.1; //params.rp_dw_plus = 1.2; //params.rp_dw_minus = 0.5; //params.rp_dw_min = FLT_EPSILON; //params.rp_dw_max = 50.; // Set up training data float labels[3][5] = {{0,0,0,0,0},{1,1,1,1,1},{0,0,0,0,0}}; Mat labelsMat(3, 5, CV_32FC1, labels); float trainingData[3][5] = { {1,2,3,4,5},{111,112,113,114,115}, {21,22,23,24,25} }; Mat trainingDataMat(3, 5, CV_32FC1, trainingData); Mat layerSizes=(Mat_<int>(1,5) << 5,2,2,2,5); bp.create(layerSizes,CvANN_MLP::SIGMOID_SYM);//CvANN_MLP::SIGMOID_SYM //CvANN_MLP::GAUSSIAN //CvANN_MLP::IDENTITY bp.train(trainingDataMat, labelsMat, Mat(),Mat(), params); // Data for visual representation int width = 512, height = 512; Mat image = Mat::zeros(height, width, CV_8UC3); Vec3b green(0,255,0), blue (255,0,0); // Show the decision regions given by the SVM for (int i = 0; i < image.rows; ++i) for (int j = 0; j < image.cols; ++j) { Mat sampleMat = (Mat_<float>(1,5) << i,j,0,0,0); Mat responseMat; bp.predict(sampleMat,responseMat); float* p=responseMat.ptr<float>(0); int response=0; for(int i=0;i<5;i++){ // cout<<p[i]<<" "; response+=p[i]; } if (response >2) image.at<Vec3b>(j, i) = green; else image.at<Vec3b>(j, i) = blue; } // Show the training data int thickness = -1; int lineType = 8; circle( image, Point(501, 10), 5, Scalar( 0, 0, 0), thickness, lineType); circle( image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType); circle( image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType); circle( image, Point( 10, 501), 5, Scalar(255, 255, 255), thickness, lineType); imwrite("result.png", image); // save the image imshow("BP Simple Example", image); // show it to the user waitKey(0); }