SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
26, January, 2013



OpenCV と scikit-learn
    で楽々顔認識

       杜 世橋 FreeBit
       @lucidfrontier45
顔認識とは ?
          Face Detection
          画像から人の顔部分を抜き取る


          Face Recognition
          与えられた顔の人物を推定する



  Lena
顔認識とは ?
 Face Detection
  Haar Cascade Classifier

                                                      Weak classifier


                                    +                 Weak classifier

                                                      Weak classifier


   Haar-like feature                                     AdaBoost
原著論文は Paul Viola and Michael J. Jones. Rapid Object Detection using a Boosted
Cascade of Simple Features. IEEE CVPR, 2001.
日本語ではこちらのスライドがわかりやすい。
顔認識とは ?
Face Recognition
                                          Input Picture
  EigenFace                               X (dim = d1 x d2)
M. Turk and A. Pentland (1991).
“Face recognition using eigenfaces”.                PCA

                                        Projected Picture
                                        Y (dim = p < d1 x d2)



                                       Nearest Neighbor or
     http://scikit-learn.org/ より       Other Supervised Prediction
     * ちなみに PCA の代わりに Fisher 判別分析を使用した FisherFace や
     LPP を使用した LaplacianFace などもある。
実装イメージ
 Face Detection             Face Recognition

                                 scikit-learn
 OpenCV
                                   SciPy
                    NumPy

 Face Detection は OpenCV の CascadeClassifier
 モジュールを使用。
 Face Recognition は scikit-learn を用いて適当に実装。
 ( 実は OpenCV にも )
実装イメージ
Face Detection

import numpy as np
import cv, cv2

#画像ファイルを読み込んでモノクロ化&輝度を正規化
img = cv2.imread(img_file) #imgはndarray型!
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray_img = cv2.equalizeHist(gray_img)

#顔検出器を作成
cascade_file = “haarcascade_frontalface_default.xml"
detector = cv2.CascadeClassifier(cascade_file)
実装イメージ
Face Detection

#検出を実行
flags = cv.CV_HAAR_FIND_BIGGEST_OBJECT | cv.CV_HAAR_DO_ROUGH_SEARCHT
rects = detector.detectMultiScale(gray_img, scaleFactor=1.1,
   minNeighbors=3, minSize=(64, 64), flags=detact_flags)

#戻り値はxy座標、幅、高さ。OpenCVのndarrayは(y,x)の順なので注意
x, y, w, h = rects[0]
face = np.array(gray_img[y:y+h, x:x+w])

#後のためにリサイズして次元を統一しておく
min_size = (64, 64)
face = cv2.resize(face, min_size, interpolation=cv.CV_INTER_AREA)
実装イメージ
データの型変換
OpenCV の関数は通常は 2 次元の 8bit int の配列を返してくる。
顔認識に進む前に 32bit float の 1 次元配列に変換しておく。
  def convImgMat(img, mat_type="opencv"):
      shape = img.shape
      #まずは32bit floatに変換
      img = np.asanyarray(img, dtype=np.float32)
      if mat_type == "opencv" and len(shape) == 1:
          size = int(math.sqrt(img.size))
          img = np.array(img.reshape((size, size)) * 255.0,
                                             dtype=np.uint8)
      #0-255を0-1に正規化し、1次元に展開する
      elif mat_type == "numpy" and len(shape) == 2:
          img = img.flatten() / 255.0
      else:
          raise ValueError("wrong format")
      return img
実装イメージ
Face Recognition( 学習編 )
import numpy as np
from sklearn.decomposition import PCA

class FaceRecognizer():

   def fit(face_imgs, labels)
       #トランスフォーマーを作成
       self.transformer = PCA(n_components=0.9)

       #係数を学習
       self.transformer.fit(face_imgs)

       #特徴量とラベルをセット
       self.features = self.transformer.transform(face_imgs)
       self.labels = np.array(labels)
実装イメージ
Face Recognition( 予測編 )
from scipy.spatial import distance

