TGraphX › Insights › Text-Prompt Object Detection and Segmentation in Images and Video
← Back to Insights

Text-Prompt Object Detection and Segmentation in Images and Video

Topic: Vision, multimodal and domain applications

Text prompt object detection means you type a phrase such as a saucer. and a model returns boxes for the image regions it matches to that phrase, even if "saucer" was never one of a fixed list of training classes. To get an outline instead of a box, each box is then passed to a second model, a promptable segmenter. Two things follow from that design, and both matter more than any architecture diagram. A returned box is a match, not a confirmation that the thing you named is there. And on video, running the pair on frames one at a time gives you independent guesses, not tracking.

This article explains the mechanism, then runs Grounding DINO and SAM 2.1 on a public-domain photograph and shows what they got right and wrong.

Closed vocabulary and open vocabulary

A closed-vocabulary detector has a fixed output head. A COCO-trained model such as a D-FINE or YOLO checkpoint scores each candidate box against 80 class indices. "Cup" and "spoon" are among them; "saucer" is not, and no amount of rewording will make the model report it.

An open-vocabulary (or open-set) detector takes the class names as an input. It compares image features with features of your text, so the set of things it can be asked about is not frozen at training time. That is not the same as knowing every concept: performance depends on whether the training data taught the model what your words look like.

Closed vocabulary Open vocabulary
Classes Fixed list baked into the head Supplied as text at run time
New category Needs labelled data and fine-tuning Can be tried by typing it; quality unknown until measured
Typical failure Nearest known class, or nothing Box on a look-alike, attributes ignored
Output label Class index Phrase or query that matched
What to test Per-class precision and recall Per-phrase precision and recall, including phrases for absent objects

How a phrase steers a detector

The shared idea is a common space for image regions and words. In a general form (a teaching formula, not the exact head of any one model):

s(i, j) = dot(v_i, t_j) and p(i, j) = sigmoid(a * s(i, j) + b)

Here v_i is the feature vector of candidate region i, t_j is the feature vector of text unit j (a word piece or a whole query), dot is the inner product, a and b are a scale and offset that a model may learn, and p(i, j) is the match score between 0 and 1.

How the two sides are produced differs a lot between families:

  • CLIP trains an image encoder and a text encoder with a contrastive objective on image and caption pairs, so a whole image and a sentence can be compared by cosine similarity. It is not a detector by itself: it has no boxes.
  • OWL-ViT and OWLv2 adapt a vision transformer of that kind for detection. Each image patch token predicts a box and a class embedding, and the class embedding is compared with the embedding of each text query.
  • Grounding DINO starts from a DETR-style detector and mixes language into several stages. A text backbone produces one feature per token and an image backbone produces multi-scale features. A feature enhancer lets the two attend to each other, language-guided query selection picks image locations that respond to the text to start the decoder queries, and a cross-modality decoder refines them into boxes. Classification is the dot product of each decoder query with each text token feature, trained with a focal loss; box regression uses L1 and generalized IoU losses.

One detail explains a lot of prompt behaviour. The Grounding DINO authors block attention between unrelated category names inside the text encoder (they call this a "sub-sentence level" representation), and the periods in a prompt are what delimit those categories.

From a text prompt and an image to grounded boxes

1. Encode2. Enhance3. Select queries4. Decode5. Threshold
Inputs and outputs of every stage
stageinputoutputwhat happens
1. Encodeimage, text promptimage features, token featuresAn image backbone and a text backbone work separately at first.
2. Enhanceboth feature setsmutually aware featuresSelf attention within each side and cross attention between image and text.
3. Select queriesenhanced featuresstarting decoder queriesImage positions that respond most to the text seed the queries.
4. Decodequeries, image, textboxes and token logitsEach query predicts a box and one logit for every text token.
5. Thresholdboxes and token scoresboxes with phrasesKeep boxes whose best token score passes; name them from the matching tokens.

Stage 1 of 5, Encode. Input: image, text prompt. Output: image features, token features.

Step through the stages of a Grounding DINO style detector. This is a simplified view of the published design. A schematic of the stages as described by the author; nothing is executed.

Several models share the name DINO

These are easy to mix up, and they do different jobs:

