tempest-react-sdk 0.36.0 → 0.37.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"detector.cjs","names":[],"sources":["../../../src/vision/tasks/detector.ts"],"sourcesContent":["/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /**\n * Run detection on a single image.\n *\n * The returned envelope carries a {@link Speed} breakdown in `speed`,\n * mirroring Ultralytics' `results[0].speed`.\n */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new DetectionResults(\n boxes,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n}\n"],"mappings":"4RA+EA,IAAa,EAAb,MAAa,UAAiB,EAAA,UAAW,CAGhB,MACA,QACA,OACA,WACA,eACA,cACA,eARrB,YACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACF,CACE,MAAM,CAAO,EARI,KAAA,MAAA,EACA,KAAA,QAAA,EACA,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA,eAAA,EACA,KAAA,cAAA,EACA,KAAA,eAAA,CAGrB,CAGA,aAAa,OAAO,EAAoB,EAA2B,CAAC,EAAsB,CACtF,IAAM,EAAqB,EAAQ,MAAQ,OAC3C,GAAI,IAAS,OACT,MAAU,MAAM,8BAA8B,EAAK,sBAAsB,EAE7E,IAAM,EAAU,MAAM,EAAA,WAAW,OAAO,EAAO,CAAO,EAChD,EAAS,EAAA,cAAc,EAAQ,QAAU,OAAQ,CACnD,WAAY,EAAQ,UACxB,CAAC,EACK,EAAgC,CAAC,EACvC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ,IAC/B,EAAM,GAAK,EAAO,GAEtB,OAAO,IAAI,EACP,EACA,EACA,EACA,EACA,EAAQ,WAAa,CAAC,IAAK,GAAG,EAC9B,EAAQ,eAAiB,IACzB,EAAQ,cAAgB,IACxB,EAAQ,eAAiB,GAC7B,CACJ,CAGA,IAAI,MAAqB,CACrB,OAAO,KAAK,KAChB,CAGA,IAAI,QAA4B,CAC5B,OAAO,KAAK,OAChB,CAGA,IAAI,OAA0C,CAC1C,OAAO,KAAK,MAChB,CAGA,IAAI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K,EACL,aAAc,CAClB,CACJ,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAI,EAAW,OACf,EAAO,IAAI,aAAa,EAAI,CAAC,EAC7B,EAAM,IAAI,WAAW,CAAC,EACtB,EAAO,IAAI,aAAa,CAAC,EAC/B,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,IAAK,CACxB,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAI,GAAK,EAAE,QACX,EAAK,GAAK,EAAE,UAChB,CACA,OAAO,IAAI,EAAA,MAAM,EAAM,EAAK,EAAM,CAAS,CAC/C,CACJ"}
1
+ {"version":3,"file":"detector.cjs","names":[],"sources":["../../../src/vision/tasks/detector.ts"],"sourcesContent":["/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { resolveInputSize } from \"../core/graph\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /**\n * Model input `[width, height]` in pixels for letterboxing.\n *\n * Only used when the model's graph leaves its spatial axes dynamic: a graph\n * that declares a static size always wins, since that is the only shape ONNX\n * Runtime will accept. Defaults to `[640, 640]`.\n */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n resolveInputSize({\n graphShape: session.inputShape,\n requested: options.inputSize,\n fallback: [640, 640],\n }),\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /**\n * The `[width, height]` this task preprocesses to.\n *\n * Resolved at creation time from the model's graph when it declares a static\n * input, so reading it back tells you the resolution inference really runs at\n * — not merely what was requested.\n */\n get inputSize(): readonly [number, number] {\n return this._inputSize;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /**\n * Run detection on a single image.\n *\n * The returned envelope carries a {@link Speed} breakdown in `speed`,\n * mirroring Ultralytics' `results[0].speed`.\n */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new DetectionResults(\n boxes,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n}\n"],"mappings":"2TAsFA,IAAa,EAAb,MAAa,UAAiB,EAAA,UAAW,CAGhB,MACA,QACA,OACA,WACA,eACA,cACA,eARrB,YACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACF,CACE,MAAM,CAAO,EARI,KAAA,MAAA,EACA,KAAA,QAAA,EACA,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA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ACX,EAAK,GAAK,EAAE,UAChB,CACA,OAAO,IAAI,EAAA,MAAM,EAAM,EAAK,EAAM,CAAS,CAC/C,CACJ"}
@@ -2,13 +2,14 @@ import { RGBImage as e } from "../types.js";
2
2
  import { SpeedTimer as t } from "../core/timing.js";
3
3
  import { Boxes as n, DetectionResults as r } from "../results.js";
4
4
  import { resolveLabels as i } from "../labels.js";
5
- import { OrtSession as a } from "../core/session.js";
6
- import { loadImage as o } from "../io/image.js";
7
- import { letterbox as s, toCHW as c, toFloat32 as l, toFloat32Tensor as u } from "../preprocess/image.js";
8
- import { decodeYolo as d } from "../postprocess/detection.js";
9
- import { VisionTask as f } from "./base.js";
5
+ import { resolveInputSize as a } from "../core/graph.js";
6
+ import { OrtSession as o } from "../core/session.js";
7
+ import { loadImage as s } from "../io/image.js";
8
+ import { letterbox as c, toCHW as l, toFloat32 as u, toFloat32Tensor as d } from "../preprocess/image.js";
9
+ import { decodeYolo as f } from "../postprocess/detection.js";
10
+ import { VisionTask as p } from "./base.js";
10
11
  //#region src/vision/tasks/detector.ts
