@ultralytics/yolo 0.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,168 @@
1
+ <!-- Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license -->
2
+
3
+ # Ultralytics Inference (Browser / WebGPU)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@ultralytics/yolo?logo=npm&logoColor=white&label=npm&color=CB3837)](https://www.npmjs.com/package/@ultralytics/yolo)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@ultralytics/yolo?logo=npm&logoColor=white&label=downloads&color=CB3837)](https://www.npmjs.com/package/@ultralytics/yolo)
7
+ [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](https://github.com/ultralytics/inference/blob/main/LICENSE)
8
+
9
+ [![Ultralytics Discord](https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue)](https://discord.com/invite/ultralytics)
10
+ [![Ultralytics Forums](https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue)](https://community.ultralytics.com/)
11
+ [![Ultralytics Reddit](https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue)](https://reddit.com/r/ultralytics)
12
+
13
+ Run [Ultralytics](https://ultralytics.com) YOLO models directly in the browser on
14
+ **WebGPU**, with no server and no Python. It covers detection, segmentation,
15
+ pose, classification, OBB, and semantic segmentation, with a compact
16
+ TypeScript API and a built-in `annotate()` for drawing.
17
+
18
+ ```ts
19
+ import { YOLO, annotate } from "@ultralytics/yolo";
20
+
21
+ const model = await YOLO.load("yolo26n.onnx");
22
+ const results = await model.predict("bus.jpg");
23
+ await annotate(document.querySelector("canvas"), "bus.jpg", results);
24
+ ```
25
+
26
+ It is a **library only** (no CLI; that is the native Rust crate). Under the hood
27
+ the engine is the `ultralytics-inference` Rust crate compiled to WebAssembly.
28
+ Inference runs on [ONNX Runtime Web](https://onnxruntime.ai/docs/tutorials/web/)
29
+ via [`ort-web`](https://ort.pyke.io/backends/web), and all pre/postprocessing,
30
+ colors, and the pose skeleton come from that shared Rust code, so results and
31
+ visuals match the native and Python paths.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ npm install @ultralytics/yolo
37
+ ```
38
+
39
+ ## Quick start
40
+
41
+ ```ts
42
+ import { YOLO, annotate } from "@ultralytics/yolo";
43
+
44
+ // Loads the model and initializes WebGPU + ONNX Runtime Web on first use.
45
+ const model = await YOLO.load("yolo26n.onnx");
46
+
47
+ const results = await model.predict("bus.jpg");
48
+ for (const box of results.boxes) {
49
+ console.log(box.name, box.conf.toFixed(2), [box.x1, box.y1, box.x2, box.y2]);
50
+ }
51
+
52
+ // Draw boxes, OBB, pose, and labels onto a canvas in one call (no canvas code).
53
+ await annotate(document.querySelector("canvas"), "bus.jpg", results);
54
+ ```
55
+
56
+ `predict()` accepts a URL/path, a `Blob`/`File`, raw encoded image bytes
57
+ (`Uint8Array`/`ArrayBuffer`), `ImageData`, an `HTMLImageElement`,
58
+ `HTMLCanvasElement`, `HTMLVideoElement`, or an `ImageBitmap`.
59
+
60
+ ```ts
61
+ const results = await model.predict(canvas, { conf: 0.25, iou: 0.7 });
62
+ console.log(model.device); // "webgpu" or "cpu"
63
+ ```
64
+
65
+ ### Webcam / video
66
+
67
+ Drawable sources (`<video>`, canvas, `ImageBitmap`, `ImageData`) take a
68
+ raw-pixel fast path with no re-encoding, so a render loop is smooth:
69
+
70
+ ```ts
71
+ const model = await YOLO.load("yolo26n.onnx");
72
+ async function frame() {
73
+ const results = await model.predict(video); // <video> element
74
+ await annotate(canvas, video, results);
75
+ requestAnimationFrame(frame);
76
+ }
77
+ ```
78
+
79
+ ## Models
80
+
81
+ A bare ONNX name resolves to the
82
+ [Ultralytics assets release](https://github.com/ultralytics/assets/releases):
83
+
84
+ ```ts
85
+ await YOLO.load("yolo26n.onnx"); // resolves to the release: .../download/v8.4.0/yolo26n.onnx
86
+ ```
87
+
88
+ Supports **yolo26**, **yolo11**, and **yolov8** in sizes `n/s/m/l/x` with task
89
+ suffixes `-seg`, `-pose`, `-cls`, `-obb`, and `-sem` (semantic, yolo26 only). A
90
+ value containing a `/` or a scheme is used as a URL/path as-is.
91
+
92
+ > **CORS note:** GitHub release assets do not send `Access-Control-Allow-Origin`,
93
+ > so a browser cannot fetch them cross-origin. Host the `.onnx` **same-origin**
94
+ > (e.g. `YOLO.load("/models/yolo26n.onnx")`) or behind a CORS-enabled origin /
95
+ > proxy. The bare-name shortcut is convenient when you mirror the assets on such
96
+ > a host.
97
+
98
+ ## Results shape
99
+
100
+ `predict()` resolves to a `Results` object shaped like the Ultralytics
101
+ `Results`:
102
+
103
+ Field names match the Rust/Ultralytics `Results` API 1-1:
104
+
105
+ | Field | Type | Tasks |
106
+ | ------------------ | --------------------------------------------------------- | --------------------- |
107
+ | `task` | `string` | all |
108
+ | `width` / `height` | `number` | all |
109
+ | `boxes` | `{ x1, y1, x2, y2, conf, cls, name, color }[]` | detect, segment, pose |
110
+ | `obb` | `{ x, y, w, h, angle, conf, cls, name, color }[]` | obb |
111
+ | `keypoints` | `{ points: [x, y, conf][], color }[]` | pose |
112
+ | `probs` | `{ top1, top5, top1conf, top5conf, name, color } \| null` | classify |
113
+ | `masks` | `Uint8Array` (RGBA overlay, `width*height*4`) | segment, semantic |
114
+ | `semantic` | `Uint16Array` (class id per pixel, `width*height`) | semantic |
115
+ | `speed` | `{ preprocess, inference, postprocess }` ms | all |
116
+
117
+ `model.names` is the class id to name map (like `model.names` in Python). Every
118
+ detection carries its Ultralytics palette `color`, and `annotate()` draws the
119
+ `masks` overlay and the pose skeleton with the same per-limb/keypoint colors as
120
+ the native renderer. None of this is duplicated in JS.
121
+
122
+ ## Requirements & notes
123
+
124
+ - **WebGPU** (Chrome/Edge, or Firefox with WebGPU enabled) from a **secure
125
+ context** (`https://` or `http://localhost`) gives the fast path. Without
126
+ WebGPU (older browsers, some phones), `YOLO.load` automatically falls back to a
127
+ portable **CPU/wasm** build that runs everywhere. Pick the device with
128
+ `YOLO.load(model, { device: "webgpu" | "cpu" })` (default `"auto"`). If WebGPU
129
+ cannot engage, the load falls back to CPU; `model.device` reports what actually
130
+ ran.
131
+ - **Model format**: export your model to ONNX with Ultralytics so the metadata
132
+ (task, class names, `imgsz`) is embedded:
133
+
134
+ ```python
135
+ from ultralytics import YOLO
136
+
137
+ YOLO("yolo26n.pt").export(format="onnx")
138
+ ```
139
+
140
+ - **Runtime assets**: on first load, `ort-web` fetches the ONNX Runtime Web wasm
141
+ bundle (~25 MB, browser-cached afterward) from `cdn.pyke.io`. If you set a
142
+ Content-Security-Policy, allow that origin in `script-src`/`connect-src`. To
143
+ avoid the CDN entirely, self-host the runtime and point to it:
144
+ ```ts
145
+ const model = await YOLO.load("yolo26n.onnx", { ortBaseUrl: "/ort/" });
146
+ ```
147
+ The folder must contain the ONNX Runtime Web entry scripts (`ort.webgpu.min.js`
148
+ and `ort.wasm.min.js` for the CPU fallback) plus the
149
+ `ort-wasm-simd-threaded.{jsep,asyncify,}.{mjs,wasm}` binaries.
150
+ - **Telemetry**: `ort-web` reports the page domain to pyke on first session
151
+ creation. See the [ort-web docs](https://ort.pyke.io/backends/web) to review or
152
+ disable it.
153
+
154
+ ## Building from source
155
+
156
+ This package builds the wasm from the Rust crate with
157
+ [`wasm-pack`](https://github.com/rustwasm/wasm-pack):
158
+
159
+ ```bash
160
+ npm run build # wasm-pack build + tsc
161
+ ```
162
+
163
+ Serve the built `dist/` + `pkg/` over `localhost` (a secure context) and open it
164
+ in a WebGPU browser.
165
+
166
+ ## License
167
+
168
+ AGPL-3.0. See the repository [LICENSE](https://github.com/ultralytics/inference/blob/main/LICENSE).
@@ -0,0 +1,166 @@
1
+ /** Axis-aligned box, pixel `xyxy`. */
2
+ export interface Box {
3
+ x1: number;
4
+ y1: number;
5
+ x2: number;
6
+ y2: number;
7
+ conf: number;
8
+ cls: number;
9
+ name: string;
10
+ color: string;
11
+ }
12
+ /** Oriented box, `xywhr` (angle in radians). */
13
+ export interface Obb {
14
+ x: number;
15
+ y: number;
16
+ w: number;
17
+ h: number;
18
+ angle: number;
19
+ conf: number;
20
+ cls: number;
21
+ name: string;
22
+ color: string;
23
+ }
24
+ /** Keypoints for one detection: `[x, y, conf]` per point. */
25
+ export interface Keypoints {
26
+ points: Array<[number, number, number]>;
27
+ color: string;
28
+ }
29
+ /** Classification probabilities. */
30
+ export interface Probs {
31
+ top1: number;
32
+ top5: number[];
33
+ top1conf: number;
34
+ top5conf: number[];
35
+ name: string;
36
+ color: string;
37
+ }
38
+ /** Per-stage timing in ms. */
39
+ export interface Speed {
40
+ preprocess: number;
41
+ inference: number;
42
+ postprocess: number;
43
+ }
44
+ /** Inference results, mirroring the Ultralytics `Results` API. */
45
+ export interface Results {
46
+ task: string;
47
+ width: number;
48
+ height: number;
49
+ boxes: Box[];
50
+ obb: Obb[];
51
+ keypoints: Keypoints[];
52
+ probs: Probs | null;
53
+ /** Segment/semantic masks as a translucent RGBA overlay (`width*height*4`), else empty. */
54
+ masks: Uint8Array;
55
+ /**
56
+ * Semantic segmentation class id per pixel, row-major (`width*height`),
57
+ * `undefined` for other tasks. The sentinel `65535` marks background or
58
+ * class-filtered pixels. The `masks` overlay is its renderable form.
59
+ */
60
+ semantic?: Uint16Array;
61
+ speed: Speed;
62
+ }
63
+ /** Options for {@link YOLO.load}. */
64
+ export interface LoadOptions {
65
+ /**
66
+ * Optional URL/path to the wasm binary (`ultralytics_inference_web_bg.wasm`).
67
+ * Only needed if your bundler does not resolve it automatically.
68
+ */
69
+ wasmUrl?: string | URL;
70
+ /**
71
+ * Optional base URL to self-host the ONNX Runtime Web build instead of
72
+ * fetching it from `cdn.pyke.io`. The directory must contain
73
+ * `ort.webgpu.min.js`, `ort-wasm-simd-threaded.jsep.wasm`, and
74
+ * `ort-wasm-simd-threaded.jsep.mjs`. Use an absolute URL ending in `/`.
75
+ */
76
+ ortBaseUrl?: string | URL;
77
+ /**
78
+ * Which device to run on, mirroring the native `device` option. `"auto"`
79
+ * (default) picks WebGPU when the browser has a working adapter, otherwise the
80
+ * portable CPU/wasm build. `"webgpu"` or `"cpu"` force one; the GPU adapter is
81
+ * chosen automatically by the browser. If WebGPU fails to engage the model
82
+ * falls back to CPU; read {@link YOLO.device} to see what actually ran.
83
+ */
84
+ device?: "auto" | "webgpu" | "cpu";
85
+ }
86
+ /** Options for {@link YOLO.predict}. */
87
+ export interface PredictOptions {
88
+ /** Confidence threshold. Default `0.25` (matches Ultralytics). */
89
+ conf?: number;
90
+ /** NMS IoU threshold. Default `0.7` (matches Ultralytics). */
91
+ iou?: number;
92
+ /**
93
+ * Keep only these class ids. Omit to keep all. Filters detections for
94
+ * detect/segment/pose/obb, and for semantic marks other pixels as background.
95
+ */
96
+ classes?: number[];
97
+ }
98
+ /** Options for {@link annotate}. */
99
+ export interface AnnotateOptions {
100
+ /** Box/line width in pixels. Defaults to a value scaled to the image size. */
101
+ lineWidth?: number;
102
+ /** Font CSS string. Defaults to a size scaled to the image. */
103
+ font?: string;
104
+ /** Draw `class_name confidence%` labels. Default `true`. */
105
+ labels?: boolean;
106
+ /** Draw pose keypoints and skeleton. Default `true`. */
107
+ keypoints?: boolean;
108
+ /** Keypoint confidence threshold for drawing. Default `0.25` (matches Ultralytics). */
109
+ keypointThreshold?: number;
110
+ }
111
+ /** Image-like inputs accepted by {@link YOLO.predict}. */
112
+ export type ImageInput = string | URL | Blob | ArrayBuffer | Uint8Array | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap;
113
+ /**
114
+ * A loaded YOLO model. Loading is asynchronous, so use {@link YOLO.load} instead
115
+ * of a constructor.
116
+ */
117
+ export declare class YOLO {
118
+ private readonly model;
119
+ private constructor();
120
+ /**
121
+ * Load a model and initialize the ONNX Runtime backend.
122
+ *
123
+ * @param source ONNX model URL/path, or its raw bytes.
124
+ * @param options Optional loader options (e.g. an explicit wasm URL).
125
+ */
126
+ static load(source: string | URL | ArrayBuffer | Uint8Array, options?: LoadOptions): Promise<YOLO>;
127
+ /** The model's task (`detect`, `segment`, `pose`, `classify`, `obb`, `semantic`). */
128
+ get task(): string;
129
+ /** The active device that ran inference (`"webgpu"` or `"cpu"`). */
130
+ get device(): string;
131
+ /** Class id -> name map (like Ultralytics `model.names`). */
132
+ get names(): Record<number, string>;
133
+ /**
134
+ * Run inference on an image.
135
+ *
136
+ * Drawable sources (`ImageData`, `HTMLImageElement`, `HTMLCanvasElement`,
137
+ * `HTMLVideoElement`, `ImageBitmap`) take a fast path that reads raw pixels
138
+ * with no re-encoding, ideal for webcam/video. URLs, `Blob`s, and raw bytes
139
+ * are decoded inside wasm.
140
+ *
141
+ * @param image The image to run on.
142
+ * @param options Confidence/IoU thresholds.
143
+ */
144
+ predict(image: ImageInput, options?: PredictOptions): Promise<Results>;
145
+ /** Release the underlying wasm model. Call when you are done with it. */
146
+ free(): void;
147
+ }
148
+ /**
149
+ * Draw inference results onto a canvas, on top of the source image.
150
+ *
151
+ * Handles every task: axis-aligned boxes, oriented boxes (OBB), pose keypoints
152
+ * with the COCO skeleton, and a top-1 banner for classification. The canvas is
153
+ * resized to the original image dimensions so detection coordinates line up.
154
+ *
155
+ * ```ts
156
+ * const results = await model.predict("bus.jpg");
157
+ * await annotate(document.querySelector("canvas"), "bus.jpg", results);
158
+ * ```
159
+ *
160
+ * @param canvas Target `<canvas>` (or `OffscreenCanvas`).
161
+ * @param image The same image passed to `predict` (URL, Blob, bytes, element, ...).
162
+ * @param results The `Results` returned by {@link YOLO.predict}.
163
+ * @param options Styling options.
164
+ */
165
+ export declare function annotate(canvas: HTMLCanvasElement | OffscreenCanvas, image: ImageInput, results: Results, options?: AnnotateOptions): Promise<void>;
166
+ export default YOLO;
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ // Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ /**
3
+ * Browser bindings for Ultralytics YOLO inference on WebGPU.
4
+ *
5
+ * Thin TypeScript wrapper around the WebAssembly module compiled from the
6
+ * `ultralytics-inference` Rust crate. Inference runs on the GPU through ONNX
7
+ * Runtime Web (bridged by `ort-web`); this module hides the wasm init, GPU
8
+ * setup, and image encoding behind a small `YOLO` class:
9
+ *
10
+ * ```ts
11
+ * import { YOLO } from "@ultralytics/yolo";
12
+ *
13
+ * const model = await YOLO.load("yolo26n.onnx");
14
+ * const results = await model.predict("bus.jpg");
15
+ * for (const box of results.boxes) {
16
+ * console.log(box.name, box.conf, box.x1, box.y1, box.x2, box.y2);
17
+ * }
18
+ * ```
19
+ */
20
+ import init, { YoloModel, start, pose_palette } from "../pkg/ultralytics_inference_web.js";
21
+ let poseSchemeCache = null;
22
+ /** The Ultralytics pose skeleton + per-keypoint/limb colors (constant). */
23
+ function poseScheme() {
24
+ poseSchemeCache ?? (poseSchemeCache = pose_palette());
25
+ return poseSchemeCache;
26
+ }
27
+ /**
28
+ * Resolve the device string passed to wasm. An explicit choice is honored;
29
+ * `"auto"` feature-detects a WebGPU adapter and otherwise falls back to CPU.
30
+ */
31
+ async function resolveDevice(pref) {
32
+ if (pref === "cpu" || pref === "webgpu")
33
+ return pref;
34
+ const gpu = navigator.gpu;
35
+ if (!gpu)
36
+ return "cpu";
37
+ try {
38
+ return (await gpu.requestAdapter()) ? "webgpu" : "cpu";
39
+ }
40
+ catch {
41
+ return "cpu";
42
+ }
43
+ }
44
+ /** Ultralytics model assets release (ONNX exports of yolo26 / yolo11 / yolov8). */
45
+ const ASSETS = "https://github.com/ultralytics/assets/releases/download/v8.4.0/";
46
+ /**
47
+ * Resolve a model reference to a URL. A bare ONNX name (e.g. `"yolo26n.onnx"`,
48
+ * `"yolo11s-seg.onnx"`, `"yolov8n.onnx"`) auto-downloads from the Ultralytics
49
+ * assets release; anything with a slash or scheme is used as-is.
50
+ */
51
+ function resolveModel(src) {
52
+ return /^[\w.-]+\.onnx$/i.test(src) ? ASSETS + src : src;
53
+ }
54
+ /**
55
+ * Reinterpret the wasm payload's little-endian `semantic` bytes as a
56
+ * `Uint16Array` of class ids (a zero-copy view), leaving every other field as-is.
57
+ */
58
+ function decodeResults(raw) {
59
+ const r = raw;
60
+ const sem = r.semantic;
61
+ r.semantic = sem && sem.length ? new Uint16Array(sem.buffer, sem.byteOffset, sem.length / 2) : undefined;
62
+ return r;
63
+ }
64
+ let initialized = false;
65
+ /** Initialize the wasm module exactly once. */
66
+ async function ensureInit(wasmUrl) {
67
+ if (initialized)
68
+ return;
69
+ await init(wasmUrl ? { module_or_path: wasmUrl } : undefined);
70
+ start();
71
+ initialized = true;
72
+ }
73
+ function isDrawable(input) {
74
+ return (input instanceof ImageData ||
75
+ input instanceof HTMLImageElement ||
76
+ input instanceof HTMLCanvasElement ||
77
+ input instanceof HTMLVideoElement ||
78
+ input instanceof ImageBitmap);
79
+ }
80
+ /** Fetch/normalize an encoded image input to bytes the wasm side can decode. */
81
+ async function toEncodedBytes(input) {
82
+ if (input instanceof Uint8Array)
83
+ return input;
84
+ if (input instanceof ArrayBuffer)
85
+ return new Uint8Array(input);
86
+ if (input instanceof Blob)
87
+ return new Uint8Array(await input.arrayBuffer());
88
+ const resp = await fetch(input);
89
+ if (!resp.ok)
90
+ throw new Error(`failed to fetch image: ${input} (${resp.status})`);
91
+ return new Uint8Array(await resp.arrayBuffer());
92
+ }
93
+ /** Read a drawable source as raw RGBA pixels (the fast path, no re-encoding). */
94
+ function toImageData(input) {
95
+ if (input instanceof ImageData) {
96
+ return { data: new Uint8Array(input.data.buffer), width: input.width, height: input.height };
97
+ }
98
+ let width;
99
+ let height;
100
+ if (input instanceof HTMLImageElement) {
101
+ [width, height] = [input.naturalWidth, input.naturalHeight];
102
+ }
103
+ else if (input instanceof HTMLVideoElement) {
104
+ [width, height] = [input.videoWidth, input.videoHeight];
105
+ }
106
+ else {
107
+ [width, height] = [input.width, input.height];
108
+ }
109
+ const canvas = makeCanvas(width, height);
110
+ const ctx = get2d(canvas, { willReadFrequently: true });
111
+ ctx.drawImage(input, 0, 0, width, height);
112
+ const img = ctx.getImageData(0, 0, width, height);
113
+ return { data: new Uint8Array(img.data.buffer), width, height };
114
+ }
115
+ function makeCanvas(width, height) {
116
+ if (typeof OffscreenCanvas !== "undefined")
117
+ return new OffscreenCanvas(width, height);
118
+ const canvas = document.createElement("canvas");
119
+ canvas.width = width;
120
+ canvas.height = height;
121
+ return canvas;
122
+ }
123
+ /** Get a 2D context or throw a clear error. */
124
+ function get2d(canvas, options) {
125
+ const ctx = canvas.getContext("2d", options);
126
+ if (!ctx)
127
+ throw new Error("could not acquire a 2D canvas context");
128
+ return ctx;
129
+ }
130
+ /**
131
+ * A loaded YOLO model. Loading is asynchronous, so use {@link YOLO.load} instead
132
+ * of a constructor.
133
+ */
134
+ export class YOLO {
135
+ constructor(model) {
136
+ this.model = model;
137
+ }
138
+ /**
139
+ * Load a model and initialize the ONNX Runtime backend.
140
+ *
141
+ * @param source ONNX model URL/path, or its raw bytes.
142
+ * @param options Optional loader options (e.g. an explicit wasm URL).
143
+ */
144
+ static async load(source, options) {
145
+ await ensureInit(options?.wasmUrl);
146
+ let bytes;
147
+ if (typeof source === "string" || source instanceof URL) {
148
+ const url = resolveModel(source.toString());
149
+ const resp = await fetch(url);
150
+ if (!resp.ok)
151
+ throw new Error(`failed to fetch model: ${url} (${resp.status})`);
152
+ bytes = new Uint8Array(await resp.arrayBuffer());
153
+ }
154
+ else {
155
+ bytes = source instanceof Uint8Array ? source : new Uint8Array(source);
156
+ }
157
+ const ortBaseUrl = options?.ortBaseUrl ? options.ortBaseUrl.toString() : undefined;
158
+ const device = await resolveDevice(options?.device);
159
+ return new YOLO(await YoloModel.load_bytes(bytes, ortBaseUrl, device));
160
+ }
161
+ /** The model's task (`detect`, `segment`, `pose`, `classify`, `obb`, `semantic`). */
162
+ get task() {
163
+ return this.model.task;
164
+ }
165
+ /** The active device that ran inference (`"webgpu"` or `"cpu"`). */
166
+ get device() {
167
+ return this.model.device;
168
+ }
169
+ /** Class id -> name map (like Ultralytics `model.names`). */
170
+ get names() {
171
+ return this.model.names;
172
+ }
173
+ /**
174
+ * Run inference on an image.
175
+ *
176
+ * Drawable sources (`ImageData`, `HTMLImageElement`, `HTMLCanvasElement`,
177
+ * `HTMLVideoElement`, `ImageBitmap`) take a fast path that reads raw pixels
178
+ * with no re-encoding, ideal for webcam/video. URLs, `Blob`s, and raw bytes
179
+ * are decoded inside wasm.
180
+ *
181
+ * @param image The image to run on.
182
+ * @param options Confidence/IoU thresholds.
183
+ */
184
+ async predict(image, options) {
185
+ const conf = options?.conf ?? 0.25;
186
+ const iou = options?.iou ?? 0.7;
187
+ const classes = options?.classes ? new Uint32Array(options.classes) : undefined;
188
+ if (isDrawable(image)) {
189
+ const { data, width, height } = toImageData(image);
190
+ return decodeResults(await this.model.predict_rgba(data, width, height, conf, iou, classes));
191
+ }
192
+ const bytes = await toEncodedBytes(image);
193
+ return decodeResults(await this.model.predict(bytes, conf, iou, classes));
194
+ }
195
+ /** Release the underlying wasm model. Call when you are done with it. */
196
+ free() {
197
+ this.model.free();
198
+ }
199
+ }
200
+ // Colors come from the Rust engine (the Ultralytics palette) on each detection,
201
+ // so there is no palette duplicated here.
202
+ /** Pick black or white text for readability over a given hex background. */
203
+ function textColorFor(hex) {
204
+ const r = parseInt(hex.slice(1, 3), 16);
205
+ const g = parseInt(hex.slice(3, 5), 16);
206
+ const b = parseInt(hex.slice(5, 7), 16);
207
+ // Perceived luminance (same threshold Ultralytics uses).
208
+ return r * 0.299 + g * 0.587 + b * 0.114 > 140 ? "#000000" : "#FFFFFF";
209
+ }
210
+ /**
211
+ * Draw inference results onto a canvas, on top of the source image.
212
+ *
213
+ * Handles every task: axis-aligned boxes, oriented boxes (OBB), pose keypoints
214
+ * with the COCO skeleton, and a top-1 banner for classification. The canvas is
215
+ * resized to the original image dimensions so detection coordinates line up.
216
+ *
217
+ * ```ts
218
+ * const results = await model.predict("bus.jpg");
219
+ * await annotate(document.querySelector("canvas"), "bus.jpg", results);
220
+ * ```
221
+ *
222
+ * @param canvas Target `<canvas>` (or `OffscreenCanvas`).
223
+ * @param image The same image passed to `predict` (URL, Blob, bytes, element, ...).
224
+ * @param results The `Results` returned by {@link YOLO.predict}.
225
+ * @param options Styling options.
226
+ */
227
+ export async function annotate(canvas, image, results, options) {
228
+ const bitmap = await resolveBitmap(image);
229
+ const width = results.width || bitmap.width;
230
+ const height = results.height || bitmap.height;
231
+ canvas.width = width;
232
+ canvas.height = height;
233
+ const ctx = get2d(canvas);
234
+ ctx.drawImage(bitmap, 0, 0, width, height);
235
+ // Segment: composite the translucent colored mask overlay from the engine.
236
+ const overlay = results.masks;
237
+ if (overlay && overlay.length === width * height * 4) {
238
+ const tmp = makeCanvas(width, height);
239
+ get2d(tmp).putImageData(new ImageData(new Uint8ClampedArray(overlay), width, height), 0, 0);
240
+ ctx.drawImage(tmp, 0, 0, width, height);
241
+ }
242
+ const lineWidth = options?.lineWidth ?? Math.max(2, Math.round(width / 320));
243
+ const fontSize = Math.max(12, Math.round(width / 40));
244
+ const font = options?.font ?? `${fontSize}px sans-serif`;
245
+ const showLabels = options?.labels ?? true;
246
+ const showKpts = options?.keypoints ?? true;
247
+ const kptThresh = options?.keypointThreshold ?? 0.25;
248
+ ctx.lineWidth = lineWidth;
249
+ ctx.font = font;
250
+ ctx.textBaseline = "top";
251
+ const label = (text, x, y, color) => {
252
+ if (!showLabels)
253
+ return;
254
+ const pad = Math.round(fontSize * 0.2);
255
+ const w = ctx.measureText(text).width + pad * 2;
256
+ const h = fontSize + pad * 2;
257
+ const ly = Math.max(0, y - h);
258
+ ctx.fillStyle = color;
259
+ ctx.fillRect(x, ly, w, h);
260
+ ctx.fillStyle = textColorFor(color);
261
+ ctx.fillText(text, x + pad, ly + pad);
262
+ };
263
+ // Axis-aligned boxes (detect / segment / pose).
264
+ for (const b of results.boxes) {
265
+ ctx.strokeStyle = b.color;
266
+ ctx.strokeRect(b.x1, b.y1, b.x2 - b.x1, b.y2 - b.y1);
267
+ label(`${b.name} ${(b.conf * 100).toFixed(0)}%`, b.x1, b.y1, b.color);
268
+ }
269
+ // Oriented boxes (obb): draw the rotated rectangle.
270
+ for (const o of results.obb) {
271
+ const color = o.color;
272
+ ctx.strokeStyle = color;
273
+ const cos = Math.cos(o.angle);
274
+ const sin = Math.sin(o.angle);
275
+ const hw = o.w / 2;
276
+ const hh = o.h / 2;
277
+ const corners = [
278
+ [-hw, -hh],
279
+ [hw, -hh],
280
+ [hw, hh],
281
+ [-hw, hh],
282
+ ].map(([dx, dy]) => [o.x + dx * cos - dy * sin, o.y + dx * sin + dy * cos]);
283
+ ctx.beginPath();
284
+ ctx.moveTo(corners[0][0], corners[0][1]);
285
+ for (let i = 1; i < corners.length; i++)
286
+ ctx.lineTo(corners[i][0], corners[i][1]);
287
+ ctx.closePath();
288
+ ctx.stroke();
289
+ label(`${o.name} ${(o.conf * 100).toFixed(0)}%`, corners[0][0], corners[0][1], color);
290
+ }
291
+ // Pose keypoints + skeleton, colored with the engine's pose palette (per-limb
292
+ // and per-keypoint), matching the native/Python renderer.
293
+ if (showKpts && results.keypoints.length) {
294
+ const { skeleton, keypoint_colors, limb_colors } = poseScheme();
295
+ const radius = Math.max(2, Math.round(width / 300));
296
+ ctx.lineWidth = Math.max(1, Math.round(lineWidth / 1.5));
297
+ for (const kp of results.keypoints) {
298
+ skeleton.forEach(([a, b], li) => {
299
+ const pa = kp.points[a];
300
+ const pb = kp.points[b];
301
+ if (!pa || !pb || pa[2] < kptThresh || pb[2] < kptThresh)
302
+ return;
303
+ ctx.strokeStyle = limb_colors[li] ?? kp.color;
304
+ ctx.beginPath();
305
+ ctx.moveTo(pa[0], pa[1]);
306
+ ctx.lineTo(pb[0], pb[1]);
307
+ ctx.stroke();
308
+ });
309
+ kp.points.forEach(([x, y, c], ki) => {
310
+ if (c < kptThresh)
311
+ return;
312
+ ctx.fillStyle = keypoint_colors[ki] ?? kp.color;
313
+ ctx.beginPath();
314
+ ctx.arc(x, y, radius, 0, Math.PI * 2);
315
+ ctx.fill();
316
+ });
317
+ }
318
+ ctx.lineWidth = lineWidth;
319
+ }
320
+ // Classification: top-1 banner.
321
+ if (results.probs) {
322
+ label(`${results.probs.name} ${(results.probs.top1conf * 100).toFixed(1)}%`, 0, fontSize + 8, results.probs.color);
323
+ }
324
+ }
325
+ /** Resolve any {@link ImageInput} to something `drawImage` accepts. */
326
+ async function resolveBitmap(input) {
327
+ if (typeof input === "string" || input instanceof URL) {
328
+ const resp = await fetch(input);
329
+ if (!resp.ok)
330
+ throw new Error(`failed to fetch image: ${input} (${resp.status})`);
331
+ return createImageBitmap(await resp.blob());
332
+ }
333
+ if (input instanceof Blob)
334
+ return createImageBitmap(input);
335
+ if (input instanceof Uint8Array)
336
+ return createImageBitmap(new Blob([input]));
337
+ if (input instanceof ArrayBuffer)
338
+ return createImageBitmap(new Blob([input]));
339
+ if (input instanceof ImageData)
340
+ return createImageBitmap(input);
341
+ // <img>, <canvas>, <video>, ImageBitmap are valid drawImage sources as-is;
342
+ // createImageBitmap on a live <video> can throw InvalidStateError.
343
+ return input;
344
+ }
345
+ export default YOLO;