Name What it is Takes text?
Grounding DINO Open-set detector conditioned on a text prompt Yes
DINO (DETR with Improved DeNoising Anchor Boxes) Closed-set DETR-style detector that Grounding DINO builds on No
DINO, DINOv2, DINOv3 (self-supervised) Vision backbones trained without labels, used for features and similarity Not the vision backbone itself
D-FINE Closed-vocabulary detector in the DETR family; not a DINO model No

Prompts and the two thresholds

In the Hugging Face implementation used below, pass either a list of phrases without periods (the processor lower-cases and joins them) or a single lower-case string in which every phrase ends with a period, for example a cup. a saucer. a spoon.

Post-processing has two thresholds, and they do different things. In transformers 5.24.1 a sigmoid is applied to the per-token logits of each query, and the box score is the largest of those values. The box threshold (the argument is named threshold) discards boxes whose score is too low. The text threshold (text_threshold) decides which tokens are strong enough to appear in the phrase attached to a surviving box. Raising the text threshold changes names, not boxes.

The score is a match strength. It is not a calibrated probability that the object exists, and scores from different phrases, checkpoints or model families are not on one scale.

From boxes to masks

The Segment Anything Model (SAM) takes an image plus a prompt such as points or a box and returns a mask. It has an image encoder, a prompt encoder and a light mask decoder, and for an ambiguous prompt it can return several candidate masks, each with the model's own estimate of mask quality. SAM does not name anything. The label comes from whatever produced the box, and the composition "text-conditioned detector, then box-prompted segmenter" is what the Grounded SAM report assembles.

Grounded boxes become masks, labels stay from the detector

Text promptOpen-set detectorBoxes with phrasesLabelled masksImagePromptablesegmenterHuman reviewboxlabelmask
The same diagram as a table
boxarrows todetail
Text promptOpen-set detector—
Open-set detectorBoxes with phrases—
Boxes with phrasesPromptable segmenter (box); Labelled masks (label)—
Labelled masksHuman review—
ImageOpen-set detector—
Promptable segmenterLabelled masks (mask)Receives the image and the box coordinates, not the phrase.
Human review——

7 boxes and 7 arrows. No box is selected.

Follow where the name and the outline come from. The segmenter never checks the name. A schematic drawn from the author's description: nothing is executed or measured.

Detection, segmentation and classification

Task What you give What you get Question answered Evaluate with
Image classification Image (plus class names or prompts if open) Scores for the whole image What is in this picture? Per-class precision and recall
Object detection Image plus class list or text prompt Boxes, names, scores Where are the instances? IoU-matched precision and recall, mAP
Promptable segmentation Image plus points or a box Masks without names Which pixels belong to this thing? Mask IoU
Grounded segmentation Image plus text Masks carrying the detector's names Which pixels match this phrase? Detection errors and mask IoU, separately

SAM 2 extends promptable segmentation to video with a memory of earlier frames, which lets a mask be carried forward. That is a different procedure from calling an image segmenter on each frame, which is what the rest of this article does.

Which model does what

Model used or named here Prompt it takes Output In the run below
Grounding DINO tiny Text Boxes with phrases Run; weight file about 689 MB
OWL-ViT, OWLv2 List of text queries Boxes with the matching query Not run
SAM 2.1 tiny Box or points Masks Run; weight file about 156 MB
D-FINE-N, COCO-trained None Boxes from 80 classes Run; weight file about 15 MB

The three checkpoints that were run need PyTorch and Transformers. They were run on a GPU only, so this article says nothing about their speed or behaviour on a CPU.

A reproducible run

The two photographs are CC0 images that ship with scikit-image: a coffee cup on a saucer with a spoon, and a close-up of a cat. With scikit-image installed, from skimage import data and then Image.fromarray(data.coffee()).save("coffee.png") writes the first file; save data.chelsea() as chelsea.png in the same way. The code needs PyTorch, Transformers and Pillow, and downloads public checkpoints.

Environment of the recorded output: Python 3.13.12, PyTorch 2.15.0, transformers 5.24.1, Pillow 13.0.0, one NVIDIA GeForce RTX 5080, run on 2026-11-27. Checkpoints are pinned by revision. Loading the SAM 2.1 checkpoint into Sam2Model printed a warning that it is typed as a video model; the image calls below ran.

python
import torch
from PIL import Image
from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor

