Visual Grounding: How Multimodal Models Precisely Localize Objects in Images
Multimodal large models can describe images and answer questions, but they often struggle with precise object reference — such as counting similar parts or locating the "third red button in the bottom-left corner." This article breaks down the problem into perception and reference layers, explains why natural language falls short for spatial grounding, and introduces coordinate-based representations as unambiguous anchors. It covers normalized box formats, structured markers with parseable output, evaluation methods for counting and localization via IoU, and practical engineering tips for placeholder management and output parsing. A must-read for developers building reliable visual grounding features.
1. Background: Seeing Is Not the Same as Pointing Accurately
Multimodal large models have reached a level where they can describe images, answer questions, and perform basic recognition. However, a specific class of tasks remains error-prone: when an image contains twenty similar parts that must be counted one by one, or when the model must tell the user the exact position of “the third red button in the bottom-left corner,” the response often deviates — or even contradicts itself across attempts.
This problem can be broken down into two layers. The first is perception: whether the model can extract sufficient visual features from raw pixels. With improvements in vision encoders and training data, this bottleneck has been largely alleviated. The second is reference (or grounding): how the model stably binds what it “sees” to specific spatial locations during reasoning. If the entire reasoning process relies solely on natural language, reference becomes ambiguous and unstable.
2. Limitations of Natural Language Reference
Natural language is good at expressing semantics, but poor at expressing spatial positions. Descriptions like “the cup in the middle of the table” or “the person near the door” are clear to humans, yet they carry several inherent problems:
- Ambiguity: Multiple “cups” may exist in the same scene; a slight variation in description can point to the wrong object.
- Non-verifiability: Textual descriptions cannot be directly aligned with image coordinates, making automated programmatic checking difficult.
- Error accumulation: In multi-step reasoning, a vague reference early on is amplified by subsequent steps, eventually breaking the logical chain.
These issues are especially pronounced in dense counting scenarios. The model may “re-count” repeatedly during reasoning and produce inconsistent results each time. The root cause often lies not in a lack of image information, but in the absence of a stable object anchor within the reasoning chain.
3. Coordinate-Based Representation: Unambiguous Anchors for Objects
One solution is to have the model directly output the spatial coordinates of objects during inference, replacing vague linguistic descriptions with geometric information. Common representations include:
- Point: A coordinate pair
(x, y)representing the object center or a key position — suitable for counting and keypoint localization. - Box:
[x1, y1, x2, y2]representing the top-left and bottom-right corners — suitable for object detection tasks. - Polygon: A series of vertices describing an irregular contour — suitable for segmentation or fine-grained boundary descriptions.
Coordinates are typically normalized. A common practice is to map coordinates to a fixed range (e.g., 0 to 1000) and then rescale them back to pixel values based on the actual image dimensions. This allows the same annotation and output format to work across images of varying resolutions.
The following code demonstrates how to parse box coordinates from model output and convert them back to pixel values:
import reBOX_PATTERN = re.compile(r"\[\[(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\]\]")def parse_boxes(text: str, img_w: int, img_h: int, scale: int = 1000):"""Extract normalized box coordinates from text and convert them to pixel coordinates."""boxes = []for m in BOX_PATTERN.finditer(text):x1, y1, x2, y2 = map(int, m.groups())boxes.append((x1 / scale * img_w,y1 / scale * img_h,x2 / scale * img_w,y2 / scale * img_h,))return boxes
Two points deserve attention when parsing. First, the regular expression only matches the expected format; any malformed output should be logged and discarded, not forcibly patched. Second, coordinates that fall outside the valid range should be clipped to [0, scale] to prevent boxes from exceeding image boundaries.
4. Structured Markers: Making References Machine-Readable
Beyond bare coordinates, explicit structured markers can be used to wrap object information — for instance, combining an object’s description with its location into a fixed “name + coordinates” format. This approach offers three benefits:
- Humans can directly read the reasoning process;
- Programs can extract objects and positions using parsing rules;
- A uniform format in training data helps the model learn stable output patterns.
When designing markers, the impact on vocabulary and tokenization must be considered. If a marker is split into multiple ordinary subwords, the model may produce boundary errors during generation, leading to parsing failures. Therefore, a common practice is to register key markers as special tokens, keeping them intact during tokenization.
It is worth emphasizing that different models support different marker formats, vocabulary designs, and output specifications. Developers should always rely on the official documentation and actual outputs of the model they are using, rather than assuming a universal format.
5. From Explicit Markers to Implicit Coordinates
One notable phenomenon is that a model may use explicit reference markers during early training, but in later training stages or during actual usage, its output chain-of-thought may contain only raw coordinates, without explicit markers.
Possible reasons for this shift include:
- The growing proportion of coordinate data in training leads the model to output numbers directly;
- Explicit markers are treated as an intermediate format, and only the coordinate information within them is retained;
- The reasoning display process may be post-processed, hiding some structured content.
For developers, determining whether an output truly “uses visual grounding” should not rest on the presence of a specific marker in the text. Instead, it should be based on whether the output can be verified. The following code uses Intersection over Union (IoU) to measure the consistency between predicted boxes and ground-truth boxes:
def iou(a, b):"""Calculate the Intersection over Union of two boxes (x1, y1, x2, y2)."""ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)area_a = (a[2] - a[0]) * (a[3] - a[1])area_b = (b[2] - b[0]) * (b[3] - b[1])union = area_a + area_b - interreturn inter / union if union > 0 else 0.0
By computing IoU over a batch of samples and measuring the proportion above a certain threshold, one can quantify localization accuracy. This is far more reliable than simply reading the output text.
6. Evaluating Counting Tasks
Counting is a direct test of grounding ability. A simple evaluation workflow is as follows:
- Prepare a set of images with human annotations, each containing the object count and bounding boxes for every object;
- Ask the model to output a list of objects, then parse the count and coordinates;
- Compare the predicted count against the ground truth to compute counting accuracy;
- Compute IoU for the matched boxes to measure localization accuracy;
- Group the statistics by scenario (dense, occluded, small objects, etc.) to identify weaknesses.
Counting accuracy and localization accuracy should be reported separately. If only counting accuracy is reported, a model could score well by “guessing locations correctly in count but randomly in position,” masking the real problem.
7. Mixed-Media Input and Placeholder Management
When an input contains multiple images, the engineering practice is to insert placeholders in the text to indicate where each image appears in the sequence. The placeholder numbering must correspond one-to-one with the image list; otherwise, the text-image alignment breaks down.
Here is a simple mapping example:
def expand_placeholders(text: str, image_tokens: dict[str, list[int]]):"""Replace placeholders in the text with the corresponding image token sequences."""out = []for piece in text.split("\n"):key = piece.strip()if key in image_tokens:out.extend(image_tokens[key])else:out.append(piece)return out
In a real-world system, the following points require attention:
- The number of images is limited by context length and GPU memory; the maximum supported count should follow the official documentation;
- The number of tokens each image occupies depends on resolution and encoding; overly long inputs need to be truncated or downsampled in advance;
- Placeholder numbering should be unique and traceable for troubleshooting alignment issues.
8. Engineering Practice Recommendations
When building visual grounding features, the following practices are recommended:
- Unified coordinate conventions: Use the same normalization range and coordinate order across the entire pipeline, and document them clearly.
- Strict parsing: Record outputs that fail to parse separately; do not silently ignore them — they often reveal model weaknesses.
- Layered evaluation: Evaluate counting, localization, and semantic matching separately to avoid aggregate metrics masking individual problems.
- Preserve raw outputs: Store full model outputs for later reproduction and comparison across model versions.
- Ground claims in testing: Before announcing any capability, validate it on your own dataset.
9. Conclusion
The essence of visual grounding is to give the model a stable, verifiable object anchor during reasoning. Coordinate-based representation provides geometric unambiguity, structured markers provide machine-readability, and rigorous evaluation ensures that these capabilities are genuine and reliable. When implementing such features, developers should focus on output format consistency, the mapping between placeholders and images, and task-specific quantitative evaluation.
