> ## Documentation Index
> Fetch the complete documentation index at: https://docs.embededitor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# onAiDetectObjects

> Let Obfuscate's Detect find every face, license plate, document and screen in the photo: what the editor sends, what it takes back, which model did best in our measurements, and servers ready for SAM 3, Moondream 3 and YOLOv8n Face.

`onAiDetectObjects` detects objects in the photo for Obfuscate's **Detect**. With it, Obfuscate's pill shows **Detect**: one tap covers every face, license plate, document and screen in the photo with an area, in the look the person chose for the next one, and the person moves, resizes or removes each one as an area drawn by hand. [`obfuscate.detect()`](https://docs.embededitor.com/api-reference/commands/obfuscate-marks#detect) does the same from code, and with [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands) the AI's model gets it as its `obfuscate_detect` tool. Without it, Obfuscate has no **Detect**: the person draws each area.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-detect.mp4?fit=max&auto=format&n=AfjjkfPM_42cL5VY&q=85&s=4aeea4993ef4ec8c6225ca360b44c5dc" />

**Detect** in Obfuscate's pill covers the four faces of a café photo, each an area the person moves, resizes or removes. SAM 3's real answer, played four times as fast as it came.

![A waiter taking an order from three friends at a café table, Obfuscate open after Detect: each of the four faces under a blurred area with its corner marks, nothing selected; the menu shows Obfuscate's styles, its shapes, Detect, and the strength at 50%](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-detect.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=af6cbd0379ad14fb83f5c9d765e0e52a)

Each face under its area, at rest, nothing selected. SAM 3's real answer.

Asked in words, with [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands): “Hide every face and license plate” on a street with a parked car, for street photos and dashcam footage. The model calls `obfuscate_detect`, which covers the faces of the group, two in the background and the plate through this function, looks again up close, and covers 4 small faces left near a café itself. SAM 3's and Claude Sonnet 5.5's real answers; the commands in [Use Cases](https://docs.embededitor.com/ai/use-cases.md).

![People talking in a narrow street of an Italian old town, a cream hatchback parked beside them with its plate in view and a café's tables behind, labeled Original; beside it the same street, each face and the plate under a pixelated area; under it, the request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-street-privacy.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=bc40b09fd88fab4e7e541df2b16299e8)

> [!NOTE]
>
> Full and Trial only. The Free and the Lite accept `onAiDetectObjects` and ignore it.

## Wire It

In the page, `onAiDetectObjects` posts the photo and the texts to your server:

```ts page.ts theme={"dark"}
import type { EmbedEditorProps } from '@embededitor/full/react';

// Detect's object detection through your server's route (route.ts)
const onAiDetectObjects: EmbedEditorProps['onAiDetectObjects'] = async ({ image, signal, texts }) => {
	const body = new FormData();

	body.append('image', image);
	body.append('texts', JSON.stringify(texts));

	const res = await fetch('/api/ai-detect-objects', { body, method: 'POST', signal });

	if (!res.ok) {
		throw new Error('The search failed.');
	}

	return res.json();
};
```

On your server, a route finds them through one of [the servers below](#servers), here as a Next.js route handler:

```ts route.ts theme={"dark"}
import sam3 from './sam3';

export const POST = async (request: Request) => {
	const form = await request.formData();
	const image = form.get('image');
	const texts: string[] = JSON.parse(`${form.get('texts')}`);

	if (!(image instanceof Blob)) {
		return new Response('No image', { status: 400 });
	}

	const found = await sam3.detectObjects({ image, signal: request.signal, texts });

	return Response.json(found);
};
```

Pass the function to `EmbedEditor`, or as the same option of `mountEditor` and `openEditor`.

## What the Editor Sends

```ts theme={"dark"}
onAiDetectObjects?: (input: { image: Blob; signal: AbortSignal; texts: string[] }) => Promise<AiDetected[]>;
```

The editor calls it once a Detect, with every kind it covers in that one call.

**image** `Blob`

A JPEG of the photo as it was loaded, with the AI's own edits on it (a **Remove**, a **Generate**, an **Expand**, a cut background), at most 1024 px on its longer side: no crop, rotation, adjustments, filter, frame, annotations or Obfuscate areas, and no mark of any kind, the badge included. So the boxes you give back map straight to the photo's px, whatever the edit holds.

**texts** `string[]`

What to find, in English: `['face', 'license plate', 'document', 'screen']`, every time, unless your [`aiPrompts`](https://docs.embededitor.com/ai/customize-prompts) replace any of them (`detectFace`, `detectLicensePlate`, `detectDocument`, `detectScreen`), in that order.

**signal** `AbortSignal`

Aborts when the person stops Detect (Escape, or Stop in a request of the AI's), on `ask.stop()` and `ask.end()`, when the editor closes, is destroyed or leaves the page, and when another image opens. Pass it on to your `fetch` and to your model's call.

## What It Gives Back

Everything found, for every text: an empty list when nothing was found.

```ts theme={"dark"}
type AiDetected = { box: { bottom: number; left: number; right: number; top: number }; confidence?: number; text: string };
```

**box** `\{ bottom; left; right; top \}`

The thing's rectangle, as fractions from 0 to 1 of the image: `left` and `right` along its width, `top` and `bottom` along its height. A box that strays off the photo is held to its edge, and one with nothing of the photo in it is left out, as is an entry with no box or a box that isn't four numbers.

**confidence** `number`

From 0 to 1, when your model gives one. Detect leaves out a find under 0.5, and covers one with none.

**text** `string`

Which of `texts` this find answers.

Each find Detect keeps becomes an area over its box grown 10 % of its width and of its height on each side, level in the photo's frame. A find at least 80 % inside an area already on the photo makes none, so a second **Detect** adds nothing, and the photo holds 64 areas at most. All the areas of one **Detect** are one undo step, and none is selected.

Where your function finds nothing, or nothing at 0.5 and up, the AI's card says **Nothing Found**, with **Draw the areas to hide by hand.** under it, and `obfuscate.detect()` rejects with `NOT_FOUND`. When your function rejects, or resolves to something that is no list, the card says **Couldn’t Detect Areas**, with your error's message under it when your function rejected. A rejection that is no `Error`, an `Error` with no message, or one of the editor's own (`EmbedEditorError`) shows **Try again.** under the title. In each case `obfuscate.detect()` rejects with `AI_FAILED`, your error as its `cause` when it rejected. Either line goes at the person's next edit. Inside a request, when the model calls its `obfuscate_detect` tool, the card shows neither: the model gets the failure, or the nothing found, as its tool's answer.

## Which Model

On 2026-11-08 we tested the three models on four photos containing 11 faces, license plates, documents and screens. We checked each box by eye. The results are a small sample, not a guarantee that every item will be found.

| | SAM 3 | Moondream 3 | YOLOv8n Face |
| - | - | - | - |
| Provider | fal | fal | Runware |
| Found | 10 of 11 | 7 of 11 | 5 of 6 faces; no other kinds |
| Time | 2.7 to 4.7 s | 2.1 to 2.7 s | 2.3 to 3.3 s |
| Cost per Detect | US\$ 0.02 | about US\$ 0.0012 | US\$ 0.0006 |
| Confidence | Yes | No | No |

**SAM 3** is our recommendation: it found 10 of the 11 without false finds. **Moondream 3** costs less but missed smaller and distant items. **YOLOv8n Face** detects faces only and returns at most 20, so it can miss people in a crowd. The smallest plate tested was about 13 px wide in the 1024 px image the editor sends. Prices are from November 2026.

## Servers

Each server is one module for your server, with the same `detectObjects` function: it takes the editor's `image`, `texts` and `signal`, and resolves to the things found, in the editor's shape.

### SAM 3

Meta's SAM 3, through fal, finds every instance of a thing named in words. fal's endpoint takes one text a call, so the server puts the photo in fal's storage once, then calls once per text, all at once, each job run by [`fal-job.ts`](#the-fal-job). Each call costs US\$ 0.005 on fal's page of November 2026. It needs `@fal-ai/client` and `FAL_KEY`.

```ts sam3.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import type { AiDetected } from '@embededitor/full/react';

import falJob from './fal-job';

// The editor's onAiDetectObjects on Meta's SAM 3, through fal, for the site's server, where the key stays (FAL_KEY): the
// photo goes up to fal's storage once, then one call per text, all at once, since fal's SAM 3 takes one text a call
// (fal-job.ts runs each, with its time limit and its cancel on a stop). Each thing it finds comes back as a box, as the
// fractions of the photo fal gives, with its score as the confidence

// fal's endpoint
const ENDPOINT = 'fal-ai/sam-3/image';
// the most things one text may find: fal's ceiling
const MAX_MASKS = 32;

// what the editor asked for (`texts`) found in `image`, the photo as loaded with the AI's own edits and none of the
// rest: a box for each thing SAM 3 finds, with its score when fal gives one. `signal` stops the calls when the person
// stops
const detectObjects = async ({ image, signal, texts }: { image: Blob; signal: AbortSignal; texts: string[] }): Promise<AiDetected[]> => {
	const url = await fal.storage.upload(image);
	const found = await Promise.all(
		texts.map(async (text): Promise<AiDetected[]> => {
			const res = await falJob.run({
				endpoint: ENDPOINT,
				signal,
				subscribe: options => {
					return fal.subscribe(ENDPOINT, {
						...options,
						input: {
							apply_mask: false,
							image_url: url,
							include_boxes: true,
							include_scores: true,
							max_masks: MAX_MASKS,
							prompt: text,
							return_multiple_masks: true
						}
					});
				}
			});
			const boxes = res.data.boxes ?? [];
			const scores = res.data.scores ?? [];

			// fal's boxes are [center x, center y, width, height], as fractions of the photo
			return boxes.map(([x, y, width, height], index): AiDetected => {
				const thing: AiDetected = { box: { bottom: y + height / 2, left: x - width / 2, right: x + width / 2, top: y - height / 2 }, text };

				if (typeof scores[index] === 'number') {
					thing.confidence = scores[index];
				}

				return thing;
			});
		})
	);

	return found.flat();
};

export default { detectObjects };
```

The editor's playground runs this file, word for word.

### Moondream 3

Moondream 3, through fal, finds every instance of a thing named in words, like SAM 3, and gives no score, so its finds come back with no confidence. fal bills it by tokens, about US\$ 0.0003 a text in our measurements: the cheapest finder on fal. fal's endpoint takes one text a call, so the server puts the photo in fal's storage once, then calls once per text, all at once, each job run by [`fal-job.ts`](#the-fal-job). It needs `@fal-ai/client` and `FAL_KEY`.

```ts moondream.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import type { AiDetected } from '@embededitor/full/react';

import falJob from './fal-job';

// The editor's onAiDetectObjects on Moondream 3, through fal, for the site's server, where the key stays (FAL_KEY): the
// photo goes up to fal's storage once, then one call per text, all at once, since fal's Moondream takes one text a call
// (fal-job.ts runs each, with its time limit and its cancel on a stop). Each thing it finds comes back as a box, as the
// fractions of the photo fal gives. Moondream gives no score, so no confidence comes back

// fal's endpoint
const ENDPOINT = 'fal-ai/moondream3-preview/detect';

// what the editor asked for (`texts`) found in `image`, the photo as loaded with the AI's own edits and none of the
// rest: a box for each thing Moondream finds. `signal` stops the calls when the person stops
const detectObjects = async ({ image, signal, texts }: { image: Blob; signal: AbortSignal; texts: string[] }): Promise<AiDetected[]> => {
	const url = await fal.storage.upload(image);
	const found = await Promise.all(
		texts.map(async (text): Promise<AiDetected[]> => {
			const res = await falJob.run({
				endpoint: ENDPOINT,
				signal,
				subscribe: options => {
					return fal.subscribe(ENDPOINT, { ...options, input: { image_url: url, preview: false, prompt: text } });
				}
			});

			return res.data.objects.map((box): AiDetected => {
				return { box: { bottom: box.y_max, left: box.x_min, right: box.x_max, top: box.y_min }, text };
			});
		})
	);

	return found.flat();
};

export default { detectObjects };
```

The editor's playground runs this file, word for word.

### YOLOv8n Face

YOLOv8n Face, through Runware, finds faces and nothing else, for a Detect that hides faces alone. Only a text that asks for faces sends the photo, as a data URL, in one task POSTed by [`runware-task.ts`](https://docs.embededitor.com/ai/on-ai-edit-image#the-runware-task); any other text finds nothing. Each face comes back for each text that asked for faces, with no confidence: YOLOv8n gives no score. Runware gives 20 faces at most. The boxes are fractions of the photo, whose size the server reads from the photo's header with [`images.ts`](https://docs.embededitor.com/ai/on-ai-edit-image#the-image-library), on photon, which runs on Node and on Cloudflare Workers alike. It needs `images.ts`, `runware-task.ts`, [`limit.ts`](#the-time-limit), `@cf-wasm/photon` and `RUNWARE_API_KEY`, and no SDK: a plain `fetch`.

```ts faces-runware.ts theme={"dark"}
import type { AiDetected } from '@embededitor/full/react';

import images from './images';
import limit from './limit';
import runwareTask from './runware-task';

// The editor's onAiDetectObjects for faces alone, on YOLOv8n Face through Runware, for the site's server, where the key stays
// (RUNWARE_API_KEY): the cheapest find we measured (US$ 0.0006 a call, 2.3 to 3.3 s), and on our photos it found the
// faces SAM 3 found, but it finds nothing else. Only where a text asks for faces does the photo go, as a data URL, in one
// task (runware-task.ts POSTs it, within limit.ts's time limit, and it stops when the person stops); a text that asks for
// anything else finds nothing. Each face comes back for each text that asked for faces, as a box, as fractions of the
// photo from the px Runware gives, the photo's size read from its header (images.ts). YOLOv8n gives no score, so no
// confidence comes back. Runware gives 20 faces at most (maxDetections' cap): in a crowd, the faces past its 20 best are
// not found

// a text that asks for faces ('face', 'faces', 'every face')
const FACE = /\bfaces?\b/i;

// what the editor asked for (`texts`) found in `image`, the photo as loaded with the AI's own edits and none of the
// rest: a box for each face YOLOv8n Face finds, for each text that asks for faces, and nothing for any other. `signal`
// stops the call when the person stops
const detectObjects = async ({ image, signal, texts }: { image: Blob; signal: AbortSignal; texts: string[] }): Promise<AiDetected[]> => {
	const asked = texts.filter(text => {
		return FACE.test(text);
	});

	if (!asked.length) {
		return [];
	}

	const buffer = await image.arrayBuffer();
	const bytes = Buffer.from(buffer);
	const { height, width } = images.size(bytes);
	const made = await limit.within({
		signal,
		work: bounded => {
			return runwareTask.post<{ cost: number; detections?: { x_max: number; x_min: number; y_max: number; y_min: number }[]; status?: 'success' }>({
				signal: bounded,
				task: {
					inputs: { image: `data:${image.type || 'image/jpeg'};base64,${bytes.toString('base64')}` },
					model: 'runware:35@1',
					settings: { confidence: 0.4, maskBlur: 0, maskPadding: 0, maxDetections: 20 },
					taskType: 'imageMasking'
				}
			});
		}
	});
	const faces = made.detections ?? [];

	return asked.flatMap(text => {
		return faces.map((face): AiDetected => {
			return { box: { bottom: face.y_max / height, left: face.x_min / width, right: face.x_max / width, top: face.y_min / height }, text };
		});
	});
};

export default { detectObjects };
```

### The fal job

fal's client, when its signal aborts, stops waiting for the job but doesn't cancel it. The fal servers run each job through this module: when the person stops or [the time limit](#the-time-limit) passes, it stops waiting and asks fal to cancel the job by its id, even where the stop comes before fal gives the id, and it fetches the job's image within the same limit. A cancel drops a job fal hasn't started yet. A job fal has already started runs to its end and is billed: fal answers the cancel and finishes the job anyway (on 2026-11-10, a Bria cut canceled 6 seconds in completed at 25.5 seconds). It needs `@fal-ai/client` and `limit.ts` beside it.

```ts fal-job.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import limit from './limit';

// The fal servers' calls (retouch-fal.ts, background.ts, background-cheap.ts, sam3.ts, moondream.ts), for the site's
// server: each job runs within limit.ts's time limit, and when the person stops or the limit passes, the call stops
// waiting and asks fal to cancel the job, since fal's subscribe, on an abort, only stops waiting. fal drops a job it
// hasn't started yet; a job it has started runs to its end, and fal bills it. The image a job made is fetched within
// the same limit, and past it either call rejects in words the editor can show.

// the image fal put at `url`, fetched against `signal` and the time limit
const download = ({ signal, url }: { signal: AbortSignal; url: string }) => {
	return limit.within({
		signal,
		work: async bounded => {
			const res = await fetch(url, { signal: bounded });

			if (!res.ok) {
				throw new Error(`fal's image answered ${res.status}`);
			}

			return res.blob();
		}
	});
};

// fal's answer to `subscribe`, the job it starts on `endpoint` with the options it is given, against `signal` and the
// time limit: at the first of the two, fal is asked to cancel the job by the id it gave, as soon as it gives it where the
// stop came first, and the call rejects once fal has answered the cancel: a server on Cloudflare Workers drops a
// request still in flight once its own has ended. A job fal has started finishes anyway, and is billed
const run = <T>({
	endpoint,
	signal,
	subscribe
}: {
	endpoint: string;
	signal: AbortSignal;
	subscribe: (options: { abortSignal: AbortSignal; onEnqueue: (requestId: string) => void }) => Promise<T>;
}) => {
	return limit.within({
		signal,
		work: async bounded => {
			let requestId = '';
			let canceled: Promise<void> = Promise.resolve();
			const cancel = async () => {
				try {
					await fal.queue.cancel(endpoint, { requestId });
				} catch {
					// a job that ended first has nothing left to cancel
				}
			};
			const abort = () => {
				if (requestId) {
					canceled = cancel();
				}
			};

			bounded.addEventListener('abort', abort, { once: true });

			try {
				return await subscribe({
					abortSignal: bounded,
					onEnqueue: id => {
						requestId = id;

						if (bounded.aborted) {
							canceled = cancel();
						}
					}
				});
			} finally {
				bounded.removeEventListener('abort', abort);
				await canceled;
			}
		}
	});
};

export default { download, run };
```

### The time limit

Every call to a model gets two minutes, its image's fetch included: over twice the slowest call we measured of a model our servers run, Object Eraser's 50 seconds on Runware, which fills a Remove. This module gives the call a signal that aborts when the person stops or the two minutes pass, whichever comes first, and past them rejects with "The model took too long.", the words the editor shows. The fal job and the Runware server both run their calls through it.

```ts limit.ts theme={"dark"}
// The time limit of the servers' calls to a model (fal-job.ts runs fal's, retouch-runware.ts and faces-runware.ts
// Runware's), for the site's server: a call gets a signal that aborts when the person stops or TIMEOUT passes,
// whichever comes first. Past TIMEOUT, it rejects in words the editor can show (TOO_LONG), the timeout kept as its
// cause

// the longest a call, with the fetch of its image, may take, in ms: over twice the slowest call our measurements saw of
// a model the servers run (Object Eraser's 50 s, on Runware) and about twice the slowest of Runware's own examples
// (Object Eraser's 63 s), as long as Runware holds a task on an HTTP call before it answers that it is still running
const TIMEOUT = 120000;
// what a call past TIMEOUT rejects with, as does one its provider ends while the task still runs
const TOO_LONG = 'The model took too long.';

// what `work` gives with a signal that aborts at `signal` or past TIMEOUT, whichever comes first: past TIMEOUT, it rejects
// with TOO_LONG; else with the work's own error
const within = async <T>({ signal, work }: { signal: AbortSignal; work: (bounded: AbortSignal) => Promise<T> }) => {
	const bounded = AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT)]);

	try {
		return await work(bounded);
	} catch (err) {
		if (bounded.aborted && !signal.aborted) {
			throw new Error(TOO_LONG, { cause: err });
		}

		throw err;
	}
};

export { TOO_LONG };
export default { within };
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.