How Multi-Turn Image Editing and Visual Grounding Coordinates Work
Combining visual grounding (locating target regions via bounding boxes or point coordinates) with multi-turn image editing lets an orchestration layer isolate exact regions on an image, apply targeted edits, and iteratively refine the result across turns without losing earlier edits or drifting away from the original scene.
- Coordinate conventions vary by model and provider: Some vision APIs return bounding boxes in
[y_min, x_min, y_max, x_max]normalized to0–1000(with top-left(0, 0)), while others return pixel coordinates or normalized[0.0, 1.0]ratios relative to the image sent to the model. You must explicitly specify the coordinate format and scale in your schema/prompt and convert coordinates using the exact dimensions of the image the model observed. - Turn-by-turn state accumulation and drift control: Across multiple editing turns, feeding raw images repeatedly can cause gradual visual drift or style inconsistency if edits are applied globally instead of locally. Grounding a bounding box first and restricting edits (via mask generation, cropped/padded region editing, or explicit preserve/change constraints) keeps untouched regions intact.
- Grounding-to-edit closed loop: A reliable pipeline separates detection/grounding (finding coordinates for
"the price tag"or"left sidebar button"), execution (generating a mask or editing the image), and verification (inspecting the updated image on the next turn to confirm the edit succeeded or issue a targeted correction).
Steps to Implement Multi-Turn Grounding and Image Editing
- Record exact dimensions of the image passed to the VLM: Store
widthandheightof the exact buffer sent to the grounding model (especially if resized or tiled) so normalized coordinates map accurately back to original pixels. - Request structured bounding boxes or point coordinates: Use a strict JSON schema to extract
{ label, yMin, xMin, yMax, xMax }in a known coordinate system (such as0–1000normalized[y_min, x_min, y_max, x_max]), clamp values to valid bounds, and convert to pixel rectangles. - Convert grounded boxes into edit masks or region instructions: Expand the bounding box slightly (padding) to cover anti-aliased edges/shadows, generate an alpha/binary mask or region spec, and run the image edit step while explicitly listing unchanged elements to preserve.
- Maintain versioned turn state (
turn_0,turn_1, …): Keep an ordered session history of image artifacts, applied edit instructions, and grounding coordinates so users can undo, follow up (“make that slightly brighter”), or inspect the latest accepted image.
TypeScript Example: Grounding Coordinates to Pixel Boxes and Multi-Turn Edit Session
import OpenAI from "openai";
import sharp from "sharp";
const openai = new OpenAI();
export interface NormalizedBox1000 {
label: string;
yMin: number; // 0..1000
xMin: number; // 0..1000
yMax: number; // 0..1000
xMax: number; // 0..1000
}
export interface PixelRect {
left: number;
top: number;
width: number;
height: number;
}
export interface EditTurnRecord {
turn: number;
instruction: string;
targetBox?: PixelRect;
imageBase64Png: string;
}
export function norm1000ToPixelRect(
box: NormalizedBox1000,
imgWidth: number,
imgHeight: number,
paddingPx = 12
): PixelRect {
const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v));
const rawLeft = Math.floor((clamp(box.xMin, 0, 1000) / 1000) * imgWidth) - paddingPx;
const rawTop = Math.floor((clamp(box.yMin, 0, 1000) / 1000) * imgHeight) - paddingPx;
const rawRight = Math.ceil((clamp(box.xMax, 0, 1000) / 1000) * imgWidth) + paddingPx;
const rawBottom = Math.ceil((clamp(box.yMax, 0, 1000) / 1000) * imgHeight) + paddingPx;
const left = clamp(rawLeft, 0, Math.max(0, imgWidth - 1));
const top = clamp(rawTop, 0, Math.max(0, imgHeight - 1));
const right = clamp(rawRight, left + 1, imgWidth);
const bottom = clamp(rawBottom, top + 1, imgHeight);
return {
left,
top,
width: right - left,
height: bottom - top,
};
}
export async function groundTargetRegion(
imagePngBuffer: Buffer,
targetDescription: string
): Promise<PixelRect> {
const meta = await sharp(imagePngBuffer).metadata();
const width = meta.width ?? 1;
const height = meta.height ?? 1;
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
messages: [
{
role: "system",
content:
"Locate the requested visual element. Return coordinates normalized from 0 to 1000 in [yMin, xMin, yMax, xMax] order where (0,0) is top-left.",
},
{
role: "user",
content: [
{ type: "text", text: `Find bounding box for: ${targetDescription}` }, { type: "image_url", image_url: { url: `data:image/png;base64,${imagePngBuffer.toString("base64")}`,
detail: "high",
},
},
],
},
],
response_format: {
type: "json_schema",
json_schema: {
name: "grounding_box",
strict: true,
schema: {
type: "object",
additionalProperties: false,
required: ["label", "yMin", "xMin", "yMax", "xMax"],
properties: {
label: { type: "string" },
yMin: { type: "number" },
xMin: { type: "number" },
yMax: { type: "number" },
xMax: { type: "number" },
},
},
},
},
});
const rawContent = response.choices[0]?.message.content ?? "{}";
const parsed = JSON.parse(rawContent) as NormalizedBox1000;
return norm1000ToPixelRect(parsed, width, height);
}
export class MultiTurnImageEditSession {
private readonly history: EditTurnRecord[] = [];
private currentBuffer: Buffer;
constructor(initialPngBuffer: Buffer) {
this.currentBuffer = initialPngBuffer;
this.history.push({
turn: 0,
instruction: "initial_image",
imageBase64Png: initialPngBuffer.toString("base64"),
});
}
async applyGroundedEdit(
targetDescription: string,
editPrompt: string,
renderEditedBuffer: (
sourcePng: Buffer,
region: PixelRect,
prompt: string
) => Promise<Buffer>
): Promise<EditTurnRecord> {
const targetBox = await groundTargetRegion(this.currentBuffer, targetDescription);
const updatedBuffer = await renderEditedBuffer(this.currentBuffer, targetBox, editPrompt);
this.currentBuffer = updatedBuffer;
const record: EditTurnRecord = {
turn: this.history.length,
instruction: editPrompt,
targetBox,
imageBase64Png: updatedBuffer.toString("base64"),
};
this.history.push(record);
return record;
}
getHistory(): EditTurnRecord[] {
return this.history;
}
}
Helpful Tips for Production Grounding and Multi-Turn Editing
- Always verify grounding visually during debugging: Render bounding boxes onto a diagnostic copy of the image in non-production/staging logs to catch off-by-one coordinate scaling, swapped
(x, y)axes, or aspect-ratio mismatches before feeding masks to an editor. - Store image artifacts in object storage rather than keeping large base64 strings in memory: In long multi-turn editing sessions, keep
imageUrl/ object-storage keys in session state and load buffers on demand so Node.js heap memory stays flat. - Re-ground after every turn before applying a follow-up edit: Never reuse stale pixel coordinates from turn $N-1$ on turn $N$ if an earlier edit shifted object boundaries, resized elements, or changed layout geometry.
You must log in or register to comment.