MODEL = "IDEA-Research/grounding-dino-tiny"
REVISION = "a2bb814dd30d776dcf7e30523b00659f4f141c71"
device = "cuda" if torch.cuda.is_available() else "cpu"

processor = AutoProcessor.from_pretrained(MODEL, revision=REVISION)
model = AutoModelForZeroShotObjectDetection.from_pretrained(MODEL, revision=REVISION).to(device).eval()


def ground(image, prompt, threshold=0.25, text_threshold=0.25):
    """Return [(phrase, score, [x1, y1, x2, y2]), ...] for one image and one prompt string."""
    inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
    with torch.inference_mode():
        outputs = model(**inputs)
    result = processor.post_process_grounded_object_detection(
        outputs, inputs.input_ids, threshold=threshold, text_threshold=text_threshold,
        target_sizes=[image.size[::-1]])[0]
    return [(phrase, round(float(score), 3), [round(float(v)) for v in box])
            for phrase, score, box in zip(result["text_labels"], result["scores"], result["boxes"])]


coffee = Image.open("coffee.png").convert("RGB")      # 600 x 400
for prompt in ["a cup. a saucer. a spoon.", "a spoon.", "a fork.", "a blue saucer.",
               "a glass of orange juice.", "a spoon to the left of the cup.", "a cup.", "a cup"]:
    print(repr(prompt), ground(coffee, prompt))
text
'a cup. a saucer. a spoon.' [('a saucer', 0.74, [75, 63, 481, 391]), ('a cup', 0.82, [170, 17, 412, 306]), ('a spoon', 0.731, [324, 64, 427, 329])]
'a spoon.' [('a spoon', 0.68, [325, 65, 426, 327])]
'a fork.' [('a fork', 0.668, [324, 64, 426, 327])]
'a blue saucer.' [('a blue saucer', 0.853, [75, 63, 482, 390])]
'a glass of orange juice.' [('a glass', 0.776, [170, 16, 413, 305]), ('juice', 0.323, [204, 94, 370, 193])]
'a spoon to the left of the cup.' [('cup', 0.543, [170, 16, 410, 298]), ('a spoon', 0.504, [324, 65, 426, 327]), ('a spoon', 0.28, [315, 221, 373, 261])]
'a cup.' [('a cup', 0.797, [170, 16, 411, 304])]
'a cup' []

The first line is the success case: cup, saucer and spoon each get one box. The rest is more useful.

Prompt What is true What came back
a fork. There is no fork The spoon, labelled fork, 0.668
a blue saucer. The saucer is reddish brown The saucer, labelled blue, 0.853
a glass of orange juice. A cup of coffee The cup as "a glass" (0.776) and the coffee as "juice" (0.323)
a spoon to the left of the cup. The spoon is to the right The spoon anyway (0.504), plus a second spoon box and the cup
a cup. then a cup One cup One box with the period; nothing above threshold without it

Read the first two rows again. Neither the noun nor the colour had to be true for a confident box. The Grounding DINO paper itself reports that the model produces false positives in some cases, and that open-set detectors it studied do not handle referring expressions well without fine-tuning.

No box threshold rescues the fork case cleanly: a fork. scored 0.668 and a spoon. asked on its own scored 0.680 on the same pixels. A threshold between them would be tuned to this one photograph. The phrases also influence each other: the spoon scored 0.731 inside the three-phrase prompt and 0.680 alone, so evaluate with the prompt string you will actually deploy.

For contrast: a closed vocabulary

For contrast, a COCO-trained D-FINE-N checkpoint, which takes no text at all:

python
from transformers import AutoImageProcessor, AutoModelForObjectDetection

DFINE = "ustc-community/dfine-nano-coco"
DFINE_REVISION = "066438d3d8f0da137a37b38fdf3368fd4afceced"
closed_processor = AutoImageProcessor.from_pretrained(DFINE, revision=DFINE_REVISION)
closed = AutoModelForObjectDetection.from_pretrained(DFINE, revision=DFINE_REVISION).to(device).eval()

