# Detect objects with a vision-language model

> **About this page**
>
> - Kind: Example
> - Summary: Asks a vision-language model for the bounding boxes of chosen objects in every image, compares the counts with annotations, and draws boxes on samples.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/detect-objects
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/detect-objects`](https://github.com/swaleio/examples/tree/main/workflows/detect-objects) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/detect-objects/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/detect-objects/workflow.yaml).

Finds chosen objects in every image without training a detector. A
vision-language model answers each image with a JSON list of bounding boxes,
which a JSON schema enforces. DuckDB scales the boxes to pixels and compares
how many of each object the model found with how many the dataset annotates,
and a Python step draws the boxes on a few sample images.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch the model | [`swaleio/hf-download`](https://hub.swale.io/swaleio/hf-download) | `cpu-4` |
| Write one request per image, with the image inline and the JSON schema of the answer | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Detect | [`swaleio/vllm-batch`](https://hub.swale.io/swaleio/vllm-batch) | `a100-1` |
| Parse the boxes, scale them to pixels, count them per label | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Compare the counts with the annotations | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Draw the boxes on sample images | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), the compute its tasks are allocated.

Every step is its own task. An answer that reaches the token limit before its
JSON closes is counted and left out.

The comparison shows how the model's idea of an object matches the dataset's:
on the default images, the model and the annotations agree on hard hats, while
the annotations mark only some of the people and vests in each picture.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `model` | `Qwen/Qwen3-VL-2B-Instruct` | Vision-language model that answers with boxes as JSON, on a 0 to 1000 grid. |
| `images` | the test split of `keremberke/construction-safety-object-detection` | Parquet file or glob with a Hugging Face Image column, as a DuckDB path. |
| `objects` | `person, hardhat, safety vest` | What to find, separated by commas. |
| `limit` | `200` | Number of images. |
| `samples` | `8` | Number of images to draw the boxes on. |

The comparison step lists the default dataset's classes; for other images,
edit that step or leave its numbers aside. The download reads the secret
`hf_token`.

## Output

`detections.parquet` on the workspace, one row per box with its label and pixel
corners, and the drawn samples in `samples/`.

## Run it

You need the CLI, logged in to your account, and a project to add the workflow to; [Getting started](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   swale workflow create --project-name my-project --file workflow.yaml
   ```

   The command prints `Workflow created:` followed by the workflow's ID.

