BadBob / Playground

你嘅模型。
走入真實世界。

將訓練好嘅模型變成實用工具。小巧嘅開源範例、清晰步驟,同埋可以自行修改嘅程式碼。

開源 · MIT · 模型仍然屬於你

由模型到應用程式
Bob 教授笑住,副老花眼鏡擱得低低,身邊塊黑板寫滿複雜物理內容。喺擦乾淨咗嘅一角,佢寫咗: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。
    處理方法
    喺專用嘅序列執行器上處理擷取同推論,喺 MainActor 上更新介面。
  2. 症狀
    預覽愈來愈慢,記憶體用量不斷增加。
    原因
    相機產生影像快過推論處理嘅速度,令冇上限嘅佇列不斷累積。
    處理方法
    略過延遲影格,依序處理,只保留最新嘅待顯示結果。避免每個影格都開一個 Task。
  3. 症狀
    停止擷取或者轉模型之後,舊偵測框又出現。
    原因
    之前嘅工作可能遲咗先完成;保留住嘅觀察者可能令資源一直佔用。
    處理方法
    取消舊工作,拒絕過期結果,停止擷取並移除觀察者。釋放暫存模型;用 Instruments 分析重複啟動同停止嘅情況。
BadBob / Playground
Core ML · Vision · MIT
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。
    處理方法
    喺專用嘅序列執行器上處理擷取同推論,喺 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()
取消目前嘅介面任務,並要求鏡頭服務停止同一次執行。
要留意
  1. 症狀
    停止擷取或者轉模型之後,舊偵測框又出現。
    原因
    之前嘅工作可能遲咗先完成;保留住嘅觀察者可能令資源一直佔用。
    處理方法
    取消舊工作,拒絕過期結果,停止擷取並移除觀察者。釋放暫存模型;用 Instruments 分析重複啟動同停止嘅情況。
Terminalbash
./build-app.sh
open ".build/BadBob Playground.app"

02.06 / 最佳實踐

做好細節,範例更好。

  • 擷取同推論唔好放喺介面執行緒。限制佇列長度,避免積埋舊影格。
  • 影像尺寸、裁切、方向同座標要有同一套約定。先用已知偵測框測試,再信任畫面標記。
  • 處理權限被拒、模型唔兼容同取消操作。喺實際使用嘅 Mac 比較已知預測結果。