BadBob / Playground

あなたのモデルを。
現実の世界へ。

学習済みモデルを、使えるものに。小さなオープンソースのサンプルと明確な手順、自分のアイデアに合わせて変えられるコードを用意します。

オープンソース · MIT · モデルはあなたのもの

モデルからアプリへ
ボブ教授が、低くずらした老眼鏡の上から目を向けて微笑んでいます。隣の黒板は難解な物理学の内容で埋まっています。消して空けた隅には、彼がこう書き残しています:MODEL = mc² / 10 PRINT "BAD BOB" / 20 GOTO 10。
  1. 01カメラ
  2. 02モデル
  3. 03予測
  4. 04あなたのアプリ
イラスト · 計算から結果へ

01 / 開発ルートを選ぶ

小さく始めて、広げていく。

利用可能

Swift

自分のCore ML検出器を使う、Macネイティブのカメラアプリ。

Core ML · macOS
利用可能

Python

モデルを調べ、便利なツールを作るスクリプトのルート。

ONNX Runtime · OpenCV
利用可能

JavaScript

対応するONNXモデルを使うブラウザーのサンプル。

Web · ONNX
利用可能

Rust

モデルと実行環境の要件を明示したネイティブ開発ルート。

OpenCV · ONNX
利用可能

Go

モデル実行との境界を明確にした実用ツール。

GoCV · ONNX
利用可能

C++

OpenCVと対応するONNXモデルによるカメラとローカル推論。

OpenCV · ONNX

DeviconGo Gopher — Renee FrenchCC BY 3.0

覚えておきたいこと
  1. 症状
    カメラの起動時に画面が固まる。
    原因
    セッションの起動は処理をブロックします。async だけでは処理は MainActor から移りません。
    対処法
    キャプチャと推論を専用の直列エグゼキュータで実行し、UI の更新は MainActor で行います。
  2. 症状
    プレビューが遅れ、メモリ使用量が増える。
    原因
    カメラのフレーム生成が推論処理より速いため、上限のないキューにフレームが蓄積します。
    対処法
    遅れたフレームを破棄し、直列に処理して、表示待ちの最新結果だけを保持します。フレームごとの Task 作成は避けます。
  3. 症状
    停止やモデル変更の後に古い枠が再表示される。
    原因
    前のタスクが遅れて完了したり、保持されたオブザーバがリソースを解放させなかったりすることがあります。
    対処法
    前の実行をキャンセルし、古い結果を拒否して、キャプチャを停止し、オブザーバを削除します。一時モデルを解放し、起動と停止の繰り返しを Instruments で計測します。
BadBob / Playground
Core ML · Vision · MIT

02 / Swift Core ML + Vision

見えるアプリを作ろう。

ひと通り動くSwiftサンプルです。モデルを選び、カメラを起動し、対応する予測を描画します。順番に読むことも、ソース全体を見ることもできます。

サンプルは、管理された環境での物や動物を対象とします。人の監視、個人の識別、行動分析は扱いません。

02.01

プロジェクトを準備する

ソースをダウンロードしてテストを実行します。カメラと、Visionに対応するCore ML物体検出モデルが必要です。モデルの重みは含みません。

基本

swift test
カメラを開かずに自動チェックを実行します。
Terminalbash
unzip badbob-playground-swift.zip
cd badbob-playground-swift
swift test
02.02

モデルを接続する

モデルを読み込み、Visionリクエストを作ります。カメラ起動前に入力を確認し、一時的なコンパイル結果を推論中は保持します。

基本

VisionDetector.init(modelURL:)
Core MLモデルを読み込むかコンパイルし、画像入力を検証します。
VisionDetector.predict(_:)
画像を前処理し、モデルを実行して検出結果を返します。

この例には、Visionの物体観測結果を返すCore ML物体検出モデルが必要です。その他のモデル形式やONNXファイルには別のアダプターが必要です。

詳しく見る

Visionは左下を原点とする正規化座標を返します。ビューの座標に変換し、縦横比を保ち、画像と枠を一緒に反転します。