class FaceRecognizer():
    …
    def predict(face_img)
        #特徴量を計算
        feature = self.transformer.transform(face_imgs)

       #距離を計算し、最も近いものを選ぶ
       distances = distance.cdist(self.features, [feature]).flatten()
       idx = distances.argmin()

       #もし距離がしきい値以上だったら未知人物を返す
       if distances[idx] > MAX_DISTANCE:
           return UNKNOWN_PERSON
       else:
           return self.labels[idx]
システム化
今回作った顔認識システムの構成


- 顔検出     Haar Cascade Classifier (OpenCV)
- 顔認識     LaplacianFace (scikit-learn 独自レポジトリ )
- DB      Redis (redis-py 経由 )
- HTTPD   Lighttpd (cgi は python)

 学習した係数や顔画像、射影した特徴量はndarray として
 Redis に保存。その際にはtostring メソッドで変換する。
 取り出すときには逆に np.fromstring を使用。
システム化
        追加学習時には LPP 係数は
        学習せず、
            射影した特徴量の
        みを計算して Redis に追加。
        予測時には Redis から特徴
        量をすべて引っ張ってきて最近
        傍探索を行う。




            精度はまだあまりよくない ...
おわり
おすすめの本
Mastering Opencv with Practical Computer Vision Projects  
Chapter 8 が OpenCV を利用した顔認識。性能を大きく左右する前処理
についても詳しく解説されている。
Android や iOS で OpenCV を利用したプログラム開発もある!
おわり

今回使用作成したコード

LPP を実装した scikit-learn のレポジトリ ( そのうち本家にマージします )
https://github.com/lucidfrontier45/scikit-learn/tree/lpp

PyFace レポジトリ
https://github.com/lucidfrontier45/PyFace

Contenu connexe

Tendances

R-CNNの原理とここ数年の流れ
R-CNNの原理とここ数年の流れR-CNNの原理とここ数年の流れ
R-CNNの原理とここ数年の流れKazuki Motohashi
 
SSII2014 チュートリアル資料
SSII2014 チュートリアル資料SSII2014 チュートリアル資料
SSII2014 チュートリアル資料Masayuki Tanaka
 
コンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashi
コンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashiコンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashi
コンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashiMasaki Hayashi
 
Introduction to YOLO detection model
Introduction to YOLO detection modelIntroduction to YOLO detection model
Introduction to YOLO detection modelWEBFARMER. ltd.
 
