基于openCV的视频人脸识别 《演员的诞生》

1.准备训练数据

  网络上下载(训练数据量大时,通过爬虫获取)目标的图片:



  运用以下代码将原图中的 人脸头像识别、提取、调整大小(这里是150*200),并分别保存。
   运行环境:win7 64+VS2013+openCV3.1。
   (PS:抱怨下vs和opencv的版本密切相关,注意安装配置)
  



    

[cpp]  view plain  copy
  1. #include <opencv2\opencv.hpp>  
  2. #include <iostream>  
  3. #include <stdio.h>  
  4. #include <opencv2/core/core.hpp>  
  5. #include <opencv2/highgui/highgui.hpp>  
  6. #include <opencv2/imgproc/imgproc.hpp>  
  7. #include <opencv2/opencv.hpp>  
  8.   
  9. #include <opencv2/imgproc/types_c.h>    
  10. #include <opencv2/videoio/videoio_c.h>    
  11. #include <opencv2/highgui/highgui_c.h>  
  12.   
  13. using namespace std;  
  14. using namespace cv;  
  15.   
  16. /** Function Headers */  
  17. void detectAndDisplay(Mat frame);  
  18.   
  19. /** Global variables */  
  20. String face_cascade_name = "F:\\Downloads\\opencv_build\\install\\etc\\haarcascades\\haarcascade_frontalface_default.xml";  
  21. String eyes_cascade_name = "F:\\Downloads\\opencv_build\\install\\etc\\haarcascades\\haarcascade_eye_tree_eyeglasses.xml";  
  22. CascadeClassifier face_cascade;   //定义人脸分类器  
  23. CascadeClassifier eyes_cascade;   //定义人眼分类器  
  24. String window_name = "Capture - Face detection";  
  25.   
  26.   
  27. /** @function main */  
  28. int main(void)  
  29. {  
  30.     //-- 1. Load the cascades  
  31.     if (!face_cascade.load(face_cascade_name)){ printf("--(!)Error loading face cascade\n"); return -1; };  
  32.     if (!eyes_cascade.load(eyes_cascade_name)){ printf("--(!)Error loading eyes cascade\n"); return -1; };  
  33.   
  34.   
  35.     //-- 2. 遍历原图像文件夹  
  36.     vector<String> files;  
  37.     glob("D:\\training\\liudh_before\\*.jpg", files, true);  
  38.   
  39.     //-- 3. 识别、提取,并保存头像至新文件夹。图片均调整为150x200像素  
  40.     for (int i = 0; i < files.size(); i++)  
  41.     {  
  42.         //Image processing    
  43.         Mat img = imread(files[i]); //读取文件  
  44.         cout << files[i] << '\n';  
  45.         detectAndDisplay(img);     //提取头像  
  46.   
  47.         waitKey(1000);  
  48.     }  
  49. }  
  50.   
  51. /** @function detectAndDisplay */  
  52. void detectAndDisplay(Mat frame)  
  53. {  
  54.     static int count = 0;  
  55.     std::vector<Rect> faces;  
  56.     Mat frame_gray;  
  57.     Mat MyFace;  
  58.   
  59.     cvtColor(frame, frame_gray, COLOR_BGR2GRAY);  
  60.     //equalizeHist(frame_gray, frame_gray);  
  61.   
  62.     //imshow("2", frame_gray);  
  63.   
  64.     //-- Detect faces  
  65.     face_cascade.detectMultiScale(frame_gray, faces, 1.1);  
  66.   
  67.     for (size_t i = 0; i < faces.size(); i++)  //人脸数目  
  68.     {  
  69.         Mat faceROI = frame_gray(faces[i]);  
  70.         rectangle(frame, faces[i], Scalar(255, 0, 0), 2, 8, 0);  
  71.   
  72.         if (faceROI.cols > 80){  
  73.             resize(faceROI, MyFace, Size(150, 200));  
  74.             string  str = format("D:\\training\\liudh\\MyFcae%d.jpg", count);  
  75.             cout << " 保存图片" << count<<endl;  
  76.             imwrite(str, MyFace);  
  77.             imshow("ii", MyFace);  
  78.         }  
  79.         count++;  
  80.   
  81.     }  
  82.     //-- Show what you got  
  83.     namedWindow(window_name, 2);  
  84.     imshow(window_name, frame);  
  85. }  

2.制作标签文件CSV

进入命令行,输入命令 di /b/s *.pgm *jpg >at.txt

会在训练数据文件夹下生成一个at.txt文件,但这文件内只有数据,没有标签。(笨办法是将数据拷贝到execl表格中生成标签)
最终生成文件内容如下所示:

也可以通过create_csv.py制作标签(注意修改文件中的目录路径)