Core ML · Visionyaml
model:
  runtime: Core ML + Vision
  formats: [.mlmodel, .mlpackage, .mlmodelc]
  image_inputs: 1
  results: VNRecognizedObjectObservation
preprocessing:
  crop_and_scale: scaleFill
  orientation: up
coordinates:
  range: [0, 1]
  origin: bottom_left
preview:
  scaling: aspect_fit
  mirroring: paired
VisionDetector.swiftswift
import CoreML
import Foundation
import Vision

/// Owned by one frame processor and used only on its serial capture queue.
final class VisionDetector {
    private let request: VNCoreMLRequest
    private let compiledURL: URL?
    private let scopedURL: URL?

    init(modelURL: URL) throws {
        guard modelURL.isFileURL,
            ["mlmodel", "mlpackage", "mlmodelc"].contains(modelURL.pathExtension.lowercased())
        else {
            throw CaptureFailure.unsupportedModel
        }

        let scoped = modelURL.startAccessingSecurityScopedResource()
        var ownedCompilation: URL?

        do {
            let loadURL: URL

            if modelURL.pathExtension.lowercased() == "mlmodelc" {
                loadURL = modelURL
            } else {
                loadURL = try MLModel.compileModel(at: modelURL)
                ownedCompilation = loadURL
            }

            let model = try MLModel(contentsOf: loadURL)
            guard
                model.modelDescription.inputDescriptionsByName.values.filter({ $0.type == .image })
                    .count == 1
            else {
                throw CaptureFailure.unsupportedModel
            }

            request = VNCoreMLRequest(model: try VNCoreMLModel(for: model))
            request.imageCropAndScaleOption = .scaleFill
            compiledURL = ownedCompilation
            scopedURL = scoped ? modelURL : nil
        } catch {
            if scoped {
                modelURL.stopAccessingSecurityScopedResource()
            }

            if let ownedCompilation {
                try? FileManager.default.removeItem(at: ownedCompilation)
            }

            throw error
        }
    }

    deinit {
        // Predictions have ended; remove only our own temporary compilation.
        if let compiledURL {
            try? FileManager.default.removeItem(at: compiledURL)
        }

        scopedURL?.stopAccessingSecurityScopedResource()
    }

    func predict(_ buffer: CVPixelBuffer) throws -> [Detection] {
        try VNImageRequestHandler(cvPixelBuffer: buffer, orientation: .up).perform([request])

        guard let objects = request.results as? [VNRecognizedObjectObservation] else {
            throw CaptureFailure.unsupportedModel
        }

        return objects.enumerated().compactMap { index, observation in

            guard let label = observation.labels.first, label.confidence.isFinite else {
                return nil
            }

            return Detection(
                id: index, label: label.identifier, confidence: label.confidence,
                bounds: observation.boundingBox)
        }
    }
}
02.03

カメラを取り込む

キャプチャは専用の直列エグゼキューターで実行します。遅れたフレームを破棄し、処理済みの最新フレームだけが画面表示を待ちます。画像と予測は常に一組です。

基本

CameraService.start(runID:modelURL:)
専用の直列エグゼキューターで撮影セッションを作成し、待機フレームを最大一つに制限したストリームを返します。
CameraService.stop(runID:)
対応する実行だけを停止し、セッション、デリゲート、監視オブジェクトを解放します。
覚えておきたいこと
  1. 症状
    カメラの起動時に画面が固まる。
    原因
    セッションの起動は処理をブロックします。async だけでは処理は MainActor から移りません。
    対処法
    キャプチャと推論を専用の直列エグゼキュータで実行し、UI の更新は MainActor で行います。
  2. 症状
    プレビューが遅れ、メモリ使用量が増える。
    原因
    カメラのフレーム生成が推論処理より速いため、上限のないキューにフレームが蓄積します。
    対処法
    遅れたフレームを破棄し、直列に処理して、表示待ちの最新結果だけを保持します。フレームごとの Task 作成は避けます。
CameraService.swiftswift
import AVFoundation
import CoreImage
import Dispatch
import Foundation

