1. 程式人生 > 其它 >OpenCV之使用FisherFaceRecognizer來實現人臉識別

OpenCV之使用FisherFaceRecognizer來實現人臉識別

一、概述

  案例:使用FisherFaceRecognizer來實現人臉識別

  主要程式碼

Ptr<BasicFaceRecognizer> model = FisherFaceRecognizer::create();
    model->train(images,labels);//訓練

    //預測
    int predictLabel = model->predict(testMat);

  實現步驟

    1.準備訓練用的人臉資料及標籤資料

    2.準備測試用的測試資料

    3.例項化BasicFaceRecognizer(人臉識別例項)-->model

    4.利用model->trans進行資料的訓練

    5.利用model->predict進行資料的預測

    6.比較測試圖片對應的標籤和預測圖片結果對應的標籤是否一致,如果一直說明人臉識別成功,否則人臉識別失敗。

二、程式碼示例

 ifstream file(filePath,ifstream::in);
    if(!file){
        qDebug()<<"file count not found";
        return;
    }
    //準備資料階段
    string line ,path,classLabel;
    vector
<Mat> images; vector<int> labels; while(getline(file,line)){ stringstream liness(line); getline(liness,path,' '); getline(liness,classLabel); images.push_back(imread(path,0)); labels.push_back(atoi(classLabel.c_str())); } cout <<"
準備資料完成:"<<images.size()<<endl; //檢測準備的訓練資料是否正常 if(images.size()<1||labels.size()<1){ qDebug()<<"準備的資料異常"; return; } //測試查樣本資料的寬高 int width = images[0].cols; int height = images[0].rows; cout << "width:"<<width<<",height:"<<height<<endl; //準備測試資料 Mat testMat = images[images.size()-1]; int testLabel = labels[labels.size()-1]; images.pop_back(); labels.pop_back(); //建立Fisher人臉識別例項,並開始訓練資料 Ptr<BasicFaceRecognizer> model = FisherFaceRecognizer::create(); model->train(images,labels);//訓練 //預測 int predictLabel = model->predict(testMat); //如果預測的標籤值和測試的標籤值一致就說明人臉識別是成功的。 cout <<"testLabel:"<<testLabel <<",predictLabel:"<<predictLabel<<endl;

三、演示影象