11
- var p = class p extends f {
12
+ var m = class m extends p {
12
13
  _head;
13
14
  _labels;
14
15
  _names;
@@ -22,9 +23,13 @@ var p = class p extends f {
22
23
  static async create(e, t = {}) {
23
24
  let n = t.head ?? "yolo";
24
25
  if (n !== "yolo") throw Error(`Unsupported detector head '${n}'. Supported: 'yolo'.`);
25
- let r = await a.create(e, t), o = i(t.labels ?? "coco", { numClasses: t.numClasses }), s = {};
26
- for (let e = 0; e < o.length; e++) s[e] = o[e];
27
- return new p(r, n, o, s, t.inputSize ?? [640, 640], t.confThreshold ?? .25, t.iouThreshold ?? .45, t.maxDetections ?? 300);
26
+ let r = await o.create(e, t), s = i(t.labels ?? "coco", { numClasses: t.numClasses }), c = {};
27
+ for (let e = 0; e < s.length; e++) c[e] = s[e];
28
+ return new m(r, n, s, c, a({
29
+ graphShape: r.inputShape,
30
+ requested: t.inputSize,
31
+ fallback: [640, 640]
32
+ }), t.confThreshold ?? .25, t.iouThreshold ?? .45, t.maxDetections ?? 300);
28
33
  }
29
34
  get head() {
30
35
  return this._head;
@@ -35,6 +40,9 @@ var p = class p extends f {
35
40
  get names() {
36
41
  return this._names;
37
42
  }
43
+ get inputSize() {
44
+ return this._inputSize;
45
+ }
38
46
  get numClasses() {
39
47
  return this._labels.length;
40
48
  }
@@ -42,9 +50,9 @@ var p = class p extends f {
42
50
  return this.predict(e, t);
43
51
  }
44
52
  async predict(e, n = {}) {
45
- let i = new t(), a = typeof e == "string" ? e : null, s = await o(e);
53
+ let i = new t(), a = typeof e == "string" ? e : null, o = await s(e);
46
54
  i.stage("load");
47
- let { tensor: c, scale: l, padLeft: u, padTop: f } = this._preprocess(s);
55
+ let { tensor: c, scale: l, padLeft: u, padTop: d } = this._preprocess(o);
48
56
  i.stage("preprocess");
49
57
  let p = await this._session.run({ [this._session.inputName]: c });
50
58
  i.stage("inference");
@@ -52,11 +60,11 @@ var p = class p extends f {
52
60
  if (m === void 0) throw Error("Detector model has no outputs.");
53
61
  let h = p[m];
54
62
  if (h === void 0) throw Error(`Detector model output ${m} missing from run() result.`);
55
- let g = d(h.data, h.dims, {
56
- originalWidth: s.width,
57
- originalHeight: s.height,
63
+ let g = f(h.data, h.dims, {
64
+ originalWidth: o.width,
65
+ originalHeight: o.height,
58
66
  padLeft: u,
59
- padTop: f,
67
+ padTop: d,
60
68
  scale: l,
61
69
  confThreshold: n.confThreshold ?? this._confThreshold,
62
70
  iouThreshold: n.iouThreshold ?? this._iouThreshold,
@@ -64,13 +72,13 @@ var p = class p extends f {
64
72
  }), _ = (n.classes === void 0 ? g : (() => {
65
73
  let e = new Set(n.classes);
66
74
  return g.filter((t) => e.has(t.classId));
67
- })()).map((e) => this._buildResult(s, e.bbox, e.classId, e.confidence)), v = [s.height, s.width], y = this._buildBoxes(_, v);
68
- return i.stage("postprocess"), [new r(y, _, this._names, s, v, a, i.speed())];
75
+ })()).map((e) => this._buildResult(o, e.bbox, e.classId, e.confidence)), v = [o.height, o.width], y = this._buildBoxes(_, v);
76
+ return i.stage("postprocess"), [new r(y, _, this._names, o, v, a, i.speed())];
69
77
  }
70
78
  _preprocess(e) {
71
- let [t, n] = this._inputSize, r = s(e, t, n);
79
+ let [t, n] = this._inputSize, r = c(e, t, n);
72
80
  return {
73
- tensor: u(c(l(r.image), r.image.width, r.image.height, 3), [
81
+ tensor: d(l(u(r.image), r.image.width, r.image.height, 3), [
74
82
  1,
75
83
  3,
76
84
  r.image.height,
@@ -114,6 +122,6 @@ var p = class p extends f {
114
122
  }
115
123
  };
116
124
  //#endregion
117
- export { p as Detector };
125
+ export { m as Detector };
118
126
 
119
127
  //# sourceMappingURL=detector.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"detector.js","names":[],"sources":["../../../src/vision/tasks/detector.ts"],"sourcesContent":["/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /**\n * Run detection on a single image.\n *\n * The returned envelope carries a {@link Speed} breakdown in `speed`,\n * mirroring Ultralytics' `results[0].speed`.\n */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new DetectionResults(\n boxes,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n}\n"],"mappings":";;;;;;;;;;AA+EA,IAAa,IAAb,MAAa,UAAiB,EAAW;CAGhB;CACA;CACA;CACA;CACA;CACA;CACA;CARrB,YACI,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACF;EADmB,AAEjB,MAAM,CAAO,GARI,KAAA,QAAA,GACA,KAAA,UAAA,GACA,KAAA,SAAA,GACA,KAAA,aAAA,GACA,KAAA,iBAAA,GACA,KAAA,gBAAA,GACA,KAAA,iBAAA;CAGrB;CAGA,aAAa,OAAO,GAAoB,IAA2B,CAAC,GAAsB;EACtF,IAAM,IAAqB,EAAQ,QAAQ;EAC3C,IAAI,MAAS,QACT,MAAU,MAAM,8BAA8B,EAAK,sBAAsB;EAE7E,IAAM,IAAU,MAAM,EAAW,OAAO,GAAO,CAAO,GAChD,IAAS,EAAc,EAAQ,UAAU,QAAQ,EACnD,YAAY,EAAQ,WACxB,CAAC,GACK,IAAgC,CAAC;EACvC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,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AS,GAAW,IAAY,IAAK,CAAC,GAAG,IAAM,IAAK,CAAC;GAC/E;GACA,IAAU,IAAI,EAAS,GAAK,GAAI,CAAE;EACtC,OACI,IAAU,IAAI,kBAAS,IAAI,WAAY,GAAG,GAAG,CAAC;EAGlD,IAAM,IAAY,KAAK,OAAO,MAAY,SAAS;EAEnD,OAAO;GACH;GACA;GACA;GACA;GACA,KAAK;GACL,MAAM;GACN,MAAM;GACN,KAAK;GACL,cAAc;EAClB;CACJ;CAEA,YACI,GACA,GACK;EACL,IAAM,IAAI,EAAW,QACf,IAAO,IAAI,aAAa,IAAI,CAAC,GAC7B,IAAM,IAAI,WAAW,CAAC,GACtB,IAAO,IAAI,aAAa,CAAC;EAC/B,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;GACxB,IAAM,IAAI,EAAW;GAMrB,AALA,EAAK,IAAI,KAAK,EAAE,KAAK,IACrB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAI,KAAK,EAAE,SACX,EAAK,KAAK,EAAE;EAChB;EACA,OAAO,IAAI,EAAM,GAAM,GAAK,GAAM,CAAS;CAC/C;AACJ"}
1
+ {"version":3,"file":"detector.js","names":[],"sources":["../../../src/vision/tasks/detector.ts"],"sourcesContent":["/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { resolveInputSize } from \"../core/graph\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /**\n * Model input `[width, height]` in pixels for letterboxing.\n *\n * Only used when the model's graph leaves its spatial axes dynamic: a graph\n * that declares a static size always wins, since that is the only shape ONNX\n * Runtime will accept. Defaults to `[640, 640]`.\n */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n resolveInputSize({\n graphShape: session.inputShape,\n requested: options.inputSize,\n fallback: [640, 640],\n }),\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /**\n * The `[width, height]` this task preprocesses to.\n *\n * Resolved at creation time from the model's graph when it declares a static\n * input, so reading it back tells you the resolution inference really runs at\n * — not merely what was requested.\n */\n get inputSize(): readonly [number, number] {\n return this._inputSize;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /**\n * Run detection on a single image.\n *\n * The returned envelope carries a {@link Speed} breakdown in `speed`,\n * mirroring Ultralytics' `results[0].speed`.\n */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new DetectionResults(\n boxes,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n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IAAI,GAAG,KAAK;GACxB,IAAM,IAAI,EAAW;GAMrB,AALA,EAAK,IAAI,KAAK,EAAE,KAAK,IACrB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAI,KAAK,EAAE,SACX,EAAK,KAAK,EAAE;EAChB;EACA,OAAO,IAAI,EAAM,GAAM,GAAK,GAAM,CAAS;CAC/C;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("../types.cjs"),t=require("../core/timing.cjs"),n=require("../results.cjs"),r=require("../labels.cjs"),i=require("../core/session.cjs"),a=require("../io/image.cjs"),o=require("../preprocess/image.cjs"),s=require("../postprocess/segmentation.cjs"),c=require("./base.cjs");var l=class l extends c.VisionTask{_head;_labels;_names;_inputSize;_confThreshold;_iouThreshold;_maxDetections;_maskThreshold;constructor(e,t,n,r,i,a,o,s,c){super(e),this._head=t,this._labels=n,this._names=r,this._inputSize=i,this._confThreshold=a,this._iouThreshold=o,this._maxDetections=s,this._maskThreshold=c}static async create(e,t={}){let n=t.head??`yolo-seg`;if(n!==`yolo-seg`)throw Error(`Unsupported segmenter head '${n}'. Supported: 'yolo-seg'.`);let a=await i.OrtSession.create(e,t),o=r.resolveLabels(t.labels??`coco`,{numClasses:t.numClasses}),s={};for(let e=0;e<o.length;e++)s[e]=o[e];return new l(a,n,o,s,t.inputSize??[640,640],t.confThreshold??.25,t.iouThreshold??.45,t.maxDetections??300,t.maskThreshold??.5)}get head(){return this._head}get labels(){return this._labels}get names(){return this._names}get numClasses(){return this._labels.length}async call(e,t={}){return this.predict(e,t)}async predict(e,r={}){let i=new t.SpeedTimer,o=typeof e==`string`?e:null,c=await a.loadImage(e);i.stage(`load`);let{tensor:l,scale:u,padLeft:d,padTop:f}=this._preprocess(c);i.stage(`preprocess`);let p=await this._session.run({[this._session.inputName]:l});i.stage(`inference`);let{perAnchor:m,prototypes:h}=this._splitOutputs(p),g=s.decodeYoloSeg(m.data,m.dims,h.data,h.dims,{numClasses:this._labels.length,inputWidth:this._inputSize[0],inputHeight:this._inputSize[1],originalWidth:c.width,originalHeight:c.height,padLeft:d,padTop:f,scale:u,confThreshold:r.confThreshold??this._confThreshold,iouThreshold:r.iouThreshold??this._iouThreshold,maxDetections:this._maxDetections,maskThreshold:this._maskThreshold}),_=(r.classes===void 0?g:(()=>{let e=new Set(r.classes);return g.filter(t=>e.has(t.classId))})()).map(e=>this._buildResult(c,e.bbox,e.classId,e.confidence,e.mask)),v=[c.height,c.width],y=this._buildBoxes(_,v),b=this._buildMasks(_,v);return i.stage(`postprocess`),[new n.SegmentationResults(y,b,_,this._names,c,v,o,i.speed())]}_preprocess(e){let[t,n]=this._inputSize,r=o.letterbox(e,t,n);return{tensor:o.toFloat32Tensor(o.toCHW(o.toFloat32(r.image),r.image.width,r.image.height,3),[1,3,r.image.height,r.image.width]),scale:r.scale,padLeft:r.padLeft,padTop:r.padTop}}_splitOutputs(e){let t,n;for(let r of this._session.outputNames){let i=e[r];i!==void 0&&(i.dims.length===3&&t===void 0?t=i:i.dims.length===4&&n===void 0&&(n=i))}if(t===void 0||n===void 0){let t=this._session.outputNames.map(t=>`${t}: ${JSON.stringify(e[t]?.dims??[])}`);throw Error(`Segmenter expected one 3-D and one 4-D output, got [${t.join(`, `)}].`)}return{perAnchor:t,prototypes:n}}_buildResult(t,n,r,i,a){let[o,s,c,l]=n.asIntXyxy(),u=Math.max(0,o),d=Math.max(0,s),f=Math.min(t.width,c),p=Math.min(t.height,l),m,h=a;if(f>u&&p>d&&a.data.length>0){let n=f-u,r=p-d,i=Math.min(a.width,n),o=Math.min(a.height,r),s=new Uint8Array(i*o*3);for(let e=0;e<o;e++){let n=((d+e)*t.width+u)*3,r=e*i*3,o=e*a.width;for(let e=0;e<i;e++)if(a.data[o+e]!==0){let i=n+e*3,a=r+e*3;s[a]=t.data[i],s[a+1]=t.data[i+1],s[a+2]=t.data[i+2]}}if(m=new e.RGBImage(s,i,o),i!==a.width||o!==a.height){let t=new Uint8Array(i*o);for(let e=0;e<o;e++)t.set(a.data.subarray(e*a.width,e*a.width+i),e*i);h=new e.Mask(t,i,o)}}else h=new e.Mask(new Uint8Array,0,0),m=new e.RGBImage(new Uint8Array,0,0);let g=this._names[r]??`class_${r}`;return{classId:r,className:g,confidence:i,bbox:n,cls:r,name:g,conf:i,box:n,mask:h,segmentedImage:m}}_buildBoxes(e,t){let r=e.length,i=new Float32Array(r*4),a=new Int32Array(r),o=new Float32Array(r);for(let t=0;t<r;t++){let n=e[t];i[t*4]=n.bbox.x1,i[t*4+1]=n.bbox.y1,i[t*4+2]=n.bbox.x2,i[t*4+3]=n.bbox.y2,a[t]=n.classId,o[t]=n.confidence}return new n.Boxes(i,a,o,t)}_buildMasks(e,t){let r=new Float32Array(e.length*4);for(let t=0;t<e.length;t++){let n=e[t];r[t*4]=n.bbox.x1,r[t*4+1]=n.bbox.y1,r[t*4+2]=n.bbox.x2,r[t*4+3]=n.bbox.y2}return new n.Masks(e.map(e=>e.mask),r,t)}};exports.Segmenter=l;
1
+ const e=require("../types.cjs"),t=require("../core/timing.cjs"),n=require("../results.cjs"),r=require("../labels.cjs"),i=require("../core/graph.cjs"),a=require("../core/session.cjs"),o=require("../io/image.cjs"),s=require("../preprocess/image.cjs"),c=require("../postprocess/segmentation.cjs"),l=require("./base.cjs");var u=class u extends l.VisionTask{_head;_labels;_names;_inputSize;_confThreshold;_iouThreshold;_maxDetections;_maskThreshold;constructor(e,t,n,r,i,a,o,s,c){super(e),this._head=t,this._labels=n,this._names=r,this._inputSize=i,this._confThreshold=a,this._iouThreshold=o,this._maxDetections=s,this._maskThreshold=c}static async create(e,t={}){let n=t.head??`yolo-seg`;if(n!==`yolo-seg`)throw Error(`Unsupported segmenter head '${n}'. Supported: 'yolo-seg'.`);let o=await a.OrtSession.create(e,t),s=r.resolveLabels(t.labels??`coco`,{numClasses:t.numClasses}),c={};for(let e=0;e<s.length;e++)c[e]=s[e];return new u(o,n,s,c,i.resolveInputSize({graphShape:o.inputShape,requested:t.inputSize,fallback:[640,640]}),t.confThreshold??.25,t.iouThreshold??.45,t.maxDetections??300,t.maskThreshold??.5)}get head(){return this._head}get labels(){return this._labels}get names(){return this._names}get inputSize(){return this._inputSize}get numClasses(){return this._labels.length}async call(e,t={}){return this.predict(e,t)}async predict(e,r={}){let i=new t.SpeedTimer,a=typeof e==`string`?e:null,s=await o.loadImage(e);i.stage(`load`);let{tensor:l,scale:u,padLeft:d,padTop:f}=this._preprocess(s);i.stage(`preprocess`);let p=await this._session.run({[this._session.inputName]:l});i.stage(`inference`);let{perAnchor:m,prototypes:h}=this._splitOutputs(p),g=c.decodeYoloSeg(m.data,m.dims,h.data,h.dims,{numClasses:this._labels.length,inputWidth:this._inputSize[0],inputHeight:this._inputSize[1],originalWidth:s.width,originalHeight:s.height,padLeft:d,padTop:f,scale:u,confThreshold:r.confThreshold??this._confThreshold,iouThreshold:r.iouThreshold??this._iouThreshold,maxDetections:this._maxDetections,maskThreshold:this._maskThreshold}),_=(r.classes===void 0?g:(()=>{let e=new Set(r.classes);return g.filter(t=>e.has(t.classId))})()).map(e=>this._buildResult(s,e.bbox,e.classId,e.confidence,e.mask)),v=[s.height,s.width],y=this._buildBoxes(_,v),b=this._buildMasks(_,v);return i.stage(`postprocess`),[new n.SegmentationResults(y,b,_,this._names,s,v,a,i.speed())]}_preprocess(e){let[t,n]=this._inputSize,r=s.letterbox(e,t,n);return{tensor:s.toFloat32Tensor(s.toCHW(s.toFloat32(r.image),r.image.width,r.image.height,3),[1,3,r.image.height,r.image.width]),scale:r.scale,padLeft:r.padLeft,padTop:r.padTop}}_splitOutputs(e){let t,n;for(let r of this._session.outputNames){let i=e[r];i!==void 0&&(i.dims.length===3&&t===void 0?t=i:i.dims.length===4&&n===void 0&&(n=i))}if(t===void 0||n===void 0){let t=this._session.outputNames.map(t=>`${t}: ${JSON.stringify(e[t]?.dims??[])}`);throw Error(`Segmenter expected one 3-D and one 4-D output, got [${t.join(`, `)}].`)}return{perAnchor:t,prototypes:n}}_buildResult(t,n,r,i,a){let[o,s,c,l]=n.asIntXyxy(),u=Math.max(0,o),d=Math.max(0,s),f=Math.min(t.width,c),p=Math.min(t.height,l),m,h=a;if(f>u&&p>d&&a.data.length>0){let n=f-u,r=p-d,i=Math.min(a.width,n),o=Math.min(a.height,r),s=new Uint8Array(i*o*3);for(let e=0;e<o;e++){let n=((d+e)*t.width+u)*3,r=e*i*3,o=e*a.width;for(let e=0;e<i;e++)if(a.data[o+e]!==0){let i=n+e*3,a=r+e*3;s[a]=t.data[i],s[a+1]=t.data[i+1],s[a+2]=t.data[i+2]}}if(m=new e.RGBImage(s,i,o),i!==a.width||o!==a.height){let t=new Uint8Array(i*o);for(let e=0;e<o;e++)t.set(a.data.subarray(e*a.width,e*a.width+i),e*i);h=new e.Mask(t,i,o)}}else h=new e.Mask(new Uint8Array,0,0),m=new e.RGBImage(new Uint8Array,0,0);let g=this._names[r]??`class_${r}`;return{classId:r,className:g,confidence:i,bbox:n,cls:r,name:g,conf:i,box:n,mask:h,segmentedImage:m}}_buildBoxes(e,t){let r=e.length,i=new Float32Array(r*4),a=new Int32Array(r),o=new Float32Array(r);for(let t=0;t<r;t++){let n=e[t];i[t*4]=n.bbox.x1,i[t*4+1]=n.bbox.y1,i[t*4+2]=n.bbox.x2,i[t*4+3]=n.bbox.y2,a[t]=n.classId,o[t]=n.confidence}return new n.Boxes(i,a,o,t)}_buildMasks(e,t){let r=new Float32Array(e.length*4);for(let t=0;t<e.length;t++){let n=e[t];r[t*4]=n.bbox.x1,r[t*4+1]=n.bbox.y1,r[t*4+2]=n.bbox.x2,r[t*4+3]=n.bbox.y2}return new n.Masks(e.map(e=>e.mask),r,t)}};exports.Segmenter=u;
2
2
  //# sourceMappingURL=segmenter.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"segmenter.cjs","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n const masks = this._buildMasks(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new SegmentationResults(\n boxes,\n masks,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":"+RAqFA,IAAa,EAAb,MAAa,UAAkB,EAAA,UAAW,CAGjB,MACA,QACA,OACA,WACA,eACA,cACA,eACA,eATrB,YACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACF,CACE,MAAM,CAAO,EATI,KAAA,MAAA,EACA,KAAA,QAAA,EACA,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA,eAAA,EACA,KAAA,cAAA,EACA,KAAA,eAAA,EACA,KAAA,eAAA,CAGrB,CAGA,aAAa,OAAO,EAAoB,EAA4B,CAAC,EAAuB,CACxF,IAAM,EAAsB,EAAQ,MAAQ,WAC5C,GAAI,IAAS,WACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B,EAElF,IAAM,EAAU,MAAM,EAAA,WAAW,OAAO,EAAO,CAAO,EAChD,EAAS,EAAA,cAAc,EAAQ,QAAU,OAAQ,CACnD,WAAY,EAAQ,UACxB,CAAC,EACK,EAAgC,CAAC,EACvC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ,IAC/B,EAAM,GAAK,EAAO,GAEtB,OAAO,IAAI,EACP,EACA,EACA,EACA,EACA,EAAQ,WAAa,CAAC,IAAK,GAAG,EAC9B,EAAQ,eAAiB,IACzB,EAAQ,cAAgB,IACxB,EAAQ,eAAiB,IACzB,EAAQ,eAAiB,EAC7B,CACJ,CAGA,IAAI,MAAsB,CACtB,OAAO,KAAK,KAChB,CAGA,IAAI,QAA4B,CAC5B,OAAO,KAAK,OAChB,CAGA,IAAI,OAA0C,CAC1C,OAAO,KAA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EACN,KAAM,EACN,IAAK,EACL,KAAM,EACN,gBACJ,CACJ,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAI,EAAW,OACf,EAAO,IAAI,aAAa,EAAI,CAAC,EAC7B,EAAM,IAAI,WAAW,CAAC,EACtB,EAAO,IAAI,aAAa,CAAC,EAC/B,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,IAAK,CACxB,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAI,GAAK,EAAE,QACX,EAAK,GAAK,EAAE,UAChB,CACA,OAAO,IAAI,EAAA,MAAM,EAAM,EAAK,EAAM,CAAS,CAC/C,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAO,IAAI,aAAa,EAAW,OAAS,CAAC,EACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,OAAQ,IAAK,CACxC,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,EAC7B,CACA,OAAO,IAAI,EAAA,MACP,EAAW,IAAK,GAAM,EAAE,IAAI,EAC5B,EACA,CACJ,CACJ,CACJ"}
1
+ {"version":3,"file":"segmenter.cjs","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { resolveInputSize } from \"../core/graph\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /**\n * Model input `[width, height]` in pixels for letterboxing.\n *\n * Only used when the model's graph leaves its spatial axes dynamic: a graph\n * that declares a static size always wins, since that is the only shape ONNX\n * Runtime will accept. Defaults to `[640, 640]`.\n */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n resolveInputSize({\n graphShape: session.inputShape,\n requested: options.inputSize,\n fallback: [640, 640],\n }),\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /**\n * The `[width, height]` this task preprocesses to.\n *\n * Resolved at creation time from the model's graph when it declares a static\n * input, so reading it back tells you the resolution inference really runs at\n * — not merely what was requested.\n */\n get inputSize(): readonly [number, number] {\n return this._inputSize;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n const masks = this._buildMasks(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new SegmentationResults(\n boxes,\n masks,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":"8TA4FA,IAAa,EAAb,MAAa,UAAkB,EAAA,UAAW,CAGjB,MACA,QACA,OACA,WACA,eACA,cACA,eACA,eATrB,YACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACF,CACE,MAAM,CAAO,EATI,KAAA,MAAA,EACA,KAAA,QAAA,EACA,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA,eAAA,EACA,KAAA,cAAA,EACA,KAAA,eAAA,EACA,KAAA,eAAA,CAGrB,CAGA,aAAa,OAAO,EAAoB,EAA4B,CAAC,EAAuB,CACxF,IAAM,EAAsB,EAAQ,MAAQ,WAC5C,GAAI,IAAS,WACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B,EAElF,IAAM,EAAU,MAAM,EAAA,WAAW,OAAO,EAAO,CAAO,EAChD,EAAS,EAAA,cAAc,EAAQ,QAAU,OAAQ,CACnD,WAAY,EAAQ,UACxB,CAAC,EACK,EAAgC,CAAC,EACvC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ,IAC/B,EAAM,GAAK,EAAO,GAEtB,OAAO,IAAI,EACP,EACA,EACA,EACA,EACA,EAAA,iBAAiB,CACb,WAAY,EAAQ,WACpB,UAAW,EAAQ,UACnB,SAAU,CAAC,IAAK,GAAG,CACvB,CAAC,EACD,EAAQ,eAAiB,IACzB,EAAQ,cAAgB,IACxB,EAAQ,eAAiB,IACzB,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AI,EAAA,KAAK,IAAI,WAAe,EAAG,CAAC,EAC5C,EAAiB,IAAI,EAAA,SAAS,IAAI,WAAe,EAAG,CAAC,EAGzD,IAAM,EAAY,KAAK,OAAO,IAAY,SAAS,IAEnD,MAAO,CACH,UACA,YACA,aACA,OACA,IAAK,EACL,KAAM,EACN,KAAM,EACN,IAAK,EACL,KAAM,EACN,gBACJ,CACJ,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAI,EAAW,OACf,EAAO,IAAI,aAAa,EAAI,CAAC,EAC7B,EAAM,IAAI,WAAW,CAAC,EACtB,EAAO,IAAI,aAAa,CAAC,EAC/B,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,IAAK,CACxB,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAI,GAAK,EAAE,QACX,EAAK,GAAK,EAAE,UAChB,CACA,OAAO,IAAI,EAAA,MAAM,EAAM,EAAK,EAAM,CAAS,CAC/C,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAO,IAAI,aAAa,EAAW,OAAS,CAAC,EACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,OAAQ,IAAK,CACxC,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,EAC7B,CACA,OAAO,IAAI,EAAA,MACP,EAAW,IAAK,GAAM,EAAE,IAAI,EAC5B,EACA,CACJ,CACJ,CACJ"}
@@ -2,13 +2,14 @@ import { Mask as e, RGBImage as t } from "../types.js";
2
2
  import { SpeedTimer as n } from "../core/timing.js";
3
3
  import { Boxes as r, Masks as i, SegmentationResults as a } from "../results.js";
4
4
  import { resolveLabels as o } from "../labels.js";
5
- import { OrtSession as s } from "../core/session.js";
6
- import { loadImage as c } from "../io/image.js";
7
- import { letterbox as l, toCHW as u, toFloat32 as d, toFloat32Tensor as f } from "../preprocess/image.js";
8
- import { decodeYoloSeg as p } from "../postprocess/segmentation.js";
9
- import { VisionTask as m } from "./base.js";
5
+ import { resolveInputSize as s } from "../core/graph.js";
6
+ import { OrtSession as c } from "../core/session.js";
7
+ import { loadImage as l } from "../io/image.js";
8
+ import { letterbox as u, toCHW as d, toFloat32 as f, toFloat32Tensor as p } from "../preprocess/image.js";
9
+ import { decodeYoloSeg as m } from "../postprocess/segmentation.js";
10
+ import { VisionTask as h } from "./base.js";
10
11
  //#region src/vision/tasks/segmenter.ts
11
- var h = class h extends m {
12
+ var g = class g extends h {
12
13
  _head;
13
14
  _labels;
14
15
  _names;
@@ -23,9 +24,13 @@ var h = class h extends m {
23
24
  static async create(e, t = {}) {
24
25
  let n = t.head ?? "yolo-seg";
25
26
  if (n !== "yolo-seg") throw Error(`Unsupported segmenter head '${n}'. Supported: 'yolo-seg'.`);
26
- let r = await s.create(e, t), i = o(t.labels ?? "coco", { numClasses: t.numClasses }), a = {};
27
+ let r = await c.create(e, t), i = o(t.labels ?? "coco", { numClasses: t.numClasses }), a = {};
27
28
  for (let e = 0; e < i.length; e++) a[e] = i[e];
28
- return new h(r, n, i, a, t.inputSize ?? [640, 640], t.confThreshold ?? .25, t.iouThreshold ?? .45, t.maxDetections ?? 300, t.maskThreshold ?? .5);
29
+ return new g(r, n, i, a, s({
30
+ graphShape: r.inputShape,
31
+ requested: t.inputSize,
32
+ fallback: [640, 640]
33
+ }), t.confThreshold ?? .25, t.iouThreshold ?? .45, t.maxDetections ?? 300, t.maskThreshold ?? .5);
29
34
  }
30
35
  get head() {
31
36
  return this._head;
@@ -36,6 +41,9 @@ var h = class h extends m {
36
41
  get names() {
37
42
  return this._names;
38
43
  }
44
+ get inputSize() {
45
+ return this._inputSize;
46
+ }
39
47
  get numClasses() {
40
48
  return this._labels.length;
41
49
  }
@@ -43,13 +51,13 @@ var h = class h extends m {
43
51
  return this.predict(e, t);
44
52
  }
45
53
  async predict(e, t = {}) {
46
- let r = new n(), i = typeof e == "string" ? e : null, o = await c(e);
54
+ let r = new n(), i = typeof e == "string" ? e : null, o = await l(e);
47
55
  r.stage("load");
48
- let { tensor: s, scale: l, padLeft: u, padTop: d } = this._preprocess(o);
56
+ let { tensor: s, scale: c, padLeft: u, padTop: d } = this._preprocess(o);
49
57
  r.stage("preprocess");
50
58
  let f = await this._session.run({ [this._session.inputName]: s });
51
59
  r.stage("inference");
52
- let { perAnchor: m, prototypes: h } = this._splitOutputs(f), g = p(m.data, m.dims, h.data, h.dims, {
60
+ let { perAnchor: p, prototypes: h } = this._splitOutputs(f), g = m(p.data, p.dims, h.data, h.dims, {
53
61
  numClasses: this._labels.length,
54
62
  inputWidth: this._inputSize[0],
55
63
  inputHeight: this._inputSize[1],
@@ -57,7 +65,7 @@ var h = class h extends m {
57
65
  originalHeight: o.height,
58
66
  padLeft: u,
59
67
  padTop: d,
60
- scale: l,
68
+ scale: c,
61
69
  confThreshold: t.confThreshold ?? this._confThreshold,
62
70
  iouThreshold: t.iouThreshold ?? this._iouThreshold,
63
71
  maxDetections: this._maxDetections,
@@ -69,9 +77,9 @@ var h = class h extends m {
69
77
  return r.stage("postprocess"), [new a(y, b, _, this._names, o, v, i, r.speed())];
70
78
  }
71
79
  _preprocess(e) {
72
- let [t, n] = this._inputSize, r = l(e, t, n);
80
+ let [t, n] = this._inputSize, r = u(e, t, n);
73
81
  return {
74
- tensor: f(u(d(r.image), r.image.width, r.image.height, 3), [
82
+ tensor: p(d(f(r.image), r.image.width, r.image.height, 3), [
75
83
  1,
76
84
  3,
77
85
  r.image.height,
@@ -146,6 +154,6 @@ var h = class h extends m {
146
154
  }
147
155
  };
148
156
  //#endregion
149
- export { h as Segmenter };
157
+ export { g as Segmenter };
150
158
 
151
159
  //# sourceMappingURL=segmenter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"segmenter.js","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n const masks = this._buildMasks(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new SegmentationResults(\n boxes,\n masks,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAqFA,IAAa,IAAb,MAAa,UAAkB,EAAW;CAGjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CATrB,YACI,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACF;EADmB,AAEjB,MAAM,CAAO,GATI,KAAA,QAAA,GACA,KAAA,UAAA,GACA,KAAA,SAAA,GACA,KAAA,aAAA,GACA,KAAA,iBAAA,GACA,KAAA,gBAAA,GACA,KAAA,iBAAA,GACA,KAAA,iBAAA;CAGrB;CAGA,aAAa,OAAO,GAAoB,IAA4B,CAAC,GAAuB;EACxF,IAAM,IAAsB,EAAQ,QAAQ;EAC5C,IAAI,MAAS,YACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B;EAElF,IAAM,IAAU,MAAM,EAAW,OAAO,GAAO,CAAO,GAChD,IAAS,EAAc,EAAQ,UAAU,QAAQ,EACnD,YAAY,EAAQ,WACxB,CAAC,GACK,IAAgC,CAAC;EACvC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAC/B,EAAM,KAAK,EAAO;EAEtB,OAAO,IAAI,EACP,GACA,GACA,GACA,GACA,EAAQ,aAAa,CAAC,KAAK,GAAG,GAC9B,EAAQ,iBAAiB,KACzB,EAAQ,gBAAgB,KACxB,EAAQ,iBAAiB,KACzB,EAAQ,iBAAiB,EAC7B;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D,IAAM,IAAY,KAAK,OAAO,MAAY,SAAS;EAEnD,OAAO;GACH;GACA;GACA;GACA;GACA,KAAK;GACL,MAAM;GACN,MAAM;GACN,KAAK;GACL,MAAM;GACN;EACJ;CACJ;CAEA,YACI,GACA,GACK;EACL,IAAM,IAAI,EAAW,QACf,IAAO,IAAI,aAAa,IAAI,CAAC,GAC7B,IAAM,IAAI,WAAW,CAAC,GACtB,IAAO,IAAI,aAAa,CAAC;EAC/B,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;GACxB,IAAM,IAAI,EAAW;GAMrB,AALA,EAAK,IAAI,KAAK,EAAE,KAAK,IACrB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAI,KAAK,EAAE,SACX,EAAK,KAAK,EAAE;EAChB;EACA,OAAO,IAAI,EAAM,GAAM,GAAK,GAAM,CAAS;CAC/C;CAEA,YACI,GACA,GACK;EACL,IAAM,IAAO,IAAI,aAAa,EAAW,SAAS,CAAC;EACnD,KAAK,IAAI,IAAI,GAAG,IAAI,EAAW,QAAQ,KAAK;GACxC,IAAM,IAAI,EAAW;GAIrB,AAHA,EAAK,IAAI,KAAK,EAAE,KAAK,IACrB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK;EAC7B;EACA,OAAO,IAAI,EACP,EAAW,KAAK,MAAM,EAAE,IAAI,GAC5B,GACA,CACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"segmenter.js","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { resolveInputSize } from \"../core/graph\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /**\n * Model input `[width, height]` in pixels for letterboxing.\n *\n * Only used when the model's graph leaves its spatial axes dynamic: a graph\n * that declares a static size always wins, since that is the only shape ONNX\n * Runtime will accept. Defaults to `[640, 640]`.\n */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n resolveInputSize({\n graphShape: session.inputShape,\n requested: options.inputSize,\n fallback: [640, 640],\n }),\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /**\n * The `[width, height]` this task preprocesses to.\n *\n * Resolved at creation time from the model's graph when it declares a static\n * input, so reading it back tells you the resolution inference really runs at\n * — not merely what was requested.\n */\n get inputSize(): readonly [number, number] {\n return this._inputSize;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n const masks = this._buildMasks(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new SegmentationResults(\n boxes,\n masks,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AA4FA,IAAa,IAAb,MAAa,UAAkB,EAAW;CAGjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CATrB,YACI,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACF;EADmB,AAEjB,MAAM,CAAO,GATI,KAAA,QAAA,GACA,KAAA,UAAA,GACA,KAAA,SAAA,GACA,KAAA,aAAA,GACA,KAAA,iBAAA,GACA,KAAA,gBAAA,GACA,KAAA,iBAAA,GACA,KAAA,iBAAA;CAGrB;CAGA,aAAa,OAAO,GAAoB,IAA4B,CAAC,GAAuB;EACxF,IAAM,IAAsB,EAAQ,QAAQ;EAC5C,IAAI,MAAS,YACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B;EAElF,IAAM,IAAU,MAAM,EAAW,OAAO,GAAO,CAAO,GAChD,IAAS,EAAc,EAAQ,UAAU,QAAQ,EACnD,YAAY,EAAQ,WACxB,CAAC,GACK,IAAgC,CAAC;EACvC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAC/B,EAAM,KAAK,EAAO;EAEtB,OAAO,IAAI,EACP,GACA,GACA,GACA,GACA,EAAiB;GACb,YAAY,EAAQ;GACpB,WAAW,EAAQ;GACnB,UAAU,CAAC,K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
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./vision/use-camera-stream.cjs"),t=require("./vision/core/exceptions.cjs"),n=require("./vision/types.cjs"),r=require("./vision/core/timing.cjs"),i=require("./vision/results.cjs"),a=require("./vision/labels.cjs"),o=require("./vision/core/providers.cjs"),s=require("./vision/core/session.cjs"),c=require("./vision/io/image.cjs"),l=require("./vision/preprocess/image.cjs"),u=require("./vision/postprocess/classification.cjs"),d=require("./vision/postprocess/detection.cjs"),f=require("./vision/postprocess/segmentation.cjs"),p=require("./vision/tasks/base.cjs"),m=require("./vision/tasks/classifier.cjs"),h=require("./vision/tasks/detector.cjs"),g=require("./vision/tasks/segmenter.cjs"),_=require("./vision/index.cjs"),v=require("./vision/luminance.cjs"),y=require("./vision/use-live-luminance.cjs");exports.BoundingBox=n.BoundingBox,exports.Boxes=i.Boxes,exports.COCO_CLASSES=a.COCO_CLASSES,exports.ClassificationResults=i.ClassificationResults,exports.Classifier=m.Classifier,exports.DEFAULT_PROVIDERS=o.DEFAULT_PROVIDERS,exports.DetectionResults=i.DetectionResults,exports.Detector=h.Detector,exports.ImageLoadError=t.ImageLoadError,exports.InferenceError=t.InferenceError,exports.LUMINANCE_SAMPLE_MAX_EDGE=v.LUMINANCE_SAMPLE_MAX_EDGE,exports.LabelMapError=t.LabelMapError,exports.LowLuminanceError=v.LowLuminanceError,exports.Mask=n.Mask,exports.Masks=i.Masks,exports.ModelLoadError=t.ModelLoadError,exports.OrtSession=s.OrtSession,exports.OrtVisionError=t.OrtVisionError,exports.Probs=i.Probs,exports.ProviderNotAvailableError=t.ProviderNotAvailableError,exports.RGBImage=n.RGBImage,exports.SegmentationResults=i.SegmentationResults,exports.Segmenter=g.Segmenter,exports.SpeedTimer=r.SpeedTimer,exports.VERSION=_.VERSION,exports.VisionTask=p.VisionTask,exports.batchedNms=d.batchedNms,exports.computeImageLuminance=v.computeImageLuminance,exports.decodeYolo=d.decodeYolo,exports.decodeYoloAnchors=d.decodeYoloAnchors,exports.decodeYoloSeg=f.decodeYoloSeg,exports.decodeYoloV8=d.decodeYoloV8,exports.decodeYoloV8Anchors=d.decodeYoloV8Anchors,exports.decodeYoloV8Seg=f.decodeYoloV8Seg,exports.fromCv2=l.fromCv2,exports.isLuminanceAcceptable=v.isLuminanceAcceptable,exports.letterbox=l.letterbox,exports.loadImage=c.loadImage,exports.nms=d.nms,exports.normalize=l.normalize,exports.resize=l.resize,exports.resolveLabels=a.resolveLabels,exports.resolveProviders=o.resolveProviders,exports.softmax=u.softmax,exports.toCHW=l.toCHW,exports.toCv2=l.toCv2,exports.toFloat32=l.toFloat32,exports.toFloat32Tensor=l.toFloat32Tensor,exports.toTensor=l.toTensor,exports.topK=u.topK,exports.useCameraStream=e.useCameraStream,exports.useLiveLuminance=y.useLiveLuminance;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./vision/use-camera-stream.cjs"),t=require("./vision/core/exceptions.cjs"),n=require("./vision/types.cjs"),r=require("./vision/core/timing.cjs"),i=require("./vision/results.cjs"),a=require("./vision/labels.cjs"),o=require("./vision/core/graph.cjs"),s=require("./vision/core/providers.cjs"),c=require("./vision/core/session.cjs"),l=require("./vision/io/image.cjs"),u=require("./vision/preprocess/image.cjs"),d=require("./vision/postprocess/classification.cjs"),f=require("./vision/postprocess/detection.cjs"),p=require("./vision/postprocess/segmentation.cjs"),m=require("./vision/tasks/base.cjs"),h=require("./vision/tasks/classifier.cjs"),g=require("./vision/tasks/detector.cjs"),_=require("./vision/tasks/segmenter.cjs"),v=require("./vision/index.cjs"),y=require("./vision/luminance.cjs"),b=require("./vision/use-live-luminance.cjs");exports.BoundingBox=n.BoundingBox,exports.Boxes=i.Boxes,exports.COCO_CLASSES=a.COCO_CLASSES,exports.ClassificationResults=i.ClassificationResults,exports.Classifier=h.Classifier,exports.DEFAULT_PROVIDERS=s.DEFAULT_PROVIDERS,exports.DetectionResults=i.DetectionResults,exports.Detector=g.Detector,exports.ImageLoadError=t.ImageLoadError,exports.InferenceError=t.InferenceError,exports.LUMINANCE_SAMPLE_MAX_EDGE=y.LUMINANCE_SAMPLE_MAX_EDGE,exports.LabelMapError=t.LabelMapError,exports.LowLuminanceError=y.LowLuminanceError,exports.Mask=n.Mask,exports.Masks=i.Masks,exports.ModelLoadError=t.ModelLoadError,exports.OrtSession=c.OrtSession,exports.OrtVisionError=t.OrtVisionError,exports.Probs=i.Probs,exports.ProviderNotAvailableError=t.ProviderNotAvailableError,exports.RGBImage=n.RGBImage,exports.SegmentationResults=i.SegmentationResults,exports.Segmenter=_.Segmenter,exports.SpeedTimer=r.SpeedTimer,exports.VERSION=v.VERSION,exports.VisionTask=m.VisionTask,exports.batchedNms=f.batchedNms,exports.computeImageLuminance=y.computeImageLuminance,exports.declaredShapesFrom=o.declaredShapesFrom,exports.decodeYolo=f.decodeYolo,exports.decodeYoloAnchors=f.decodeYoloAnchors,exports.decodeYoloSeg=p.decodeYoloSeg,exports.decodeYoloV8=f.decodeYoloV8,exports.decodeYoloV8Anchors=f.decodeYoloV8Anchors,exports.decodeYoloV8Seg=p.decodeYoloV8Seg,exports.fromCv2=u.fromCv2,exports.isLuminanceAcceptable=y.isLuminanceAcceptable,exports.letterbox=u.letterbox,exports.loadImage=l.loadImage,exports.nms=f.nms,exports.normalize=u.normalize,exports.resize=u.resize,exports.resolveInputSize=o.resolveInputSize,exports.resolveLabels=a.resolveLabels,exports.resolveProviders=s.resolveProviders,exports.softmax=d.softmax,exports.spatialInputSize=o.spatialInputSize,exports.toCHW=u.toCHW,exports.toCv2=u.toCv2,exports.toFloat32=u.toFloat32,exports.toFloat32Tensor=u.toFloat32Tensor,exports.toTensor=u.toTensor,exports.topK=d.topK,exports.useCameraStream=e.useCameraStream,exports.useLiveLuminance=b.useLiveLuminance;