/// A custom executor keeps blocking AVFoundation work off the main actor.
public actor CameraService: CameraCapturing {
    private nonisolated let queue = DispatchSerialQueue(label: "ai.badbob.playground.camera")
    public nonisolated var unownedExecutor: UnownedSerialExecutor {
        queue.asUnownedSerialExecutor()
    }

    private var session: AVCaptureSession?
    private var output: AVCaptureVideoDataOutput?
    private var processor: FrameProcessor?
    private var monitor: CaptureSessionMonitor?
    private var activeRunID: UUID?

    public init() {}

    public func start(runID: UUID, modelURL: URL) async throws -> FrameStream {
        stopActiveRun()
        let detector = try loadDetector(modelURL: modelURL)

        try Task.checkCancellation()

        guard let camera = AVCaptureDevice.default(for: .video) else {
            throw CaptureFailure.noCamera
        }

        let candidate = AVCaptureSession()
        let frames = AVCaptureVideoDataOutput()
        let (stream, continuation) = FrameStream.makeStream(bufferingPolicy: .bufferingNewest(1))
        let delegate = FrameProcessor(detector: detector, continuation: continuation)
        try configureSession(candidate, output: frames, processor: delegate, camera: camera)

        try Task.checkCancellation()
        session = candidate
        output = frames
        processor = delegate
        activeRunID = runID
        monitor = CaptureSessionMonitor(session: candidate, continuation: continuation)
        continuation.onTermination = { [weak self] _ in
            Task { await self?.stop(runID: runID) }
        }

        candidate.startRunning()

        guard candidate.isRunning else {
            stopActiveRun()
            throw CaptureFailure.configuration
        }

        return stream
    }

    private func loadDetector(modelURL: URL) throws -> VisionDetector {
        do {
            return try VisionDetector(modelURL: modelURL)
        } catch let error as CaptureFailure {
            throw error
        } catch {
            throw CaptureFailure.model(error.localizedDescription)
        }
    }

    private func configureSession(
        _ candidate: AVCaptureSession,
        output frames: AVCaptureVideoDataOutput,
        processor delegate: FrameProcessor,
        camera: AVCaptureDevice
    ) throws {
        candidate.beginConfiguration()

        do {
            let input = try AVCaptureDeviceInput(device: camera)

            guard candidate.canAddInput(input), candidate.canAddOutput(frames) else {
                throw CaptureFailure.configuration
            }

            candidate.addInput(input)
            candidate.addOutput(frames)

            if candidate.canSetSessionPreset(.hd1280x720) {
                candidate.sessionPreset = .hd1280x720
            }

            frames.alwaysDiscardsLateVideoFrames = true
            frames.videoSettings = [
                kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
            ]
            // The delegate, Vision request and frame renderer share this one serial queue.
            frames.setSampleBufferDelegate(delegate, queue: queue)

            if let connection = frames.connection(with: .video),
                connection.isVideoMirroringSupported
            {
                connection.automaticallyAdjustsVideoMirroring = false
                connection.isVideoMirrored = false
            }

            candidate.commitConfiguration()
        } catch {
            candidate.commitConfiguration()
            frames.setSampleBufferDelegate(nil, queue: nil)
            delegate.finish()
            throw error
        }
    }

    public func stop(runID: UUID) {
        // A cancelled old task must not stop a more recent capture run.
        guard activeRunID == runID else {
            return
        }

        stopActiveRun()
    }

    private func stopActiveRun() {
        // Remove observers first so our deliberate stop cannot become a failure.
        monitor?.invalidate()
        monitor = nil
        session?.stopRunning()
        output?.setSampleBufferDelegate(nil, queue: nil)
        processor?.finish()
        processor = nil
        output = nil
        session = nil
        activeRunID = nil
    }
}

