opencv的人臉識別

opencv2.4提出了一個新的關于人臉識別的類FaceRecognizer,可以用它進行人臉識別實驗。當前主要的算法有Eigenfaces ,Fisherfaces ,Local Binary Patterns Histograms。

人臉識別

人臉識別對于人來說很簡單,出生三天的baby就可以分辨出周圍的人臉了。那么計算機是怎么做到的呢?其實我們對于人怎么識別出人臉都知之甚少,是根據內部特征(眼睛,鼻子,嘴巴)還是外部特征(頭型,發際線)?我們怎么分析一張圖片,大腦怎么編碼它?經證實,我們的大腦根據不同的局部特征(線,邊緣,角度)有不同的神經細胞分析。顯然我們沒有把世界看成零散的塊塊,我們的視覺皮層必須以某種方式把不同的信息來源轉化成有用的模式。自動人臉識別就是從圖片中抽取這些有意義的特征,然后用某種方式來形成分類。
基于幾何特征的人臉識別可能是最直觀的識別方式了。起初的一種識別方式這樣表述:標記一些點(眼睛,耳朵,鼻子的位置),構建出特征向量(點之間的距離和角度),然后計算訓練圖片的特征向量的歐氏距離來進行識別。這種方法對于光照變化具有魯棒性,但有個巨大的缺陷:即使是目前比較先進的算法,標記點的確定也是很復雜的,而且,也有論文表示,僅僅是幾何特征可能沒有涵蓋足夠的識別信息。
Eigenfaces方法描述了一個全面的方法來識別人臉:一個臉部圖像由高維圖像空間表示成低維的一個點表示,從而讓分類變得簡單。低維子空間由主成分分析PCA得到,這種變化對于標準點的重構是最優的,但沒有分類標記。那么如果當變化僅由外部因素產生,比如光照,那么這樣的降維方法是不可能拿來分類的。因此,提出線性判別分析來進行識別。
還有局部特征抽取的方法。為了避免圖像局部區域輸入數據的高維度,抽取的特征需要對遮擋,光照,小樣本有更好的魯棒性。用于局部特征抽取的算法有比如gabor小波,離散余弦變換和局部二值特征LBP,至于到底哪種才是表示空間信息的局部特征抽取的最佳方式,仍是個開放性的研究。

人臉數據庫

你可以創建自己的數據庫或者幾個網上可用的數據庫。

  • AT&T Facedatabase也叫ORL數據庫,40個人不同的10張照片,基于不同的時間,光照變化,面部表情(眼睛閉到沒,笑沒笑),面部細節(帶沒帶眼鏡兒)。所有圖片都是在黑暗的背景下拍攝的直立的正臉。
    *Yale Facedatabase A也叫Yalefaces。ORL數據庫比較適合初始的測試,是一個相當簡易的數據庫,Eigenfaces方法就已經有大概97%的識別率了,所以對于其他方法,你也看不到有長進了。Yale就對此很友好了,因為識別問題更加復雜。
    *Extended Yale Facedatabase B這個數據庫有點大喲,不適合初學者,而且這個數據庫重點是考察抽取的特征是否對光照有魯棒性,圖片之間幾乎沒什么變化。初學者,還是建議用ORL。

準備數據

得到數據之后,需要把它讀到程序里面來,這里用的是CSV文件格式,基本上所有的CSV文件都需要包括文件名和分類標記,像這樣:/path/to/image.ext;0
/path/to/image.ext是圖片的路徑,Windows系統就是C:/faces/person0/image0.jpg,然后分號隔開,用整數0標記圖片,表示所屬的類別。
下載ORL,CSV文件格式如下:

./at/s1/1.pgm;0
./at/s1/2.pgm;0
...
./at/s2/1.pgm;1
./at/s2/2.pgm;1
...
./at/s40/1.pgm;39
./at/s40/2.pgm;39

假設數據存在D:/data/at,CSV文件存在D:/data/at.txt. 你需要把./替換成D:/data/.成功建立好CSV后,可以試著運行它:
facerec_demo.exe D:/data/at.txt

創建CSV