[python]  view plain  copy
  1. #!/usr/bin/env python  
  2.   
  3. import sys  
  4. import os.path  
  5.   
  6. # This is a tiny script to help you creating a CSV file from a face  
  7. # database with a similar hierarchie:  
  8. #  
  9. #  philipp@mango:~/facerec/data/at$ tree  
  10. #  .  
  11. #  |-- README  
  12. #  |-- s1  
  13. #  |   |-- 1.pgm  
  14. #  |   |-- ...  
  15. #  |   |-- 10.pgm  
  16. #  |-- s2  
  17. #  |   |-- 1.pgm  
  18. #  |   |-- ...  
  19. #  |   |-- 10.pgm  
  20. #  ...  
  21. #  |-- s40  
  22. #  |   |-- 1.pgm  
  23. #  |   |-- ...  
  24. #  |   |-- 10.pgm  
  25. #  
  26.   
  27. if __name__ == "__main__":  
  28.   
  29.     #if len(sys.argv) != 2:  
  30.     #    print "usage: create_csv <base_path>"  
  31.     #    sys.exit(1)  
  32.   
  33.     #BASE_PATH=sys.argv[1]  
  34.     BASE_PATH="D:/att_faces"  
  35.       
  36.     SEPARATOR=";"  
  37.   
  38.     fh = open("D:/att_faces/at.txt",'w')  
  39.   
  40.     label = 1   
  41.     for dirname, dirnames, filenames in os.walk(BASE_PATH):  
  42.         for subdirname in dirnames:  
  43.             subject_path = os.path.join(dirname, subdirname)  
  44.             for filename in os.listdir(subject_path):  
  45.                 abs_path = "%s/%s" % (subject_path, filename)  
  46.                 #print "%s%s%d" % (abs_path, SEPARATOR, label)  
  47.                 fh.write(abs_path)  
  48.                 fh.write(SEPARATOR)  
  49.                 fh.write(str(label))  
  50.                 fh.write("\n")        
  51.             label = label + 1  
  52.     fh.close()  

3. 训练模型

    EigenFace和FisherFace的训练图像和测试图像都必须是灰度图,而且是经过归一化裁剪过的。
   
    1.运用alt.txt文件,加载训练数据;提取数据和标签

   2.根据FaceRecognizer三种训练模型进行训练;

   3.保存训练数据及模型(xml)