for name in ["coffee.png", "chelsea.png"]:
    image = Image.open(name).convert("RGB")
    inputs = closed_processor(images=image, return_tensors="pt").to(device)
    with torch.inference_mode():
        outputs = closed(**inputs)
    found = closed_processor.post_process_object_detection(
        outputs, threshold=0.5, target_sizes=[image.size[::-1]])[0]
    print(name, [(closed.config.id2label[int(i)], round(float(s), 2))
                 for i, s in zip(found["labels"], found["scores"])])
text
coffee.png [('cup', 0.9), ('diningtable', 0.84), ('spoon', 0.82), ('spoon', 0.69), ('spoon', 0.57), ('spoon', 0.56), ('spoon', 0.5)]
chelsea.png [('cat', 0.95)]

It has no saucer class, so it cannot report one. It does have a fork class and, correctly for this picture, reported no fork at this threshold. It also returned several overlapping "spoon" boxes for one spoon, a reminder that a closed vocabulary does not remove the need for review.

Masks from the boxes

Next, the grounded boxes go to SAM 2.1 (tiny). Two boxes are added on purpose: the false "fork" and a rectangle drawn by hand around no object, across the edge of the table.

python
from transformers import Sam2Model, Sam2Processor

SAM = "facebook/sam2.1-hiera-tiny"
SAM_REVISION = "de431c4043854a71d8101e17995dfe596bf101a5"
sam_processor = Sam2Processor.from_pretrained(SAM, revision=SAM_REVISION)
sam = Sam2Model.from_pretrained(SAM, revision=SAM_REVISION).to(device).eval()

detections = ground(coffee, "a cup. a saucer. a spoon.") + ground(coffee, "a fork.")
detections.append(("(no object, drawn by hand)", None, [20, 20, 120, 100]))
boxes = [box for _, _, box in detections]
inputs = sam_processor(images=coffee, input_boxes=[boxes], return_tensors="pt").to(device)
with torch.inference_mode():
    outputs = sam(**inputs, multimask_output=False)
masks = sam_processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"].cpu())[0]

for (phrase, _, (x1, y1, x2, y2)), mask, quality in zip(detections, masks, outputs.iou_scores[0]):
    pixels, area = int(mask[0].sum()), (x2 - x1) * (y2 - y1)
    print(f"{phrase:28s} box {area:6d} px  mask {pixels:6d} px  fill {pixels / area:.2f}  "
          f"predicted quality {quality.item():.2f}")
text
a saucer                     box 133168 px  mask  54683 px  fill 0.41  predicted quality 0.97
a cup                        box  69938 px  mask  34653 px  fill 0.50  predicted quality 0.87
a spoon                      box  27295 px  mask   6547 px  fill 0.24  predicted quality 0.95
a fork                       box  26826 px  mask   6537 px  fill 0.24  predicted quality 0.95
(no object, drawn by hand)   box   8000 px  mask   3967 px  fill 0.50  predicted quality 0.84

The spoon's mask covers about a quarter of its box. If you count pixels, measure coverage or cut objects out, the box is a poor stand-in. The saucer mask fills well under half of its box, because the box also encloses the cup standing on it and the table around the rim.

The last two lines are the warning. The false "fork" box produced essentially the spoon's mask with a high predicted quality, and the hand-drawn box, which holds no object, also produced a mask, covering the dark area beyond the table edge. Predicted mask quality is the model's own estimate of how good the outline is for that prompt. It says nothing about whether the label is correct.

The saucer box and the saucer mask on the same cells

Two coarse grids and their overlap. The grounded saucer box is a filled rectangle. The mask is a ring and crescent shape inside it, with a large gap where the cup stands, so the overlap shows many cells that are in the box only.

grounded box

SAM mask

0 (dark)1 (light)

Left to right: cell column 0 to 29. Top to bottom: cell row 0 to 19.

Cells at or above the threshold

only grounded boxonly SAM maskboth

