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 से बाहर नहीं जाता।
    उपाय
    कैप्चर और अनुमान को अलग क्रमिक executor पर चलाएँ। UI को MainActor पर अपडेट करें।
  2. लक्षण
    प्रीव्यू पीछे रह जाता है और मेमोरी का उपयोग बढ़ता है।
    कारण
    कैमरा अनुमान की प्रक्रिया से तेज़ फ़्रेम देता है, इसलिए असीमित कतार बढ़ती जाती है।
    उपाय
    देर से आए फ़्रेम छोड़ें, क्रम से प्रोसेस करें और केवल नवीनतम लंबित परिणाम रखें। हर फ़्रेम के लिए अलग Task न बनाएँ।
  3. लक्षण
    रोकने या मॉडल बदलने के बाद पुराने बॉक्स फिर दिखते हैं।
    कारण
    पहले का कार्य देर से पूरा हो सकता है; बचे हुए observer संसाधनों को जीवित रख सकते हैं।
    उपाय
    पुराना रन रद्द करें, पुराने परिणाम अस्वीकार करें, कैप्चर रोकें और observer हटाएँ। अस्थायी मॉडल मुक्त करें; बार-बार शुरू करने और रोकने को 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(_:)
चित्र तैयार करता है, मॉडल चलाता है और डिटेक्शन लौटाता है।

इस उदाहरण के लिए ऐसा Core ML ऑब्जेक्ट डिटेक्टर चाहिए जो Vision ऑब्जेक्ट ऑब्ज़र्वेशन लौटाए। अन्य मॉडल प्रकारों और 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 से बाहर नहीं जाता।
    उपाय
    कैप्चर और अनुमान को अलग क्रमिक executor पर चलाएँ। 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. लक्षण
    रोकने या मॉडल बदलने के बाद पुराने बॉक्स फिर दिखते हैं।
    कारण
    पहले का कार्य देर से पूरा हो सकता है; बचे हुए observer संसाधनों को जीवित रख सकते हैं।
    उपाय
    पुराना रन रद्द करें, पुराने परिणाम अस्वीकार करें, कैप्चर रोकें और observer हटाएँ। अस्थायी मॉडल मुक्त करें; बार-बार शुरू करने और रोकने को Instruments से मापें।
Terminalbash
./build-app.sh
open ".build/BadBob Playground.app"

02.06 / बेहतर तरीके

छोटी बारीकियाँ। बेहतर उदाहरण।

  • कैप्चर और मॉडल संचालन को UI थ्रेड से बाहर रखें। पुराने फ़्रेम जमा करने के बजाय कतार सीमित रखें।
  • चित्र का आकार, क्रॉप, दिशा और निर्देशांक एक साझा नियम मानें। चिह्नों पर भरोसा करने से पहले ज्ञात बॉक्स से जाँचें।
  • अनुमति न मिलने, असंगत मॉडल और रद्द करने को सँभालें। जिस Mac का इस्तेमाल करेंगे, उस पर ज्ञात अनुमानों की तुलना करें।