用不著手動輸入產生CSV文件,官方源碼有python的腳本自動生成,在..\opencv_contrib-master\modules\face\samples\etc\create_csv.py,這里貼出來。

#!/usr/bin/env python

import sys
import os.path

# This is a tiny script to help you creating a CSV file from a face
# database with a similar hierarchie:
#
#  philipp@mango:~/facerec/data/at$ tree
#  .
#  |-- README
#  |-- s1
#  |   |-- 1.pgm
#  |   |-- ...
#  |   |-- 10.pgm
#  |-- s2
#  |   |-- 1.pgm
#  |   |-- ...
#  |   |-- 10.pgm
#  ...
#  |-- s40
#  |   |-- 1.pgm
#  |   |-- ...
#  |   |-- 10.pgm
#

if __name__ == "__main__":

    if len(sys.argv) != 2:
        print("usage: create_csv <base_path>")
        sys.exit(1)

    BASE_PATH=sys.argv[1]
    SEPARATOR=";"

    label = 0
    for dirname, dirnames, filenames in os.walk(BASE_PATH):
        for subdirname in dirnames:
            subject_path = os.path.join(dirname, subdirname)
            for filename in os.listdir(subject_path):
                abs_path = "%s/%s" % (subject_path, filename)
                print("%s%s%d" % (abs_path, SEPARATOR, label))
            label = label + 1

看到沒,你的文件目錄格式要像代碼注釋里那樣才行,然后調用create_csv.py at,at就是你存放圖片的根目錄。

Eigenfaces

輸入圖片表示方式的問題在于它的高維度,pq大小的二維灰度圖片跨域了m=pq維的向量空間,因此一個100*100像素的圖片就已經有10000維的空間了。那么,所有維度都同樣有用嗎?我們可以這樣,如果數據有任何偏差,就尋找涵蓋大部分信息的成分。哈哈哈,那就是PCA勒!把一系列可能相關的變量轉換成低維的不相關變量。也就是說,高維數據經常用相關變量來描述,而大部分信息被其中部分有意義的變量包括。PCA尋找數據最大方差的自然基,稱為主成分。

Eigenfaces的算法流程

X={x1,x2,…,xn} 是一組隨機向量
1.計算均值μ

image.png

2.去中心化,計算協方差矩陣S
image.png

3.計算矩陣S的特征值λi和特征向量vi
image.png

4.根據特征值對特征向量降序排列,k個主成分就是k個最大的特征值的特征向量。
觀察量x的k個主成分:
image.png

PCA基的重構:
image.png

其中,W=(v1,v2,…,vk).
Eigenfaces然后執行識別:

  • 投射所有訓練樣本到PCA子空間
  • 投射所有測試樣本到PCA子空間
  • 尋找訓練樣本和測試樣本的投射空間的最近鄰
    還有個問題要解決,假設我們有100*100的400張圖片,PCA要解決方差矩陣S=XXT,這里的X尺寸為10000*400.最后得到的是10000*10000的矩陣,大概0.8個G,這樣就很沒有靈性,可以這樣做,先考慮S=XTX ,這樣計算維度就大大減小了。
    image.png

    然后等式左右都左乘X,就可以巧妙計算S的特征向量了,可以看到,XTX和XXT特征值是相同的。
    image.png

opencv里的Eigenfaces

源碼見..\opencv_contrib-master\modules\face\samples\facerec_eigenfaces.cpp,在opencv的contrib模塊里面,這里貼出來。

/*
 * Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
 * Released to public domain under terms of the BSD Simplified license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the organization nor the names of its contributors
 *     may be used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 *   See <http://www.opensource.org/licenses/bsd-license>
 */

#include "opencv2/core.hpp"
#include "opencv2/face.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"

#include <iostream>
#include <fstream>
#include <sstream>

using namespace cv;
using namespace cv::face;
using namespace std;

static Mat norm_0_255(InputArray _src) {
    Mat src = _src.getMat();
    // Create and return normalized image:
    Mat dst;
    switch(src.channels()) {
    case 1:
        cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
        break;
    case 3:
        cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
        break;
    default:
        src.copyTo(dst);
        break;
    }
    return dst;
}

