#include "cv.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
using namespace cv;
using namespace std;
#define NUM 35
void getok(Mat& trainingImages, vector<int>& trainingLabels);
void getno(Mat& trainingImages, vector<int>& trainingLabels);
int main(int argc, char** argv)
{
Mat classes,trainingData,trainingImages;
CvMat* results;
vector<int> trainingLabels;
getok(trainingImages, trainingLabels);
getno(trainingImages, trainingLabels);
Mat(trainingImages).copyTo(trainingData);
trainingData.convertTo(trainingData, CV_32FC1);
Mat(trainingLabels).copyTo(classes);
CvSVM SVM;; CvSVMParams param;CvTermCriteria criteria;//新建一个SVM //这里是参数
criteria = cvTermCriteria(CV_TERMCRIT_EPS, 1000, FLT_EPSILON);
param = CvSVMParams(CvSVM::C_SVC, CvSVM::RBF, 10.0, 0.09, 1.0, 10.0, 0.5, 1.0, NULL, criteria);
SVM.train(trainingData, classes, Mat(), Mat(), param);
cout << "训练中。。。。" << endl;
SVM.save("svm.xml");
int n = 1;
while (n <= 20) //30
{
string ImgName;
ImgName = "测试/3";
stringstream ss;
string str;
ss << n; ss >> str;
ImgName = ImgName + " (" + str + ")"; //图像文件明格式:ImgName(n)
ImgName = ImgName + ".bmp";
cout << "处理:" << ImgName << endl;
Mat src_test = imread(ImgName);//读取图片
Mat src_test1 = src_test;
resize(src_test, src_test, Size(200, 200));src_test = src_test.reshape(1, 1);src_test.convertTo(src_test, CV_32FC1);
float response = SVM.predict(src_test);
if (response == 1)
imshow("完好", src_test1);
if (response == -1)
imshow("缺陷", src_test1);
waitKey(0);
n++;
}
}
void getok(Mat& trainingImages, vector<int>& trainingLabels)
{
int n = 1;
while (n <= NUM) //30
{
string ImgName;
ImgName = "完好/1";
stringstream ss;
string str;
ss << n; ss >> str;
ImgName = ImgName + " (" + str + ")"; //图像文件明格式:ImgName(n)
ImgName = ImgName + ".bmp";
cout << "处理:" << ImgName << endl;
Mat src_test = imread(ImgName);//读取图片
resize(src_test, src_test, Size(200, 200));
src_test = src_test.reshape(1, 1);
trainingImages.push_back(src_test);
trainingLabels.push_back(1);
n++;
}
}
void getno(Mat& trainingImages, vector<int>& trainingLabels)
{
int n1 = 1;
while (n1 <= NUM) //30
{
string ImgName;
ImgName = "破损/2";
stringstream ss;
string str;
ss << n1; ss >> str;
ImgName = ImgName + " (" + str + ")"; //图像文件明格式:ImgName(n)
ImgName = ImgName + ".bmp";
cout << "处理:" << ImgName << endl;
Mat src_test = imread(ImgName);//读取图片
resize(src_test, src_test, Size(200, 200));
src_test = src_test.reshape(1, 1);
trainingImages.push_back(src_test);
trainingLabels.push_back(-1);
n1++;
}
}