reproduce-bug.cpp

Reproduction of a similar bug - Stefan Walk, 2010-08-18 02:35 pm

Download (1.5 kB)

 
1
#include <opencv2/opencv.hpp>
2
#include <opencv2/ml/ml.hpp>
3
#include <iostream>
4
5
using namespace cv;
6
using namespace std;
7
8
Mat catMat(Mat const& a, Mat const& b) {
9
        assert(a.cols == b.cols);
10
        Mat ret(a.rows + b.rows, a.cols, a.type());
11
        Mat d = ret.rowRange(0, a.rows);
12
        a.copyTo(d);
13
        d = ret.rowRange(a.rows, a.rows + b.rows);
14
        b.copyTo(d);
15
        return ret;
16
}
17
18
void outMat(Mat& out) {
19
        for (int i = 0; i < out.rows; i++) {
20
                for (int j = 0; j < out.cols; j++) {
21
                        cout << out.at<float>(i, j) << " ";
22
                }
23
                cout << endl;
24
        }
25
}
26
27
28
void classify_svm(Mat const& data, Mat const& labels, Mat& out) {
29
        CvSVMParams params;
30
        params.svm_type    = CvSVM::C_SVC;
31
        params.kernel_type = CvSVM::LINEAR;
32
        params.p           = 1;
33
        CvSVM classifier;
34
        classifier.train(data, labels, Mat(), Mat(), params);
35
        for (int i = 0; i < out.rows; i++) {
36
                out.at<float>(i, 0) = -classifier.predict(data.row(i), true);
37
        }
38
        params = classifier.get_params();
39
        cout << "p: " << params.p << endl;
40
}
41
42
43
int main(int, char**) {
44
        int npos = 2474;
45
               int nneg = 12180;
46
        int dim = 3780;
47
        Mat pos(npos, dim, CV_32FC1);
48
        randn(pos, 1, 1);
49
        Mat neg(nneg, dim, CV_32FC1);
50
        randn(neg, 0, 1);
51
        Mat data = catMat(pos, neg);
52
        Mat labels = catMat(Mat::ones(npos, 1, CV_32FC1), Mat::ones(nneg, 1, CV_32FC1) * -1);
53
        cout << data.rows << " " << data.cols << endl;
54
        Mat out(labels.rows, 1, CV_32FC1);
55
56
        classify_svm(data, labels, out);
57
58
        for (int i = 0; i < out.rows; i++) {
59
                cout << labels.at<float>(i, 0) << " " << out.at<float>(i, 0) << endl;
60
        }
61
}