static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
    std::ifstream file(filename.c_str(), ifstream::in);
    if (!file) {
        string error_message = "No valid input file was given, please check the given filename.";
        CV_Error(Error::StsBadArg, error_message);
    }
    string line, path, classlabel;
    while (getline(file, line)) {
        stringstream liness(line);
        getline(liness, path, separator);
        getline(liness, classlabel);
        if(!path.empty() && !classlabel.empty()) {
            images.push_back(imread(path, 0));
            labels.push_back(atoi(classlabel.c_str()));
        }
    }
}

int main(int argc, const char *argv[]) {
    // Check for valid command line arguments, print usage
    // if no arguments were given.
    if (argc < 2) {
        cout << "usage: " << argv[0] << " <csv.ext> <output_folder> " << endl;
        exit(1);
    }
    string output_folder = ".";
    if (argc == 3) {
        output_folder = string(argv[2]);
    }
    // Get the path to your CSV.
    string fn_csv = string(argv[1]);
    // These vectors hold the images and corresponding labels.
    vector<Mat> images;
    vector<int> labels;
    // Read in the data. This can fail if no valid
    // input filename is given.
    try {
        read_csv(fn_csv, images, labels);
    } catch (cv::Exception& e) {
        cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
        // nothing more we can do
        exit(1);
    }
    // Quit if there are not enough images for this demo.
    if(images.size() <= 1) {
        string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
        CV_Error(Error::StsError, error_message);
    }
    // Get the height from the first image. We'll need this
    // later in code to reshape the images to their original
    // size:
    int height = images[0].rows;
    // The following lines simply get the last images from
    // your dataset and remove it from the vector. This is
    // done, so that the training data (which we learn the
    // cv::BasicFaceRecognizer on) and the test data we test
    // the model with, do not overlap.
    Mat testSample = images[images.size() - 1];
    int testLabel = labels[labels.size() - 1];
    images.pop_back();
    labels.pop_back();
    // The following lines create an Eigenfaces model for
    // face recognition and train it with the images and
    // labels read from the given CSV file.
    // This here is a full PCA, if you just want to keep
    // 10 principal components (read Eigenfaces), then call
    // the factory method like this:
    //
    //      EigenFaceRecognizer::create(10);
    //
    // If you want to create a FaceRecognizer with a
    // confidence threshold (e.g. 123.0), call it with:
    //
    //      EigenFaceRecognizer::create(10, 123.0);
    //
    // If you want to use _all_ Eigenfaces and have a threshold,
    // then call the method like this:
    //
    //      EigenFaceRecognizer::create(0, 123.0);
    //
    Ptr<EigenFaceRecognizer> model = EigenFaceRecognizer::create();
    model->train(images, labels);
    // The following line predicts the label of a given
    // test image:
    int predictedLabel = model->predict(testSample);
    //
    // To get the confidence of a prediction call the model with:
    //
    //      int predictedLabel = -1;
    //      double confidence = 0.0;
    //      model->predict(testSample, predictedLabel, confidence);
    //
    string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
    cout << result_message << endl;
    // Here is how to get the eigenvalues of this Eigenfaces model:
    Mat eigenvalues = model->getEigenValues();
    // And we can do the same to display the Eigenvectors (read Eigenfaces):
    Mat W = model->getEigenVectors();
    // Get the sample mean from the training data
    Mat mean = model->getMean();
    // Display or save:
    if(argc == 2) {
        imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
    } else {
        imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
    }
    // Display or save the Eigenfaces:
    for (int i = 0; i < min(10, W.cols); i++) {
        string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
        cout << msg << endl;
        // get eigenvector #i
        Mat ev = W.col(i).clone();
        // Reshape to original size & normalize to [0...255] for imshow.
        Mat grayscale = norm_0_255(ev.reshape(1, height));
        // Show the image & apply a Jet colormap for better sensing.
        Mat cgrayscale;
        applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
        // Display or save:
        if(argc == 2) {
            imshow(format("eigenface_%d", i), cgrayscale);
        } else {
            imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
        }
    }

    // Display or save the image reconstruction at some predefined steps:
    for(int num_components = min(W.cols, 10); num_components < min(W.cols, 300); num_components+=15) {
        // slice the eigenvectors from the model
        Mat evs = Mat(W, Range::all(), Range(0, num_components));
        Mat projection = LDA::subspaceProject(evs, mean, images[0].reshape(1,1));
        Mat reconstruction = LDA::subspaceReconstruct(evs, mean, projection);
        // Normalize the result:
        reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
        // Display or save:
        if(argc == 2) {
            imshow(format("eigenface_reconstruction_%d", num_components), reconstruction);
        } else {
            imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(), num_components), reconstruction);
        }
    }
    // Display if we are not writing to an output folder:
    if(argc == 2) {
        waitKey(0);
    }
    return 0;
}

