BadBob / Playground

Dein Modell.
Raus in die Welt.

Mach aus einem trainierten Modell etwas Nutzbares. Kleine Open-Source-Beispiele, klare Schritte und Code, den du zu deinem eigenen machen kannst.

Open Source · MIT · Dein Modell bleibt deins

VOM MODELL ZUR APP
Professor Bob lächelt und blickt über seine tief sitzende Lesebrille. Neben ihm steht eine Tafel voller komplexer Physik. In eine freigewischte Ecke hat er geschrieben: MODEL = mc² / 10 PRINT "BAD BOB" / 20 GOTO 10.
  1. 01Kamera
  2. 02Modell
  3. 03Vorhersage
  4. 04Deine App
Illustration · von der Berechnung zum Ergebnis

01 / WÄHLE DEINEN WEG

Ein kleiner Anfang. Viel Platz zum Weiterbauen.

Verfügbar

Swift

Eine native Mac-Kamera-App mit deinem Core ML-Detektor.

Core ML · macOS
Verfügbar

Python

Ein Skriptpfad zum Prüfen von Modellen und Bauen praktischer Werkzeuge.

ONNX Runtime · OpenCV
Verfügbar

JavaScript

Browserbeispiele mit einem unterstützten ONNX-Modell.

Web · ONNX
Verfügbar

Rust

Ein nativer Pfad mit klaren Modell- und Laufzeitanforderungen.

OpenCV · ONNX
Verfügbar

Go

Praktische Werkzeuge mit einer klaren Schnittstelle zur Modellausführung.

GoCV · ONNX
Verfügbar

C++

Kamera und lokale Inferenz mit OpenCV und einem unterstützten ONNX-Modell.

OpenCV · ONNX

DeviconGo Gopher — Renee FrenchCC BY 3.0

Gut zu wissen
  1. Symptom
    Die Oberfläche friert beim Kamerastart ein.
    Ursache
    Der Sitzungsstart blockiert; async allein verlagert die Arbeit nicht vom MainActor.
    Abhilfe
    Führe Aufnahme und Inferenz auf einem eigenen seriellen Executor aus. Aktualisiere die Oberfläche auf dem MainActor.
  2. Symptom
    Die Vorschau hinkt hinterher und der Speicherbedarf wächst.
    Ursache
    Die Kamera liefert Bilder schneller, als die Inferenz sie verarbeitet. Dadurch wächst eine unbegrenzte Warteschlange.
    Abhilfe
    Verwirf verspätete Bilder, verarbeite seriell und behalte nur das neueste wartende Ergebnis. Vermeide einen Task pro Bild.
  3. Symptom
    Alte Rahmen erscheinen nach dem Stoppen oder Modellwechsel erneut.
    Ursache
    Ein früherer Task kann verspätet enden; gehaltene Beobachter können Ressourcen weiter binden.
    Abhilfe
    Brich den alten Durchlauf ab, verwerfe veraltete Ergebnisse, stoppe die Aufnahme und entferne Beobachter. Gib temporäre Modelle frei; untersuche wiederholte Starts und Stopps mit Instruments.
BadBob / Playground
Core ML · Vision · MIT
02.01

Projekt vorbereiten

Lade den Quellcode herunter und führe die Tests aus. Du brauchst eine Kamera und einen Vision-kompatiblen Core ML-Objektdetektor. Modellgewichte sind nicht enthalten.

Grundlagen

swift test
Führt automatische Prüfungen aus, ohne die Kamera zu öffnen.
Terminalbash
unzip badbob-playground-swift.zip
cd badbob-playground-swift
swift test
02.02

Dein Modell verbinden

Lade dein Modell und erstelle eine Vision-Anfrage. Prüfe die Eingaben vor dem Kamerastart und behalte temporäre Kompilierungen während der gesamten Inferenzlaufzeit.

Grundlagen

VisionDetector.init(modelURL:)
Lädt oder kompiliert das Core-ML-Modell und prüft seine Bildeingabe.
VisionDetector.predict(_:)
Bereitet das Bild vor, führt das Modell aus und liefert Erkennungen zurück.