2. The workflow reads the secret `hf_token`. Create it as a project secret, or as an account secret that allows the project, as [Use secrets in workflows](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

3. Start a run with the workflow's ID:

   ```bash
   swale workflow run start --project-name my-project --workflow-id <workflow-id>
   ```

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="workflow.yaml"
name: Detect objects with a vision-language model
description: Asks a vision-language model for the bounding boxes of chosen objects in every image, compares the counts with annotations, and draws boxes on samples.
compute_type: cpu-4

inputs:
  model:
    description: Hugging Face repo id of a vision-language model that answers with bounding boxes as JSON.
    default: Qwen/Qwen3-VL-2B-Instruct
  images:
    description: Parquet file or glob with a Hugging Face Image column, as a DuckDB path.
    default: hf://datasets/keremberke/construction-safety-object-detection@~parquet/full/test/*.parquet
  objects:
    description: What to find, as the model should read it.
    default: person, hardhat, safety vest
  limit:
    description: Number of images.
    default: "200"
  samples:
    description: Number of images to draw the boxes on.
    default: "8"

entry_point: main

blocks:
  main:
    tasks:
      fetch_model:
        name: Fetch model
        uses: swaleio/hf-download
        args:
          repo: ${{inputs.model}}
          dest: ${{env.WORKFLOW_STORAGE}}/model
          token: ${{secrets.hf_token}}

      requests:
        name: Write detection requests
        uses: swaleio/duckdb
        args:
          sql: |
            CREATE TABLE images AS
              SELECT 'img-' || lpad((row_number() OVER () - 1)::VARCHAR, 5, '0') AS custom_id, *
              FROM (SELECT * FROM '${{inputs.images}}' LIMIT ${{inputs.limit}});
            COPY images TO '${{env.WORKFLOW_STORAGE}}/images.parquet' (FORMAT parquet);
            COPY (
              SELECT custom_id, 'POST' AS method, '/v1/chat/completions' AS url,
                     {'model': '${{env.WORKFLOW_STORAGE}}/model',
                      'messages': [{'role': 'user', 'content': [
                        {'type': 'image_url', 'image_url': {'url': 'data:image/jpeg;base64,' || base64(image.bytes)}},
                        {'type': 'text', 'text': $$Locate every $$ || $$${{inputs.objects}}$$ || $$ in the image. Answer with a JSON list of objects, each with "bbox_2d" as [x1, y1, x2, y2] and "label".$$}]}],
                      'max_tokens': 1024, 'temperature': 0,
                      'structured_outputs': {'json': {
                        'type': 'array', 'maxItems': 50,
                        'items': {'type': 'object',
                                  'properties': {'bbox_2d': {'type': 'array', 'items': {'type': 'number'}, 'minItems': 4, 'maxItems': 4},
                                                 'label': {'type': 'string'}},
                                  'required': ['bbox_2d', 'label']}}}} AS body
              FROM images
            ) TO '${{env.WORKFLOW_STORAGE}}/requests.jsonl' (FORMAT json);
            SELECT count(*) AS images FROM images;

      detect:
        name: Detect
        uses: swaleio/vllm-batch
        compute_type: a100-1
        start_on:
          - fetch_model
          - requests
        args:
          model: ${{env.WORKFLOW_STORAGE}}/model
          input_file: ${{env.WORKFLOW_STORAGE}}/requests.jsonl
          output_file: ${{env.WORKFLOW_STORAGE}}/results.jsonl

      collect:
        name: Collect boxes
        uses: swaleio/duckdb
        start_on:
          - detect
        args:
          sql: |
            -- An answer cut off at max_tokens is not valid JSON and is left out.
            CREATE TABLE answers AS
              SELECT custom_id, response.body.choices[1].message.content AS content
              FROM read_json('${{env.WORKFLOW_STORAGE}}/results.jsonl');
            SELECT count(*) FILTER (json_valid(content)) AS answered,
                   count(*) FILTER (NOT json_valid(content)) AS cut_off
              FROM answers;
            -- The model gives coordinates from 0 to 1000 across the image; scale them to pixels.
            CREATE TABLE detections AS
              WITH answers AS (
                SELECT custom_id, content::JSON AS boxes FROM answers WHERE json_valid(content))
              SELECT a.custom_id, i.image_id, lower(trim(b.label)) AS label,
                     b.bbox_2d[1] * i.width / 1000 AS x1, b.bbox_2d[2] * i.height / 1000 AS y1,
                     b.bbox_2d[3] * i.width / 1000 AS x2, b.bbox_2d[4] * i.height / 1000 AS y2
              FROM answers a
              JOIN '${{env.WORKFLOW_STORAGE}}/images.parquet' i USING (custom_id),
                   unnest(from_json(a.boxes, '[{"bbox_2d": ["DOUBLE"], "label": "VARCHAR"}]')) AS t(b);
            COPY detections TO '${{env.WORKFLOW_STORAGE}}/detections.parquet' (FORMAT parquet);
            SELECT label, count(*) AS boxes, count(DISTINCT custom_id) AS images
              FROM detections GROUP BY label ORDER BY boxes DESC;

      compare:
        name: Compare counts with annotations
        uses: swaleio/duckdb
        start_on:
          - collect
        args:
          sql: |
            -- The annotation classes of the default dataset, in their label order.
            CREATE TABLE classes AS
              SELECT unnest(['barricade', 'dumpster', 'excavators', 'gloves', 'hardhat', 'mask', 'no-hardhat',
                             'no-mask', 'no-safety vest', 'person', 'safety net', 'safety shoes', 'safety vest',
                             'dump truck', 'mini-van', 'truck', 'wheel loader']) AS label,
                     generate_subscripts(['barricade', 'dumpster', 'excavators', 'gloves', 'hardhat', 'mask', 'no-hardhat',
                             'no-mask', 'no-safety vest', 'person', 'safety net', 'safety shoes', 'safety vest',
                             'dump truck', 'mini-van', 'truck', 'wheel loader'], 1) - 1 AS category;
            CREATE TABLE annotated AS
              SELECT i.custom_id, c.label
              FROM '${{env.WORKFLOW_STORAGE}}/images.parquet' i,
                   unnest(i.objects.category) AS t(category)
              JOIN classes c USING (category);
            SELECT label,
                   (SELECT count(*) FROM annotated a WHERE a.label = l.label) AS annotated,
                   (SELECT count(*) FROM '${{env.WORKFLOW_STORAGE}}/detections.parquet' d WHERE d.label = l.label) AS detected
              FROM (SELECT trim(unnest(string_split($$${{inputs.objects}}$$, ','))) AS label) l;

      draw:
        name: Draw sample boxes
        uses: swaleio/python-3-13
        start_on:
          - collect
        args:
          script: |
            import io, os, subprocess, sys
            subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps",
                            "duckdb==2.0.1", "pillow==13.0.0"], check=True)
            sys.path.insert(0, "/tmp/deps")
            import duckdb
            from PIL import Image, ImageDraw

            storage = os.environ["WORKFLOW_STORAGE"]
            out = os.path.join(storage, "samples")
            os.makedirs(out, exist_ok=True)
            con = duckdb.connect()
            images = con.execute(
                f"SELECT custom_id, image.bytes FROM '{storage}/images.parquet' ORDER BY custom_id LIMIT ${{inputs.samples}}"
            ).fetchall()
            for custom_id, data in images:
                img = Image.open(io.BytesIO(data)).convert("RGB")
                draw = ImageDraw.Draw(img)
                boxes = con.execute(
                    f"SELECT label, x1, y1, x2, y2 FROM '{storage}/detections.parquet' WHERE custom_id = ?", [custom_id]
                ).fetchall()
                for label, x1, y1, x2, y2 in boxes:
                    draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
                    draw.text((x1 + 4, y1 + 4), label, fill="red")
                img.save(os.path.join(out, f"{custom_id}.jpg"))
                print(custom_id, len(boxes), "boxes")
```

## Licenses of the defaults

- Model: [Qwen/Qwen3-VL-2B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-2B-Instruct), Apache-2.0.
- Dataset: [keremberke/construction-safety-object-detection](https://huggingface.co/datasets/keremberke/construction-safety-object-detection), CC BY 4.0.
- Packages the draw step installs: DuckDB (MIT) and Pillow (MIT-CMU).