先說說最關鍵的類EigenFaceRecognizer,包含在facerec.hpp頭文件,代碼里可直接包含face.hpp,他的繼承關系如下:


image.png

創建個Eigenfaces的對象

static Ptr<EigenFaceRecognizer> create(int num_components = 0, double threshold = DBL_MAX);

num_components就是主成分分析的成分個數,我們并不知道到底設多少才是最好的,這個依賴與你的輸入來試驗,保持80應該是比較合適的。threshold是你在預測圖片時的閾值,一般就是指預測和訓練圖片的距離的最大值。如果直接創建create(),那么默認num_components=0。

注意了!:

  • 訓練和預測都應該在灰度圖像上進行,用cvtColor轉換一下
  • 保證你的訓練和預測的圖片尺寸一致

在他爸爸BasicFaceRecognizer那里,有這些屬性和方法可以訪問:

public:
    /** @see setNumComponents */
    CV_WRAP int getNumComponents() const;
    /** @copybrief getNumComponents @see getNumComponents */
    CV_WRAP void setNumComponents(int val);
    /** @see setThreshold */
    CV_WRAP double getThreshold() const;
    /** @copybrief getThreshold @see getThreshold */
    CV_WRAP void setThreshold(double val);
    CV_WRAP std::vector<cv::Mat> getProjections() const;
    CV_WRAP cv::Mat getLabels() const;
    CV_WRAP cv::Mat getEigenValues() const;
    CV_WRAP cv::Mat getEigenVectors() const;
    CV_WRAP cv::Mat getMean() const;

    virtual void read(const FileNode& fn);
    virtual void write(FileStorage& fs) const;
    virtual bool empty() const;

    using FaceRecognizer::read;
    using FaceRecognizer::write;

他爺爺FaceRecognizer那里定義了train,update,predict,write,read等一些方法,后輩可以覆蓋。

注意了!

  • read,write保存模型數據可以用xml,yaml
  • update是指在原有訓練基礎上添加圖片和標簽進行更新,這個只有LBP才能用。

代碼里顯示了偽彩色圖,可以看到不同的Eigenfaces的灰度值是如何分布的,可見,Eigenfaces不僅編碼了面部特征,還有光照變化。


image.png

然后,我們可以利用低維近似來重構人臉,來看看一個好的重構需要多少Eigenfaces,分別使用了10,30,...,310個Eigenfaces
10個特征向量顯然不是很好的,50個看起來已經能夠很好的編碼面部的一些重要信息了,大概300個,差不多。


image.png

Fisherfaces

PCA,是Eigenfaces的核心,可以找到數據最大化方差的特征的線性組合,這是可以呈現數據的一種強有力的方式,但他并沒有考慮分類,而且如果丟掉一些成分可能也會丟棄一些判別信息。如果數據的變化由外部因素導致,比如光照,那么PCA的成分不會包含任何判別信息。
線性判別分析是一種降維可分的方法,由老魚費舍爾(并不是湖人隊的)發明。為了找到一種最優分類的特征組合方式,考慮最大化類內散度和最小化類間散度。想法很簡單,在低維表示下,同類應該緊緊在一起,而不同類應盡可能遠離。
在opencv里面,調用fisherfaces和Eigenfaces是一樣的方法。還有第三種方法LBP,后面再講

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容