[cpp]  view plain  copy
  1. //#include "stdafx.h"  
  2. #include <opencv2/opencv.hpp>  
  3. #include <iostream>  
  4. #include <fstream>  
  5. #include <sstream>  
  6. #include <math.h>  
  7.   
  8. #include <opencv2/face.hpp>  
  9. #include <opencv2/face/facerec.hpp>  
  10. #include <iostream>  
  11. #include <stdio.h>  
  12. #include "opencv2/core.hpp"  
  13. #include "opencv2/core/utility.hpp"  
  14. #include "opencv2/core/ocl.hpp"  
  15. #include "opencv2/imgcodecs.hpp"  
  16. #include "opencv2/highgui.hpp"  
  17. #include "opencv2/features2d.hpp"  
  18. #include "opencv2/calib3d.hpp"  
  19. #include "opencv2/imgproc.hpp"  
  20. #include"opencv2/flann.hpp"  
  21. #include"opencv2/xfeatures2d.hpp"  
  22. #include"opencv2/ml.hpp"  
  23. #include"opencv2/face.hpp"  
  24. #include"opencv2/face/facerec.hpp"  
  25. #include"opencv2/objdetect.hpp"  
  26.   
  27. using namespace cv;  
  28. using namespace std;  
  29. using namespace face;  
  30.   
  31. static Mat norm_0_255(InputArray _src) {  
  32.     Mat src = _src.getMat();  
  33.     // 创建和返回一个归一化后的图像矩阵:  
  34.     Mat dst;  
  35.     switch (src.channels()) {  
  36.     case1:  
  37.         cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);  
  38.         break;  
  39.     case3:  
  40.         cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);  
  41.         break;  
  42.     default:  
  43.         src.copyTo(dst);  
  44.         break;  
  45.     }  
  46.     return dst;  
  47. }  
  48.   
  49. //使用CSV文件去读图像和标签,主要使用stringstream和getline方法  
  50. static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {  
  51.     std::ifstream file(filename.c_str(), ifstream::in);  
  52.     if (!file) {  
  53.         string error_message = "No valid input file was given, please check the given filename.";  
  54.         CV_Error(CV_StsBadArg, error_message);  
  55.     }  
  56.     string line, path, classlabel;  
  57.     while (getline(file, line)) {  
  58.         stringstream liness(line);  
  59.         getline(liness, path, separator);  
  60.         getline(liness, classlabel);  
  61.         if (!path.empty() && !classlabel.empty()) {  
  62.             images.push_back(imread(path, 0));  
  63.             labels.push_back(atoi(classlabel.c_str()));  
  64.         }  
  65.     }  
  66. }  
  67.   
  68.   
  69. int main()  
  70. {  
  71.   
  72.     //读取你的CSV文件路径.  
  73.     //string fn_csv = string(argv[1]);  
  74.     string fn_csv = "D:\\training\\at.txt";  
  75.   
  76.     // 2个容器来存放图像数据和对应的标签  
  77.     vector<Mat> images;  
  78.     vector<int> labels;  
  79.     // 读取数据. 如果文件不合法就会出错  
  80.     // 输入的文件名已经有了.  
  81.     try  
  82.     {  
  83.         read_csv(fn_csv, images, labels);  
  84.     }  
  85.     catch (cv::Exception& e)  
  86.     {  
  87.         cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;  
  88.         // 文件有问题,我们啥也做不了了,退出了  
  89.         exit(1);  
  90.     }  
  91.     // 如果没有读取到足够图片,也退出.  
  92.     if (images.size() <= 1) {  
  93.         string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";  
  94.         CV_Error(CV_StsError, error_message);  
  95.     }  
  96.   
  97.     // 下面的几行代码仅仅是从你的数据集中移除最后一张图片  
  98.     //[gm:自然这里需要根据自己的需要修改,他这里简化了很多问题]  
  99.     Mat testSample = images[images.size() - 1];  
  100.     int testLabel = labels[labels.size() - 1];  
  101.     images.pop_back();  
  102.     labels.pop_back();  
  103.     // 下面几行创建了一个特征脸模型用于人脸识别,  
  104.     // 通过CSV文件读取的图像和标签训练它。  
  105.     // T这里是一个完整的PCA变换  
  106.     //如果你只想保留10个主成分,使用如下代码  
  107.     //      cv::createEigenFaceRecognizer(10);  
  108.     //  
  109.     // 如果你还希望使用置信度阈值来初始化,使用以下语句:  
  110.     //      cv::createEigenFaceRecognizer(10, 123.0);  
  111.     //  
  112.     // 如果你使用所有特征并且使用一个阈值,使用以下语句:  
  113.     //      cv::createEigenFaceRecognizer(0, 123.0);  
  114.        
  115.     Ptr <FaceRecognizer> model = createEigenFaceRecognizer(10);  
  116.     model->train(images, labels);  
  117.     model->save("MyFacePCAModel.xml");  
  118.   
  119.     Ptr <FaceRecognizer> model1 = createFisherFaceRecognizer(10);  
  120.     model1->train(images, labels);  
  121.     model1->save("MyFaceFisherModel.xml");  
  122.   
  123.     Ptr <FaceRecognizer> model2 = createLBPHFaceRecognizer(10);  
  124.     model2->train(images, labels);  
  125.     model2->save("MyFaceLBPHModel.xml");  
  126.   
  127.     // 下面对测试图像进行预测,predictedLabel是预测标签结果  
  128.     int predictedLabel = model->predict(testSample);  
  129.     int predictedLabel1 = model1->predict(testSample);  
  130.     int predictedLabel2 = model2->predict(testSample);  
  131.   
  132.     // 还有一种调用方式,可以获取结果同时得到阈值:  
  133.     //      int predictedLabel = -1;  
  134.     //      double confidence = 0.0;  
  135.     //      model->predict(testSample, predictedLabel, confidence);  
  136.   
  137.     string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);  
  138.     string result_message1 = format("Predicted class = %d / Actual class = %d.", predictedLabel1, testLabel);  
  139.     string result_message2 = format("Predicted class = %d / Actual class = %d.", predictedLabel2, testLabel);  
  140.     cout << result_message << endl;  
  141.     cout << result_message1 << endl;  
  142.     cout << result_message2 << endl;  
  143.   
  144.     while (1);  
  145.     //waitkey只对imshow有效  
  146.     //if (waitKey(10) == 17) return 0;; //  
  147.     //return 0;  
  148. }  
4. 预测数据

     加载上述训练好的训练模型,并进行估值
   
      
