Visual Grounding is the task of identifying an object from a text prompt and outputting its bounding box in the format [[x0, y0, x1, y1]].
Workflow:
- Construct a
conversation list containing a user role with an image type and a text type prompt (e.g., "Where is the [object]? Answer in [[x0,y0,x1,y1]] format."). - Process the conversation using
processor(conversation=conversation, return_tensors="pt"). - Move inputs to GPU and ensure
pixel_values are in torch.bfloat16. - Generate output using
model.generate(**inputs). - Decode the response using
processor.batch_decode(). - Parse the bounding box from the text response using a helper like
extract_boxes().
conversation = [
{
"role": "user",
"content": [
{
"type": "image",
"image": {"image_path": image_path}
},
{
"type": "text",
"text": "Where is the white car? Answer in [[x0,y0,x1,y1]] format.",
},
]
}
]
# Single-turn conversation
inputs = processor(conversation=conversation, return_tensors="pt")
inputs = {k: v.cuda() if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
if "pixel_values" in inputs:
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
output_ids = model.generate(**inputs, max_new_tokens=128)
response = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
print(response)