SlideShare a Scribd company logo
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

More Related Content

PDF
Opencv object detection_takmin
PDF
Rでウォーリを探してみた
PDF
Deformable Part Modelとその発展
PDF
Chainerチュートリアル -v1.5向け- ViEW2015
PDF
ICCV 2019 論文紹介 (26 papers)
PDF
Deep Learning 勉強会 (Chapter 7-12)
PPTX
cvsaisentan20141004 kanezaki
Opencv object detection_takmin
Rでウォーリを探してみた
Deformable Part Modelとその発展
Chainerチュートリアル -v1.5向け- ViEW2015
ICCV 2019 論文紹介 (26 papers)
Deep Learning 勉強会 (Chapter 7-12)
cvsaisentan20141004 kanezaki

What's hot (20)

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

Viewers also liked (8)

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

Similar to Face Recognition with OpenCV and scikit-learn (20)

PDF
AV 画像認識とその周辺 - UT Startup Gym 講演資料
PDF
AdaFace(CVPR2022)
PDF
顔認識の未来について語ろう! (CVPR 2018 完全読破チャレンジ報告会)
PDF
畳み込みニューラルネットワークによる画像分類について
PDF
Retail Face Analysis Inside-Out
PDF
文献紹介:Prior Guided GAN Based Semantic Inpainting
PPTX
SynFace: Face Recognition with Synthetic Data 論文紹介
PPTX
AI x WebAR MediaPipeの顔認識を使ってみよう! in 織りなすラボ
PDF
画像処理でのPythonの利用
PPTX
AI x WebAR! MediaPipeの顔認識を使ってみよう!
PDF
170731 深層学習による顔認識入室記録
PDF
20141127 py datatokyomeetup2
PPTX
ArcFace: Additive Angular Margin Loss for Deep Face Recognition
PDF
アメブロFaceの顔認識システム
PDF
2016年1月期 AITCオープンラボ 「第1回 機械学習勉強会 ~Deep Learningを使って訪問者判定してみた」
PDF
Face APIで 寝る時間を確保しよう
PDF
統計的学習手法による人検出
PDF
統計的学習手法よる人検出
PDF
論文輪読資料「FaceNet: A Unified Embedding for Face Recognition and Clustering」
PDF
SSII2014 詳細画像識別 (FGVC) @OS2
AV 画像認識とその周辺 - UT Startup Gym 講演資料
AdaFace(CVPR2022)
顔認識の未来について語ろう! (CVPR 2018 完全読破チャレンジ報告会)
畳み込みニューラルネットワークによる画像分類について
Retail Face Analysis Inside-Out
文献紹介:Prior Guided GAN Based Semantic Inpainting
SynFace: Face Recognition with Synthetic Data 論文紹介
AI x WebAR MediaPipeの顔認識を使ってみよう! in 織りなすラボ
画像処理でのPythonの利用
AI x WebAR! MediaPipeの顔認識を使ってみよう!
170731 深層学習による顔認識入室記録
20141127 py datatokyomeetup2
ArcFace: Additive Angular Margin Loss for Deep Face Recognition
アメブロFaceの顔認識システム
2016年1月期 AITCオープンラボ 「第1回 機械学習勉強会 ~Deep Learningを使って訪問者判定してみた」
Face APIで 寝る時間を確保しよう
統計的学習手法による人検出
統計的学習手法よる人検出
論文輪読資料「FaceNet: A Unified Embedding for Face Recognition and Clustering」
SSII2014 詳細画像識別 (FGVC) @OS2

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