LoginSignup
103
95

More than 5 years have passed since last update.

Swiftで笑顔認識をやってみた

Last updated at Posted at 2014-11-07

Swiftで笑顔認識をやってみました。

コードはこちら
iOS7からApple公式APIで顔認識ができるようになったので、Swiftで書いてみました。

追記

Swift2にupdateしました。
Swift3にupdateしました。(2016/09/28)
Swift4 Xcode9 でも動きます。(2018/01/14)

コード


guard let image = self.sampleImageView.image, let cgImage = image.cgImage else {
    return
}

// storyboardに置いたimageViewからCIImageを生成する
let ciImage = CIImage(cgImage: cgImage)

// 顔認識なのでTypeをCIDetectorTypeFaceに指定する
let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])

// 取得するパラメーターを指定する
let options = [CIDetectorSmile : true, CIDetectorEyeBlink : true]

// 画像から特徴を抽出する
let features = detector.featuresInImage(ciImage, options: options)

var resultString = "DETECTED FACES:\n\n"

for feature in features as! [CIFaceFeature] {
    resultString.append("bounds: \(NSStringFromCGRect(feature.bounds))\n")
    resultString.append("hasSmile: \(feature.hasSmile ? "YES" : "NO")\n")

    resultString.append("\n")
}

実行画面

Screen Shot 2014-11-07 at 17.29.00.png

CIFaceFeatureについて

CIFaceFeatureで取得できるもの

主なプロパティだと、以下のものなどがあります

プロパティ 説明
bounds CGRect 画像内での顔の座標と大きさ
hasSmile Bool 笑顔かどうか
faceAngle Float 顔の傾き
leftEyePosition CGPoint 左目の位置
rightEyePosition CGPoint 右目の位置
mouthPosition CGPoint 口の位置

他にも、leftEyeClosedやrightEyeClosedなどのプロパティがあるので、ウィンクでシャッターを切ることも可能になります。

しかし、CIFaceFeatureでのright, leftは画像内での左右であって、
鏡映している場合は、その人物の左目・右目とは一致しないので、注意が必要です。

“Right”/"Left" is relative to the original (non-mirrored) image orientation, not to the owner of the eye.

CIDetectorについて

今回は、CIDetectorを顔認識に使いましたが、他の対象物の認識にも利用できるようです。

detectorOfType 説明
CIDetectorTypeFace 顔認識 ( face recognition )
CIDetectorTypeRectangle 矩形認識 ( rectangle detection )
CIDetectorTypeQRCode QRコード認識 ( barcode detection )
CIDetectorTypeText 文字認識 ( text detection )

参考

@shu223さん
https://github.com/shu223/iOS7-Sampler/blob/master/iOS7Sampler/SampleViewControllers/SmileDetectionViewController.m

Objective-Cで書かれていますが、Appleのサンプルコードも参考になります
https://developer.apple.com/library/IOs/samplecode/SquareCam/Introduction/Intro.html

写真はこちらから
http://www.ashinari.com/2012/02/06-357198.php?category=265

103
95
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
103
95