opencv svm分類

zipfeel發表於2017-08-25
void svm()
{
    // 視覺表達資料的設定
    int width = 512, height = 512;
    Mat image = Mat::zeros(height, width, CV_8UC3);

    //建立訓練資料
    int labels[4] = { 1, -1, -1, -1 };
    Mat labelsMat(4, 1, CV_32SC1, labels);
    InputArray svmOutput(labelsMat);

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

    //設定支援向量機的引數
    Ptr<SVM> svm = SVM::create();
    svm->setType(SVM::C_SVC);
    svm->setKernel(SVM::LINEAR);
    svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));

    // 訓練支援向量機
    svm->train(svmInput, ROW_SAMPLE, svmOutput);

    Vec3b green(0, 255, 0), blue(255, 0, 0);
    //顯示由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;
        }

    //顯示訓練資料
    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);

    //顯示支援向量
    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);

    return ;
}

void svm2()
{
    #define NTRAINING_SAMPLES   100         // 每類訓練樣本的數量
    #define FRAC_LINEAR_SEP     0.9f        // 部分(Fraction)線性可分的樣本組成部分

    //設定視覺表達的引數
    const int WIDTH = 512, HEIGHT = 512;
    Mat I = Mat::zeros(HEIGHT, WIDTH, CV_8UC3);

    //隨機建立訓練資料
    Mat trainData(2 * NTRAINING_SAMPLES, 2, CV_32FC1);
    InputArray svmInput(trainData);
    Mat labels(2 * NTRAINING_SAMPLES, 1, CV_32SC1);
    InputArray svmOutput(labels);

    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

    //設定支援向量機的引數
    Ptr<SVM> svm = SVM::create();
    svm->setType(SVM::C_SVC);
    svm->setKernel(SVM::LINEAR);
    svm->setC(0.1);
    svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, (int)1e7, 1e-6));

    //訓練支援向量機
    cout << "Starting training process" << endl;
    svm->train(svmInput, ROW_SAMPLE, svmOutput);
    cout << "Finished training process" << endl;

    //標出決策區域
    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;
        }

    //顯示訓練資料
    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);
    }

    //顯示支援向量
    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);

    return ;
}

相關文章