OpenCV4入门教程136:简单SVM测试

索引地址:系列索引

土狗可以分为:四眼、大黄、松狮、下司等等。

现在给你一只狗的图片,你给分辨出图片中有没有狗,如果有狗是不是土狗,如果是土狗是土狗中的哪一种。

svm(support vector machine,支持向量机)是分类器中最常用的一种。

线性数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//---------------------------------【头文件、命名空间包含部分】----------------------------
// 描述:包含程序所使用的头文件和命名空间
//-----------------------------------------------------------------------------------------
#include "opencv2/imgcodecs.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/ml/ml.hpp>

using namespace cv;
using namespace cv::ml;

//-----------------------------------【main( )函数】--------------------------------------------
// 描述:控制台应用程序的入口函数,我们的程序从这里开始
//-------------------------------------------------------------------------------------------------
int main() {
// 视觉表达数据的设置(Data for visual representation)
int width = 512, height = 512;//图像尺寸
Mat image = Mat::zeros(height, width, CV_8UC3);//生成一幅全黑的图像

//建立训练数据( Set up training data)
int labels[4] = {1, -1, -1, -1};//标签数据
Mat labelsMat(4, 1, CV_32SC1, labels);//将标签数据填充到mat对象中

float trainingData[ 4 ][ 2 ] = {{501, 10}, {255, 10}, {501, 255}, {10, 501}};
Mat trainingDataMat(4, 2, CV_32FC1, trainingData);

Ptr<ml::SVM> svm = ml::SVM::create();
//设置支持向量机的参数(Set up SVM's parameters)
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));

// 训练支持向量机(Train the SVM)
Ptr<ml::TrainData> tdata = ml::TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);
svm->train(tdata);

Vec3b green(0, 255, 0), blue(255, 0, 0);
//显示由SVM给出的决定区域 (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, 2) << j, i);
float response = svm->predict(sampleMat);

if (response == 1)
image.at<Vec3b>(i, j) = green;
else if (response == -1)
image.at<Vec3b>(i, j) = 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);

//显示支持向量 (Show support vectors)
thickness = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();

for (int i = 0; i < sv.rows; ++i) {
const float *v = sv.ptr<float>(i);
circle(image, Point((int)v[ 0 ], (int)v[ 1 ]), 6, Scalar(128, 128, 128), thickness,
lineType);
}

imwrite("result.png", image); // 保存图像

imshow("SVM Simple Example", image); // 显示图像
waitKey(0);
}

测试结果:

linear

非线性数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//---------------------------------【头文件、命名空间包含部分】----------------------------
// 描述:包含程序所使用的头文件和命名空间
//------------------------------------------------------------------------------------------------
#include "opencv2/imgcodecs.hpp"
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/ml/ml.hpp>
using namespace cv::ml;

#define NTRAINING_SAMPLES 100 // 每类训练样本的数量
#define FRAC_LINEAR_SEP 0.9f // 部分(Fraction)线性可分的样本组成部分

using namespace cv;
using namespace std;

//-----------------------------------【main( )函数】--------------------------------------------
// 描述:控制台应用程序的入口函数,我们的程序从这里开始
//-------------------------------------------------------------------------------------------------
int main() {
//设置视觉表达的参数
const int WIDTH = 512, HEIGHT = 512;
Mat I = Mat::zeros(HEIGHT, WIDTH, CV_8UC3);
//---------------------【1】随机建立训练数据---------------------------------------
Mat trainData(2 * NTRAINING_SAMPLES, 2, CV_32FC1);
Mat labels(2 * NTRAINING_SAMPLES, 1, CV_32SC1);

RNG rng(100); // 随机生成值

//建立训练数据的线性可分的组成部分
int nLinearSamples = (int)(FRAC_LINEAR_SEP * NTRAINING_SAMPLES);

// 为Class1生成随机点
Mat trainClass = trainData.rowRange(0, nLinearSamples);
// 点的x坐标为[0,0.4)
Mat c = trainClass.colRange(0, 1);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(0.4 * WIDTH));
// 点的Y坐标为[0,1)
c = trainClass.colRange(1, 2);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));