[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...
[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...
[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...Deep Learning JP
 
Deep Learningと画像認識   ~歴史・理論・実践~
Deep Learningと画像認識 ~歴史・理論・実践~Deep Learningと画像認識 ~歴史・理論・実践~
Deep Learningと画像認識   ~歴史・理論・実践~nlab_utokyo
 
Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...
Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...
Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...Yusuke Uchida
 
SuperGlue; Learning Feature Matching with Graph Neural Networks (CVPR'20)
SuperGlue;Learning Feature Matching with Graph Neural Networks (CVPR'20)SuperGlue;Learning Feature Matching with Graph Neural Networks (CVPR'20)
SuperGlue; Learning Feature Matching with Graph Neural Networks (CVPR'20)Yusuke Uchida
 
SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~
SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~
SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~SSII
 
[DL輪読会]End-to-End Object Detection with Transformers
[DL輪読会]End-to-End Object Detection with Transformers[DL輪読会]End-to-End Object Detection with Transformers
[DL輪読会]End-to-End Object Detection with TransformersDeep Learning JP
 
[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...
[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...
[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...Deep Learning JP
 
[DL輪読会]Object-Centric Learning with Slot Attention
[DL輪読会]Object-Centric Learning with Slot Attention[DL輪読会]Object-Centric Learning with Slot Attention
[DL輪読会]Object-Centric Learning with Slot AttentionDeep Learning JP
 
Deep learning実装の基礎と実践
Deep learning実装の基礎と実践Deep learning実装の基礎と実践
Deep learning実装の基礎と実践Seiya Tokui
 
20180622 munit multimodal unsupervised image-to-image translation
20180622 munit   multimodal unsupervised image-to-image translation20180622 munit   multimodal unsupervised image-to-image translation
20180622 munit multimodal unsupervised image-to-image translationh m
 
Deep Learningについて(改訂版)
Deep Learningについて(改訂版)Deep Learningについて(改訂版)
Deep Learningについて(改訂版)Brains Consulting, Inc.
 
Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)
Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)
Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)Ohsawa Goodfellow
 
Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料
Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料
Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料Yusuke Uchida
 
Building High-level Features Using Large Scale Unsupervised Learning
Building High-level Features Using Large Scale Unsupervised LearningBuilding High-level Features Using Large Scale Unsupervised Learning
Building High-level Features Using Large Scale Unsupervised LearningTakuya Minagawa
 
コンピューテーショナルフォトグラフィ
コンピューテーショナルフォトグラフィコンピューテーショナルフォトグラフィ
コンピューテーショナルフォトグラフィNorishige Fukushima
 

Tendances (20)

R-CNNの原理とここ数年の流れ
R-CNNの原理とここ数年の流れR-CNNの原理とここ数年の流れ
R-CNNの原理とここ数年の流れ
 
SSII2014 チュートリアル資料
SSII2014 チュートリアル資料SSII2014 チュートリアル資料
SSII2014 チュートリアル資料
 
コンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashi
コンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashiコンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashi
コンピュータビジョンの最新ソフトウェア開発環境 SSII2015 チュートリアル hayashi
 
Introduction to YOLO detection model
Introduction to YOLO detection modelIntroduction to YOLO detection model
Introduction to YOLO detection model
 
PCL
PCLPCL
PCL
 
[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...
[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...
[DL輪読会]VoxelPose: Towards Multi-Camera 3D Human Pose Estimation in Wild Envir...
 
Deep Learningと画像認識   ~歴史・理論・実践~
Deep Learningと画像認識 ~歴史・理論・実践~Deep Learningと画像認識 ~歴史・理論・実践~
Deep Learningと画像認識   ~歴史・理論・実践~
 
Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...
Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...
Image Retrieval Overview (from Traditional Local Features to Recent Deep Lear...
 
SuperGlue; Learning Feature Matching with Graph Neural Networks (CVPR'20)
SuperGlue;Learning Feature Matching with Graph Neural Networks (CVPR'20)SuperGlue;Learning Feature Matching with Graph Neural Networks (CVPR'20)
SuperGlue; Learning Feature Matching with Graph Neural Networks (CVPR'20)
 
SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~
SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~
SSII2019TS: 実践カメラキャリブレーション ~カメラを用いた実世界計測の基礎と応用~
 
[DL輪読会]End-to-End Object Detection with Transformers
[DL輪読会]End-to-End Object Detection with Transformers[DL輪読会]End-to-End Object Detection with Transformers
[DL輪読会]End-to-End Object Detection with Transformers
 
[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...
[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...
[DL輪読会]Vision Transformer with Deformable Attention (Deformable Attention Tra...
 
[DL輪読会]Object-Centric Learning with Slot Attention
[DL輪読会]Object-Centric Learning with Slot Attention[DL輪読会]Object-Centric Learning with Slot Attention
[DL輪読会]Object-Centric Learning with Slot Attention
 
Deep learning実装の基礎と実践
Deep learning実装の基礎と実践Deep learning実装の基礎と実践
Deep learning実装の基礎と実践
 
20180622 munit multimodal unsupervised image-to-image translation
20180622 munit   multimodal unsupervised image-to-image translation20180622 munit   multimodal unsupervised image-to-image translation
20180622 munit multimodal unsupervised image-to-image translation
 
Deep Learningについて(改訂版)
Deep Learningについて(改訂版)Deep Learningについて(改訂版)
Deep Learningについて(改訂版)
 
Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)
Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)
Learning Deep Architectures for AI (第 3 回 Deep Learning 勉強会資料; 松尾)
 
Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料
Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料
Swin Transformer (ICCV'21 Best Paper) を完璧に理解する資料
 
Building High-level Features Using Large Scale Unsupervised Learning
Building High-level Features Using Large Scale Unsupervised LearningBuilding High-level Features Using Large Scale Unsupervised Learning
Building High-level Features Using Large Scale Unsupervised Learning
 
コンピューテーショナルフォトグラフィ
コンピューテーショナルフォトグラフィコンピューテーショナルフォトグラフィ
コンピューテーショナルフォトグラフィ
 

En vedette

Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Luigi De Russis
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic WebLuigi De Russis
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Luigi De Russis
 
PyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel Hordes
PyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel HordesPyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel Hordes
PyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel Hordeskgrandis
 
Face Recognition using OpenCV
Face Recognition using OpenCVFace Recognition using OpenCV
Face Recognition using OpenCVVasile Chelban
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101Luigi De Russis
 

En vedette (8)

Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic Web
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)
 
Java and OWL
Java and OWLJava and OWL
Java and OWL
 
PyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel Hordes
PyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel HordesPyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel Hordes
PyCon 2012: Militarizing Your Backyard: Computer Vision and the Squirrel Hordes
 
Face Recognition using OpenCV
Face Recognition using OpenCVFace Recognition using OpenCV
Face Recognition using OpenCV
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 

Similaire à Face Recognition with OpenCV and scikit-learn

画像処理でのPythonの利用
画像処理でのPythonの利用画像処理でのPythonの利用
画像処理でのPythonの利用Yasutomo Kawanishi
 
はじめての人のためのDeep Learning
はじめての人のためのDeep Learningはじめての人のためのDeep Learning
はじめての人のためのDeep LearningTadaichiro Nakano
 
Kashiwa.R#1 画像解析とパターン認識における R の利用
Kashiwa.R#1 画像解析とパターン認識における R の利用Kashiwa.R#1 画像解析とパターン認識における R の利用
Kashiwa.R#1 画像解析とパターン認識における R の利用nmaro
 
画像認識と深層学習
画像認識と深層学習画像認識と深層学習
画像認識と深層学習Yusuke Uchida
 
introduce "Stealing Machine Learning Models via Prediction APIs"
introduce "Stealing Machine Learning Models  via Prediction APIs"introduce "Stealing Machine Learning Models  via Prediction APIs"
introduce "Stealing Machine Learning Models via Prediction APIs"Isao Takaesu
 
LexADV_WOVis Ver.0.1bの概要
LexADV_WOVis Ver.0.1bの概要LexADV_WOVis Ver.0.1bの概要
LexADV_WOVis Ver.0.1bの概要ADVENTURE Project
 
[DL Hacks 実装]Representation Learning by Rotating Your Faces
[DL Hacks 実装]Representation Learning by Rotating Your Faces[DL Hacks 実装]Representation Learning by Rotating Your Faces
[DL Hacks 実装]Representation Learning by Rotating Your FacesDeep Learning JP
 
Deep Learningの基礎と応用
Deep Learningの基礎と応用Deep Learningの基礎と応用
Deep Learningの基礎と応用Seiya Tokui
 
Lecuture on Deep Learning API
Lecuture on Deep Learning APILecuture on Deep Learning API
Lecuture on Deep Learning APINaoki Watanabe
 
「機械学習とは?」から始める Deep learning実践入門
「機械学習とは?」から始める Deep learning実践入門「機械学習とは?」から始める Deep learning実践入門
「機械学習とは?」から始める Deep learning実践入門Hideto Masuoka
 
AV 画像認識とその周辺 - UT Startup Gym 講演資料
AV 画像認識とその周辺 - UT Startup Gym 講演資料AV 画像認識とその周辺 - UT Startup Gym 講演資料
AV 画像認識とその周辺 - UT Startup Gym 講演資料ぱろすけ
 
Introduction to "Facial Landmark Detection by Deep Multi-task Learning"
Introduction to "Facial Landmark Detection by Deep Multi-task Learning"Introduction to "Facial Landmark Detection by Deep Multi-task Learning"
Introduction to "Facial Landmark Detection by Deep Multi-task Learning"Yukiyoshi Sasao
 

Similaire à Face Recognition with OpenCV and scikit-learn (13)

画像処理でのPythonの利用
画像処理でのPythonの利用画像処理でのPythonの利用
画像処理でのPythonの利用
 
はじめての人のためのDeep Learning
はじめての人のためのDeep Learningはじめての人のためのDeep Learning
はじめての人のためのDeep Learning
 
Kashiwa.R#1 画像解析とパターン認識における R の利用
Kashiwa.R#1 画像解析とパターン認識における R の利用Kashiwa.R#1 画像解析とパターン認識における R の利用
Kashiwa.R#1 画像解析とパターン認識における R の利用
 
画像認識と深層学習
画像認識と深層学習画像認識と深層学習
画像認識と深層学習
 
introduce "Stealing Machine Learning Models via Prediction APIs"
introduce "Stealing Machine Learning Models  via Prediction APIs"introduce "Stealing Machine Learning Models  via Prediction APIs"
introduce "Stealing Machine Learning Models via Prediction APIs"
 
LexADV_WOVis Ver.0.1bの概要
LexADV_WOVis Ver.0.1bの概要LexADV_WOVis Ver.0.1bの概要
LexADV_WOVis Ver.0.1bの概要
 
[DL Hacks 実装]Representation Learning by Rotating Your Faces
[DL Hacks 実装]Representation Learning by Rotating Your Faces[DL Hacks 実装]Representation Learning by Rotating Your Faces
[DL Hacks 実装]Representation Learning by Rotating Your Faces
 
20141008物体検出器
20141008物体検出器20141008物体検出器
20141008物体検出器
 
Deep Learningの基礎と応用
Deep Learningの基礎と応用Deep Learningの基礎と応用
Deep Learningの基礎と応用
 
Lecuture on Deep Learning API
Lecuture on Deep Learning APILecuture on Deep Learning API
Lecuture on Deep Learning API
 
「機械学習とは?」から始める Deep learning実践入門
「機械学習とは?」から始める Deep learning実践入門「機械学習とは?」から始める Deep learning実践入門
「機械学習とは?」から始める Deep learning実践入門
 
AV 画像認識とその周辺 - UT Startup Gym 講演資料
AV 画像認識とその周辺 - UT Startup Gym 講演資料AV 画像認識とその周辺 - UT Startup Gym 講演資料
AV 画像認識とその周辺 - UT Startup Gym 講演資料
 
Introduction to "Facial Landmark Detection by Deep Multi-task Learning"
Introduction to "Facial Landmark Detection by Deep Multi-task Learning"Introduction to "Facial Landmark Detection by Deep Multi-task Learning"
Introduction to "Facial Landmark Detection by Deep Multi-task Learning"
 

Face Recognition with OpenCV and scikit-learn

  • 1. 26, January, 2013 OpenCV と scikit-learn で楽々顔認識 杜 世橋 FreeBit @lucidfrontier45
  • 2. 顔認識とは ? Face Detection 画像から人の顔部分を抜き取る Face Recognition 与えられた顔の人物を推定する Lena
  • 3. 顔認識とは ? Face Detection Haar Cascade Classifier Weak classifier + Weak classifier Weak classifier Haar-like feature AdaBoost 原著論文は Paul Viola and Michael J. Jones. Rapid Object Detection using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. 日本語ではこちらのスライドがわかりやすい。
  • 4. 顔認識とは ? Face Recognition Input Picture EigenFace X (dim = d1 x d2) M. Turk and A. Pentland (1991). “Face recognition using eigenfaces”. PCA Projected Picture Y (dim = p < d1 x d2) Nearest Neighbor or http://scikit-learn.org/ より Other Supervised Prediction * ちなみに PCA の代わりに Fisher 判別分析を使用した FisherFace や LPP を使用した LaplacianFace などもある。
  • 5. 実装イメージ Face Detection Face Recognition scikit-learn OpenCV SciPy NumPy Face Detection は OpenCV の CascadeClassifier モジュールを使用。 Face Recognition は scikit-learn を用いて適当に実装。 ( 実は OpenCV にも )
  • 6. 実装イメージ Face Detection import numpy as np import cv, cv2 #画像ファイルを読み込んでモノクロ化&輝度を正規化 img = cv2.imread(img_file) #imgはndarray型! gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray_img = cv2.equalizeHist(gray_img) #顔検出器を作成 cascade_file = “haarcascade_frontalface_default.xml" detector = cv2.CascadeClassifier(cascade_file)
  • 7. 実装イメージ Face Detection #検出を実行 flags = cv.CV_HAAR_FIND_BIGGEST_OBJECT | cv.CV_HAAR_DO_ROUGH_SEARCHT rects = detector.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=3, minSize=(64, 64), flags=detact_flags) #戻り値はxy座標、幅、高さ。OpenCVのndarrayは(y,x)の順なので注意 x, y, w, h = rects[0] face = np.array(gray_img[y:y+h, x:x+w]) #後のためにリサイズして次元を統一しておく min_size = (64, 64) face = cv2.resize(face, min_size, interpolation=cv.CV_INTER_AREA)
  • 8. 実装イメージ データの型変換 OpenCV の関数は通常は 2 次元の 8bit int の配列を返してくる。 顔認識に進む前に 32bit float の 1 次元配列に変換しておく。 def convImgMat(img, mat_type="opencv"): shape = img.shape #まずは32bit floatに変換 img = np.asanyarray(img, dtype=np.float32) if mat_type == "opencv" and len(shape) == 1: size = int(math.sqrt(img.size)) img = np.array(img.reshape((size, size)) * 255.0, dtype=np.uint8) #0-255を0-1に正規化し、1次元に展開する elif mat_type == "numpy" and len(shape) == 2: img = img.flatten() / 255.0 else: raise ValueError("wrong format") return img
  • 9. 実装イメージ Face Recognition( 学習編 ) import numpy as np from sklearn.decomposition import PCA class FaceRecognizer(): def fit(face_imgs, labels) #トランスフォーマーを作成 self.transformer = PCA(n_components=0.9) #係数を学習 self.transformer.fit(face_imgs) #特徴量とラベルをセット self.features = self.transformer.transform(face_imgs) self.labels = np.array(labels)
  • 10. 実装イメージ Face Recognition( 予測編 ) from scipy.spatial import distance class FaceRecognizer(): … def predict(face_img) #特徴量を計算 feature = self.transformer.transform(face_imgs) #距離を計算し、最も近いものを選ぶ distances = distance.cdist(self.features, [feature]).flatten() idx = distances.argmin() #もし距離がしきい値以上だったら未知人物を返す if distances[idx] > MAX_DISTANCE: return UNKNOWN_PERSON else: return self.labels[idx]
  • 11. システム化 今回作った顔認識システムの構成 - 顔検出 Haar Cascade Classifier (OpenCV) - 顔認識 LaplacianFace (scikit-learn 独自レポジトリ ) - DB Redis (redis-py 経由 ) - HTTPD Lighttpd (cgi は python) 学習した係数や顔画像、射影した特徴量はndarray として Redis に保存。その際にはtostring メソッドで変換する。 取り出すときには逆に np.fromstring を使用。
  • 12. システム化 追加学習時には LPP 係数は 学習せず、 射影した特徴量の みを計算して Redis に追加。 予測時には Redis から特徴 量をすべて引っ張ってきて最近 傍探索を行う。 精度はまだあまりよくない ...
  • 13. おわり おすすめの本 Mastering Opencv with Practical Computer Vision Projects   Chapter 8 が OpenCV を利用した顔認識。性能を大きく左右する前処理 についても詳しく解説されている。 Android や iOS で OpenCV を利用したプログラム開発もある!
  • 14. おわり 今回使用作成したコード LPP を実装した scikit-learn のレポジトリ ( そのうち本家にマージします ) https://github.com/lucidfrontier45/scikit-learn/tree/lpp PyFace レポジトリ https://github.com/lucidfrontier45/PyFace