[cpp]  view plain  copy
  1. #include<opencv2\opencv.hpp>  
  2. #include<iostream>  
  3. #include <opencv2\opencv.hpp>  
  4. #include <iostream>  
  5. #include <stdio.h>  
  6. #include <opencv2/core/core.hpp>  
  7. #include <opencv2/highgui/highgui.hpp>  
  8. #include <opencv2/imgproc/imgproc.hpp>  
  9. #include <opencv2/opencv.hpp>  
  10.   
  11. #include <opencv2/imgproc/types_c.h>    
  12. #include <opencv2/videoio/videoio_c.h>    
  13. #include <opencv2/highgui/highgui_c.h>  
  14. #include <opencv2/face.hpp>  
  15. #include <opencv2/face/facerec.hpp>  
  16.   
  17. using namespace std;  
  18. using namespace cv;  
  19. using namespace face;  
  20.   
  21. int main()  
  22. {  
  23.   
  24.     VideoCapture cap("D:\\pics\\wjd.avi");    //打开默认摄像头  
  25.     if (!cap.isOpened())  
  26.     {  
  27.         return -1;  
  28.     }  
  29.   
  30.     Mat frame;  
  31.     Mat edges;  
  32.     Mat gray;  
  33.   
  34.     CascadeClassifier cascade;  
  35.     bool stop = false;  
  36.     //训练好的文件名称,放置在可执行文件同目录下  
  37.     cascade.load("D:\\training\\training_data\\haarcascade_frontalface_default.xml");  
  38.   
  39.     Ptr<FaceRecognizer> modelPCA = createEigenFaceRecognizer();  
  40.     modelPCA->load("D:\\training\\training_data\\MyFacePCAModel.xml");  
  41.   
  42.     while (!stop)  
  43.     {  
  44.         cap >> frame;  
  45.         //frame = imread("D:\\pics\\test3.jpg");  
  46.         if (frame.empty()) break;  
  47.         //建立用于存放人脸的向量容器  
  48.         vector<Rect> faces(0);  
  49.   
  50.         cvtColor(frame, gray, CV_BGR2GRAY);  
  51.         //改变图像大小,使用双线性差值  
  52.         //resize(gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR);  
  53.         //变换后的图像进行直方图均值化处理  
  54.         equalizeHist(gray, gray);  
  55.   
  56.         cascade.detectMultiScale(gray, faces,  
  57.             1.1);  
  58.             //, 2, 0  
  59.             //|CV_HAAR_FIND_BIGGEST_OBJECT  
  60.             //|CV_HAAR_DO_ROUGH_SEARCH  
  61.             //| CV_HAAR_SCALE_IMAGE,  
  62.             //Size(30, 30));  
  63.   
  64.         Mat face;  
  65.         Point text_lb;  
  66.   
  67.         for (size_t i = 0; i < faces.size(); i++)  
  68.         {  
  69.             if (faces[i].height > 0 && faces[i].width > 0)  
  70.             {  
  71.                 face = gray(faces[i]);  
  72.                 text_lb = Point(faces[i].x, faces[i].y);  
  73.   
  74.                 rectangle(frame, faces[i], Scalar(255, 0, 0), 1, 8, 0);  
  75.             }  
  76.         }  
  77.         imshow("face1", frame);  
  78.   
  79.         Mat face_test;  
  80.   
  81.         int predictPCA = 0;  
  82.         if (face.rows >= 80)  
  83.         {  
  84.             resize(face, face_test, Size(150, 200));  
  85.   
  86.         }  
  87.         //Mat face_test_gray;  
  88.         //cvtColor(face_test, face_test_gray, CV_BGR2GRAY);  
  89.   
  90.         if (!face_test.empty())  
  91.         {  
  92.             //测试图像应该是灰度图  
  93.             predictPCA = modelPCA->predict(face_test);  
  94.         }  
  95.   
  96.         cout << predictPCA << endl;  
  97.         if (predictPCA == 1)  
  98.         {  
  99.             string name = "liangcw";  
  100.             putText(frame, name, text_lb, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255));  
  101.         }  
  102.         else if (predictPCA == 2)  
  103.         {  
  104.             string name = "liudh";  
  105.             putText(frame, name, text_lb, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255));  
  106.         }  
  107.         else if (predictPCA == 3)  
  108.         {  
  109.             string name = "zyw";  
  110.             putText(frame, name, text_lb, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255));  
  111.         }  
  112.         else if (predictPCA == 4)  
  113.         {  
  114.             string name = "zzy";  
  115.             putText(frame, name, text_lb, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255));  
  116.         }  
  117.         imshow("face2", frame);  
  118.         //waitKey(0);  
  119.   
  120.         if (waitKey(10) >= 0)  
  121.             stop = true;  
  122.     }  
  123.   
  124.     return 0;  
  125. }  


5. 测试结果

    优酷下载了《演员的诞生》某片段,转成avi格式,能识别出视频中的周一围、章子怡等



6. 结论

    基于openCV人脸识别的相关结构体(CascaderClassify、FacerRecognizer),训练数据越大识别效果才越好

    人脸检测相关模型,如正脸、侧脸、眼睛、鼻子都是分开的,有没有联合一起的??

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值