/// AVFoundation invokes this delegate only on CameraService's serial queue.
/// No sample buffer or mutable Vision object crosses into a Task or the UI.
private final class FrameProcessor: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
    private let detector: VisionDetector
    private let continuation: FrameStream.Continuation
    private let renderer = CIContext(options: [.cacheIntermediates: false])
    private var finished = false

    init(detector: VisionDetector, continuation: FrameStream.Continuation) {
        self.detector = detector
        self.continuation = continuation
    }

    func finish() {
        guard !finished else {
            return
        }

        finished = true
        continuation.finish()
    }

    func captureOutput(
        _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,
        from connection: AVCaptureConnection
    ) {
        guard !finished, let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            return
        }

        autoreleasepool {
            do {
                let detections = try detector.predict(buffer)
                let image = CIImage(cvPixelBuffer: buffer)

                guard let pixels = renderer.createCGImage(image, from: image.extent) else {
                    throw CaptureFailure.imageCreation
                }

                continuation.yield(DetectionFrame(image: pixels, detections: detections))
            } catch {
                finished = true
                continuation.finish(throwing: error)
            }
        }
    }
}
02.04

予測を正しい位置に置く

Visionは左下を原点とする正規化座標を返します。ビューの座標に変換し、縦横比を保ち、画像と枠を一緒に反転します。

基本

OverlayGeometry.project(...)
Visionの検出枠を縦横比を保つ表示座標に変換し、画像と枠を一緒に反転します。
覚えておきたいこと

画像サイズ、切り取り、向き、座標は一つの規約として扱います。既知の枠でテストしてから表示を信頼します。

OverlayGeometry.swiftswift
import CoreGraphics

/// Convert Vision's normalized, bottom-left coordinates to an aspect-fit view.
public enum OverlayGeometry {
    public static func project(
        _ bounds: CGRect, imageSize: CGSize, viewport: CGSize, mirrored: Bool
    ) -> CGRect? {
        guard
            [imageSize.width, imageSize.height, viewport.width, viewport.height].allSatisfy({
                $0.isFinite && $0 > 0
            }),
            [bounds.origin.x, bounds.origin.y, bounds.width, bounds.height].allSatisfy(\.isFinite),
            bounds.width > 0, bounds.height > 0
        else { return nil }
        let clipped = bounds.intersection(CGRect(x: 0, y: 0, width: 1, height: 1))

        guard !clipped.isNull, !clipped.isEmpty else {
            return nil
        }

        let scale = min(viewport.width / imageSize.width, viewport.height / imageSize.height)
        let width = imageSize.width * scale
        let height = imageSize.height * scale

        return CGRect(
            x: (viewport.width - width) / 2 + (mirrored ? 1 - clipped.maxX : clipped.minX) * width,
            y: (viewport.height - height) / 2 + (1 - clipped.maxY) * height,
            width: clipped.width * width, height: clipped.height * height
        )
    }
}
02.05

ビルドして、モデルを試す。

ローカルアプリをビルドし、検出器を選んでStart cameraを押します。信頼度のしきい値と反転を調整し、終わったらキャプチャを停止します。

基本

CameraController.start()
カメラの許可を求め、撮影を開始し、対応するフレームをMainActorで更新します。
CameraController.stop()
実行中のUIタスクをキャンセルし、カメラサービスに同じ実行の停止を要求します。
覚えておきたいこと
  1. 症状
    停止やモデル変更の後に古い枠が再表示される。
    原因
    前のタスクが遅れて完了したり、保持されたオブザーバがリソースを解放させなかったりすることがあります。
    対処法
    前の実行をキャンセルし、古い結果を拒否して、キャプチャを停止し、オブザーバを削除します。一時モデルを解放し、起動と停止の繰り返しを Instruments で計測します。
Terminalbash
./build-app.sh
open ".build/BadBob Playground.app"

02.06 / ベストプラクティス

細部を整えて、よいサンプルに。

  • キャプチャと推論はUIスレッドの外で行います。古いフレームを蓄積せず、キューの長さを制限します。
  • 画像サイズ、切り取り、向き、座標は一つの規約として扱います。既知の枠でテストしてから表示を信頼します。
  • 権限の拒否、モデルの非互換、キャンセルを処理します。実際に使うMacで既知の予測結果を比較します。