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 上比較已知預測結果。