selected cell
cell row 0, cell column 0
grounded box there
0
SAM mask there
0
grounded box: cells counted
340 of 600
SAM mask: cells counted
140 of 600
cells in both
140
cells in either
340
IoU = both / either
0.4118
Dice = 2 × both / sum
0.5833
grounded box: cell row (rows) by cell column (columns)
row01234567891011121314151617181920212223242526272829
0000000000000000000000000000000
1000000000000000000000000000000
2000000000000000000000000000000
3000011111111111111111111000000
4000011111111111111111111000000
5000011111111111111111111000000
6000011111111111111111111000000
7000011111111111111111111000000
8000011111111111111111111000000
9000011111111111111111111000000
10000011111111111111111111000000
11000011111111111111111111000000
12000011111111111111111111000000
13000011111111111111111111000000
14000011111111111111111111000000
15000011111111111111111111000000
16000011111111111111111111000000
17000011111111111111111111000000
18000011111111111111111111000000
19000011111111111111111111000000
SAM mask: cell row (rows) by cell column (columns)
row01234567891011121314151617181920212223242526272829
0000000000000000000000000000000
1000000000000000000000000000000
2000000000000000000000000000000
3000000000000000000000000000000
4000000011000000000000000000000
5000000111000000000000000000000
6000001111000000000000100000000
7000001111000000000001110000000
8000011111000000000001110000000
9000011111000000000001111000000
10000011111100000000011111000000
11000011111100000000011111000000
12000011111100000000001111000000
13000011111100000000001111000000
14000001111100011100001110000000
15000000111111111110001110000000
16000000111111111111111100000000
17000000001111111111111000000000
18000000000011111111100000000000
19000000000000001000000000000000

Cell cell row 0, cell column 0: grounded box 0 (below the threshold), SAM mask 0 (below the threshold). Cells at or above 0.5: grounded box 340 of 600, SAM mask 140 of 600. IoU 0.4118, Dice 0.5833.

Both layers cover the 600 by 400 photograph in 20 pixel cells. Cells in the box only are area the mask leaves out: the cup, the spoon and the table around the saucer. Measured grid values, as recorded by the author: SAM 2.1 tiny mask from the Grounding DINO tiny saucer box, a cell is 1 if at least half its pixels are, transformers 5.24.1, 2026-11-27. The figure only displays and compares them. A cell counts when its value is at or above the threshold. IoU and Dice compare the counted cells of the two layers.

Video: independent frames are not tracking

To see what per-frame prompting does over time without needing a video file, slide a 300 pixel wide window across the photograph in steps of 50 pixels, as a camera panning right would. In the full image the spoon lies roughly between x = 325 and x = 426, so it is outside the first window, partly inside the second and third, and fully inside from x0 = 150 on.

python
for x0 in range(0, 301, 50):
    window = coffee.crop((x0, 0, x0 + 300, 400))
    best = {prompt: max([score for _, score, _ in ground(window, prompt)], default=0.0)
            for prompt in ("a spoon.", "a fork.")}
    print(f"window x0={x0:3d}  spoon {best['a spoon.']:.3f}  fork {best['a fork.']:.3f}")
text
window x0=  0  spoon 0.418  fork 0.346
window x0= 50  spoon 0.413  fork 0.358
window x0=100  spoon 0.394  fork 0.343
window x0=150  spoon 0.637  fork 0.628
window x0=200  spoon 0.760  fork 0.705
window x0=250  spoon 0.746  fork 0.764
window x0=300  spoon 0.714  fork 0.713

Best score per window for two phrases while the view pans

best score00.51threshold 0.5050100150200250300window left edge (px)

a spoon. (circles)a fork. (squares, dashed)

a spoon., values at or above the threshold: 4 of 7 (150, 200, 250, 300)

a fork., values at or above the threshold: 4 of 7 (150, 200, 250, 300)

best score by window left edge (px)
window left edge (px)a spoon.a fork.at or above threshold
00.4180.346none
500.4130.358none
1000.3940.343none
1500.6370.628a spoon., a fork.
2000.760.705a spoon., a fork.
2500.7460.764a spoon., a fork.
3000.7140.713a spoon., a fork.

Threshold 0.5. a spoon. is at or above it at 4 of 7 (150, 200, 250, 300). a fork. is at or above it at 4 of 7 (150, 200, 250, 300).

Move the threshold. The spoon is outside the first window and only partly inside the next two; there is no fork anywhere. Measured values, as recorded by the author: Grounding DINO tiny, transformers 5.24.1, crops of the CC0 coffee image, RTX 5080, 2026-11-27. The figure only displays and compares them. Which values cross the threshold is computed from them.

In the first window the spoon is not in view at all, yet both phrases returned something. At a 0.5 threshold those weak hits vanish, and so does the spoon while it is still entering the frame. The fork curve tracks the spoon curve: where the model is sure about the spoon, it is about as sure about the fork.

