OpenCV之人脸识别(训练模型-->保存模型--->使用模型)

一、概述

  案例:使用OpenCV训练模型并将自己识别出来。其中包含了训练模型、保存模型、使用模型

  训练模型步骤

    1.加载采集好的数据文件,并将图片和图片对一个的标签存入vector

    2.准备一个测试数据,ps:从采集的文件中取

    3.实例化特征脸人脸识别模型EigenFaceRecognizer model

    4.训练模型model->trans

  保存模型及加载模型

    1.保存模型:model->save(模型路径)

    2.加载模型:Ptr<BasicFaceRecognizer> model =Algorithm::load<EigenFaceRecognizer>("模型路径");

  使用训练好的模型进行人脸识别步骤

    1.实例化并加载训练好的人脸数据模型

    2.使用级联分类器加载人脸模型

    3.实例化VideoCapture加载视频文件(或打开摄像头)

    4.while循环读取frame

      4.1在frame中找到人脸roi区域

      4.2.对roi区域灰度化

      4.3.对roi区域执行model->predict(roi)进行预测

      4.4.如果预测结果为101(我自己人脸的标签值),则说明把我自己识别出来了。

      4.5循环4步骤,直到视频播放结束(或关闭摄像头)

二、代码示例

Face_Recognizer_My_Face::Face_Recognizer_My_Face(QWidget *parent)
    : MyGraphicsView{parent}
{
    this->setWindowTitle("人脸识别小案例");
    QPushButton *btn = new QPushButton(this);
    btn->setText("选择视频文件");
    connect(btn,&QPushButton::clicked,[=](){
        chooseVideoFile();
    });
}


void Face_Recognizer_My_Face::chooseVideoFile(){
    QString filePath = QFileDialog::getOpenFileName(this,"选择视频文件","/Users/yangwei/Downloads/","数据文件(*.mp4)");
    qDebug()<<filePath;
    recognizerMyFace(filePath.toStdString().c_str());
}

void Face_Recognizer_My_Face::recognizerMyFace(const char * filePath){
    //准备训练数据
    string transFileName = "/Users/yangwei/Documents/tony/opencv/myfaces/targetData.txt";
    ifstream file(transFileName,ifstream::in);
    if(!file){
        qDebug()<<"准备训练数据";
        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()));
    }
    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];

    //使用特征脸进行数据检验
//    Ptr<BasicFaceRecognizer> model = EigenFaceRecognizer::create();
//    //训练
//    model->train(images,labels);

//    model->save("/Users/yangwei/Documents/tony/opencv/myfaces/test.txt");

    Ptr<BasicFaceRecognizer> model =Algorithm::load<EigenFaceRecognizer>("/Users/yangwei/Documents/tony/opencv/myfaces/test.txt");


    //预测
    int predictLabel = model->predict(testMat);
    cout <<"测试标签:"<<testLabel<<",预测标签:"<<predictLabel<<endl;;

    //使用级联分类器找到人脸区域
    string faceFilePath = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_alt_tree.xml";
    CascadeClassifier faceDetector;
    faceDetector.load(faceFilePath);


    VideoCapture capture;
    capture.open(filePath);
    if(!capture.isOpened()){
        qDebug()<<"打开视频文件失败";
        return;
    }

    Mat frame,dst;
    vector<Rect> faces;
    while(capture.read(frame)){
        faceDetector.detectMultiScale(frame,faces,1.1,3,0,Size(100,100),Size(400,400));
        for(int i=0;i<faces.size();i++){
            Mat roi = frame(faces[i]);
            cvtColor(roi,dst,COLOR_BGR2GRAY);
            cv::resize(dst,testMat,Size(100,100));
            int label = model->predict(testMat);
            rectangle(frame,faces[i],Scalar(255,0,0),2,8,0);
            putText(frame, format("i'm %s", (label == 110 ? "yw.yang" : "Unknow")), faces[i].tl(), FONT_HERSHEY_PLAIN, 1.0, Scalar(0, 0, 255), 2, 8);
        }
        imshow("frame",frame);
        int key = waitKey(1);
        if(key==27){
            break;
        }

    }

}

  

  

三、演示图像

  

 

posted on 2022-05-09 13:55  飘杨......  阅读(2188)  评论(0编辑  收藏  举报