1. 程式人生 > 其它 >OpenCV之頭像識別採集訓練資料

OpenCV之頭像識別採集訓練資料

一、概述

  案例:在進行人臉識別之前需要採集人臉資料進行訓練,下面就說說如何簡單的採集人臉資料。

  需要使用到的工具:

    1.級聯分類器--->識別頭像區域

    2.將識別的頭像區域儲存到磁碟

    3.將頭像資料的路徑和對應的標籤放入檔案中備用

二、程式碼示例

Face_Collect_Face_Data::Face_Collect_Face_Data(QWidget *parent)
    : MyGraphicsView{parent}
{
    this->setWindowTitle("採集人臉資料");
    QPushButton *btn = new
QPushButton(this); btn->setText("選擇視訊檔案採集人臉資料"); connect(btn,&QPushButton::clicked,[=](){ chooseVideo(); }); } void Face_Collect_Face_Data::chooseVideo(){ QString filePath = QFileDialog::getOpenFileName(this,"選擇視訊檔案","/Users/yangwei/Downloads/","資料檔案(*.mp4)"); qDebug()
<<filePath; saveCollectFaceData(filePath.toStdString().c_str()); } void Face_Collect_Face_Data::saveCollectFaceData(const char * filePath){ //級聯分類器檔案路徑 string haarFilePath = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_alt_tree.xml"; VideoCapture capture; capture.open(filePath);
if(!capture.isOpened()){ qDebug()<<"無法開啟視訊檔案"; return; } CascadeClassifier faceDetector;//例項化級聯分類器 faceDetector.load(haarFilePath); Mat frame; vector<Rect> faces; int count = 0; 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++){ //將識別到的人臉區域儲存起來 if(count%10==0){ Mat result; cv::resize(frame(faces[i]),result,Size(100,100)); String path = format("/Users/yangwei/Documents/tony/opencv/myfaces/face_%d.jpg", count); cout << path<<endl; imwrite(path, result); } //將識別到的人臉框繪製出來 rectangle(frame,faces[i],Scalar(255,0,0),3,8); } imshow("frame",frame); int key = waitKey(1); if(key==27){ break; } count ++; } }

三、演示圖片