3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

動物を認識して自動撮影するカメラを作る

Last updated at Posted at 2020-09-25

Sep-26-2020 02-43-16.gif

犬・猫がフレーム内に現れたら自動でシャッターを切る機能を作ります。

手順

Visionに動物認識コンピュータービジョンリクエストがあります。
リクエスト結果でフレームに動物がいるか判別し写真を撮るように設定します。

let animalRequest:VNRecognizeAnimalsRequest = {
    let request = VNRecognizeAnimalsRequest(completionHandler: { (request, error) in
        guard let animalObservation = results.first as? VNRecognizedObjectObservation else { return }
// animalObservationがあれば、動物がいるので、シャッターを切る
        self.avCapturePhotoOutput.capturePhoto(with: settings, delegate: self as! AVCapturePhotoCaptureDelegate)
    })
    request.revision = VNRecognizeAnimalsRequestRevision1 //リビジョン1では、認識できるのは犬・猫のみです。
    return request
}()

captureOutputデリゲートメソッド内で、上記のリクエストを実行し、フレームを解析します。

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
    let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: orientation, options: [:])
    do {
        try imageRequestHandler.perform([animalRequest])
       } catch {
        print(error)
       }
}

応用

同じ手法で他のリクエストを使うと、人間や任意の物体を認識して写真を撮れます。
Observationには、犬猫の場所を示すBoundingBoxも含まれていますので、そこにオートフォーカスしたりもできます。


お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
[MLBoysチャンネル]
(https://www.youtube.com/channel/UCbHff-wfjTnB3rtXIP6y0xg)
Medium

相棒
note
相棒
note

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?