On real video this shows up as boxes that blink, change phrase or jump between objects. A per-frame pipeline has no identity: ten frames with one spoon box each are not ten spoons, and not evidence that it is the same spoon. Phrases about events or order ("picks up", "enters", "after") are not something a single frame can answer. If you need identity, add a tracker or use a video model with memory, and evaluate that separately.

Evaluating your own phrases

  1. Label a sample of your images yourself, including images where the object is absent.
  2. A prediction matches a labelled object when their intersection over union (shared area divided by combined area, counted in pixels for masks) reaches a threshold you state. For each phrase, count true positives, false positives and misses, then report precision and recall.
  3. Add control phrases that should return nothing (the fork), and swapped attributes (the blue saucer). If controls fire as often as real phrases, thresholds will not save you.
  4. Fix the prompt string, thresholds, checkpoint revision and input size, and record them with the results.

Published zero-shot benchmarks such as LVIS, with more than a thousand categories, tell you how a checkpoint behaves on their images and names, not on yours.

IoU, precision, recall and mean average precision are worked through in the D-FINE article, which also explains how that closed-vocabulary detector produces its boxes.

Failure How it shows What to do
Absent object Box on the most similar thing Negative controls; require review before accepting
Ignored attribute or relation Right noun, wrong colour or side Detect the noun, then check the attribute with a separate rule or person
Phrase wording Scores move with synonyms, articles or neighbouring phrases Freeze and version the prompt string
Missing delimiter Nothing above threshold End phrases with periods, or pass a list
Ambiguous mask prompt Part, object or object plus neighbour Inspect candidates; add points
Per-frame video Flicker, no identity Tracking or memory-based video model

Check each checkpoint's licence before using it in a product; the three used here are published as Apache-2.0 on their model cards, which says nothing about other sizes or successors. To serve open-set models behind a local API rather than a script, VisionServeX lists Grounding DINO and OWLv2 among its model families.

Where this fits: Anastig and fixed-vocabulary pipelines

Disclosure: the author of this article is also involved in building Anastig.

Anastig Vision Lab is a separate, early-access web workbench, not part of TGraphX; the Anastig overview on this site summarises what else it offers with and without an account. As of 2026-11-27 it lists text-prompt search, but a signed-out visitor cannot run a text prompt on Anastig's hardware: there is no in-browser build, so it needs a GPU worker, either Anastig Remote GPU (paid, by arrangement; the public Vision Lab landing page still lists Anastig-hosted inference as roadmap, so confirm access first) or your own machine running Anastig, for which no customer setup instructions are published. The annotation demo does not demonstrate it.

What a guest can run there is the contrast case: COCO detectors (YOLOv10n and D-FINE-N) on the device, and segmentation from a box or points, which is a visual prompt rather than a text prompt. For the worker route, the product offers Grounding DINO or OWL-ViT and OWLv2 boxes with a confidence threshold and result limit, optionally a SAM mask per box. If a prompt finds nothing and names a COCO class, it can fall back to a COCO detector and labels the output as a fallback, so read the run label. Prompted video is analysed per sampled frame, without tracking or temporal reasoning. That route was not exercised for this article, and nothing above is an Anastig result.

In Anastig Vision Lab This device, no account GPU worker
Text-prompt detection No Grounding DINO, OWL-ViT, OWLv2
Box or point segmentation SAM-family models SAM-family models
Fixed-vocabulary detection YOLOv10n, D-FINE-N A larger catalogue

A fixed vocabulary is the right choice when your classes are in it and you want predictable labels. AI-Powered Video Analyzer, a video pipeline from the same author that runs on your own computer, detects with D-FINE on the 80 COCO classes in its command-line and Python pipeline, so it cannot be asked for a saucer.

If you use grounded boxes as pre-labels, reviewing model proposals covers when to accept, edit or reject them and how to measure the correction.

Where such models can run, and where your pixels go in each case, is the subject of local computer vision inference in the browser or on a GPU worker.

Summary

A text prompt turns detection into matching between words and regions, and a box-prompted segmenter turns those boxes into outlines. Both steps will answer even when the premise is wrong. Treat the output as proposals, measure per phrase with controls that should fail, and do not read frame-by-frame results as tracking.

References