Dieses Beispiel benötigt einen Core-ML-Objektdetektor, der Vision-Objektbeobachtungen liefert. Andere Modelltypen und ONNX-Dateien benötigen einen anderen Adapter.

Vertiefung

Vision liefert normalisierte Koordinaten vom linken unteren Rand. Rechne sie in deine Ansicht um, erhalte das Seitenverhältnis und spiegle Bild und Rahmen gemeinsam.

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

Kamera einbinden

Die Aufnahme läuft auf einem eigenen seriellen Executor. Verspätete Frames werden verworfen; nur der neueste verarbeitete Frame wartet auf die Oberfläche. Bild und Vorhersagen bleiben zusammen.

Grundlagen

CameraService.start(runID:modelURL:)
Erstellt die Aufnahmesitzung auf ihrem seriellen Executor und liefert einen Stream mit höchstens einem wartenden Bild.
CameraService.stop(runID:)
Stoppt nur den zugehörigen Durchlauf und gibt Sitzung, Delegate und Beobachter frei.
Gut zu wissen
  1. Symptom
    Die Oberfläche friert beim Kamerastart ein.
    Ursache
    Der Sitzungsstart blockiert; async allein verlagert die Arbeit nicht vom MainActor.
    Abhilfe
    Führe Aufnahme und Inferenz auf einem eigenen seriellen Executor aus. Aktualisiere die Oberfläche auf dem MainActor.
  2. Symptom
    Die Vorschau hinkt hinterher und der Speicherbedarf wächst.
    Ursache
    Die Kamera liefert Bilder schneller, als die Inferenz sie verarbeitet. Dadurch wächst eine unbegrenzte Warteschlange.
    Abhilfe
    Verwirf verspätete Bilder, verarbeite seriell und behalte nur das neueste wartende Ergebnis. Vermeide einen Task pro Bild.
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

Vorhersagen richtig platzieren

Vision liefert normalisierte Koordinaten vom linken unteren Rand. Rechne sie in deine Ansicht um, erhalte das Seitenverhältnis und spiegle Bild und Rahmen gemeinsam.

Grundlagen

OverlayGeometry.project(...)
Projiziert Vision-Boxen in eine Ansicht mit erhaltenem Seitenverhältnis und spiegelt Bild und Boxen gemeinsam.
Gut zu wissen

Behandle Bildgröße, Zuschnitt, Ausrichtung und Koordinaten als gemeinsamen Vertrag. Teste bekannte Rahmen, bevor du der Einblendung vertraust.

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

Bauen. Starten. Modell testen.

Baue die lokale App, wähle deinen Detektor und drücke Start camera. Passe Konfidenzschwelle und Spiegelung an. Beende die Aufnahme anschließend.

Grundlagen

CameraController.start()
Fordert die Kameraberechtigung an, startet die Aufnahme und aktualisiert passende Bilder auf MainActor.
CameraController.stop()
Bricht die aktive UI-Aufgabe ab und fordert den Kameradienst auf, denselben Durchlauf zu stoppen.
Gut zu wissen
  1. Symptom
    Alte Rahmen erscheinen nach dem Stoppen oder Modellwechsel erneut.
    Ursache
    Ein früherer Task kann verspätet enden; gehaltene Beobachter können Ressourcen weiter binden.
    Abhilfe
    Brich den alten Durchlauf ab, verwerfe veraltete Ergebnisse, stoppe die Aufnahme und entferne Beobachter. Gib temporäre Modelle frei; untersuche wiederholte Starts und Stopps mit Instruments.
Terminalbash
./build-app.sh
open ".build/BadBob Playground.app"

02.06 / Bewährte Vorgehensweisen

Kleine Details. Bessere Beispiele.

  • Halte Aufnahme und Inferenz vom UI-Thread fern. Begrenze die Warteschlange, statt alte Frames anzusammeln.
  • Behandle Bildgröße, Zuschnitt, Ausrichtung und Koordinaten als gemeinsamen Vertrag. Teste bekannte Rahmen, bevor du der Einblendung vertraust.
  • Behandle verweigerten Zugriff, inkompatible Modelle und Abbrüche. Vergleiche bekannte Vorhersagen auf dem Mac, den du verwenden wirst.