openCV提供了多种机器学习算法如SVM,adaboost,decision tree等,今天研究了一下神经网络,
写了一个简单的例子,以备忘。
问题描述:现有平面上100个随机点,如下图,以红色和蓝色标记为两类,现根据这些点训练一个BP神经网络分类器,将平面上的点分类。
代码如下:
//从文件载入数据 ifstream fid("E:\\code\\SmokeDetector\\data.dat",ios::binary); float* data = new float[200]; fid.read((char*)data,sizeof(float)*200); Mat trainData(100,2,CV_32FC1,data); fid.close(); //dispMat(trainData); ifstream fid2("E:\\code\\SmokeDetector\\label.dat",ios::binary); float* label = new float[100]; fid2.read((char*)label,sizeof(float)*100); Mat trainLabel(100,1,CV_32FC1,label); fid2.close(); //dispMat(trainLabel); CvANN_MLP bp; CvANN_MLP_TrainParams param; param.term_crit = cvTermCriteria(CV_TERMCRIT_ITER,10000,0.001); //设置结束条件 param.train_method = CvANN_MLP_TrainParams::BACKPROP; //训练方法采用BackProgation param.bp_dw_scale=0.1; param.bp_moment_scale=0.1; //设置为3层神经网络,1个隐藏层(8个触发节点) int layers[3] = {2,8,1}; Mat_<int> layerSize(1,3); memcpy(layerSize.data,layers,sizeof(int)*3); bp.create(layerSize,CvANN_MLP::SIGMOID_SYM); bp.train(trainData,trainLabel,Mat(),Mat(),param); bp.save("bpModel.xml"); //save classifier Mat testImg(256,256,CV_8UC3); Mat sample(1,2,CV_32FC1); Mat res; Vec3b red(0,0,255),blue(255,0,0); for(int i=0;i<testImg.rows;i++) { for(int j=0;j<testImg.cols;j++) { sample.at<float>(0,0) = i/float(testImg.rows); sample.at<float>(0,1) = j/float(testImg.cols); bp.predict(sample,res); float tmp = ((float*)res.data)[0];; if(tmp<0) testImg.at<Vec3b>(i,j) = red; else testImg.at<Vec3b>(i,j) = blue; } } imshow("result",testImg); imwrite("result.jpg",testImg); cvWaitKey(0);
包含头:
#include "stdafx.h" #include <opencv2\opencv.hpp> #include <iostream> #include <string> #include <fstream> using namespace std; using namespace cv;