// 为Class2生成随机点
trainClass = trainData.rowRange(2 * NTRAINING_SAMPLES - nLinearSamples, 2 * NTRAINING_SAMPLES);
// 点的x坐标为[0.6, 1]
c = trainClass.colRange(0, 1);
rng.fill(c, RNG::UNIFORM, Scalar(0.6 * WIDTH), Scalar(WIDTH));
// 点的Y坐标为[0, 1)
c = trainClass.colRange(1, 2);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));

//------------------建立训练数据的非线性可分组成部分 ---------------

// 随机生成Class1和Class2的点
trainClass = trainData.rowRange(nLinearSamples, 2 * NTRAINING_SAMPLES - nLinearSamples);
// 点的x坐标为[0.4, 0.6)
c = trainClass.colRange(0, 1);
rng.fill(c, RNG::UNIFORM, Scalar(0.4 * WIDTH), Scalar(0.6 * WIDTH));
// 点的y坐标为[0, 1)
c = trainClass.colRange(1, 2);
rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));

//------------------------- 为类设置标签 ---------------------------------
labels.rowRange(0, NTRAINING_SAMPLES).setTo(1); // Class 1
labels.rowRange(NTRAINING_SAMPLES, 2 * NTRAINING_SAMPLES).setTo(2); // Class 2

//------------------------ 2. 设置支持向量机的参数 --------------------
Ptr<ml::SVM> svm = ml::SVM::create();
svm->setC(0.1);
svm->setType(SVM::C_SVC);
svm->setKernel(SVM::LINEAR);
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER,(int)1e7,1e-6));

//------------------------ 3. 训练支持向量机
//----------------------------------------------------
cout << "Starting training process" << endl;
Ptr<ml::TrainData> tdata = ml::TrainData::create(trainData, ROW_SAMPLE,labels);
svm->train(tdata);
cout << "Finished training process" << endl;

//------------------------ 4. 标出决策区域(decision
// regions)----------------------------------------
Vec3b green(0, 100, 0), blue(100, 0, 0);
for (int i = 0; i < I.rows; ++i)
for (int j = 0; j < I.cols; ++j) {
Mat sampleMat = (Mat_<float>(1, 2) << i, j);
float response = svm->predict(sampleMat);

if (response == 1)
I.at<Vec3b>(j, i) = green;
else if (response == 2)
I.at<Vec3b>(j, i) = blue;
}

//----------------------- 5. 显示训练数据(training
// data)--------------------------------------------
int thick = -1;
int lineType = 8;
float px, py;
// Class 1
for (int i = 0; i < NTRAINING_SAMPLES; ++i) {
px = trainData.at<float>(i, 0);
py = trainData.at<float>(i, 1);
circle(I, Point((int)px, (int)py), 3, Scalar(0, 255, 0), thick, lineType);
}
// Class 2
for (int i = NTRAINING_SAMPLES; i < 2 * NTRAINING_SAMPLES; ++i) {
px = trainData.at<float>(i, 0);
py = trainData.at<float>(i, 1);
circle(I, Point((int)px, (int)py), 3, Scalar(255, 0, 0), thick, lineType);
}

//------------------------- 6. 显示支持向量(support
// vectors)-------------------------------------------
thick = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();

for (int i = 0; i < sv.rows; ++i) {
const float *v = sv.ptr<float>(i);
circle(I, Point((int)v[ 0 ], (int)v[ 1 ]), 6, Scalar(128, 128, 128), thick, lineType);
}

imwrite("result.png", I); //保存图像到文件
imshow("SVM for Non-Linear Training Data", I); // 显示最终窗口
waitKey(0);
}

测试结果:

non-linear


OpenCV4入门教程136:简单SVM测试
https://blog.jackeylea.com/opencv/opencv-simpl-svm-test/
作者
JackeyLea
发布于
2020年9月17日
许可协议