FastVLMBoxes / src /components /BoxAnnotator.ts
Quazim0t0's picture
Upload 36 files
1a9c884 verified
raw
history blame
1.61 kB
/**
* Extracts JSON array from a markdown code block (```json ... ``` or ``` ... ```)
*/
export function extractJsonFromMarkdown(markdown: string): any[] | null {
let jsonString = "";
const jsonBlock = markdown.match(/```json([\s\S]*?)```/i) || markdown.match(/```([\s\S]*?)```/i);
if (jsonBlock && jsonBlock[1]) {
jsonString = jsonBlock[1].trim();
} else {
// Fallback: try to parse the whole string
jsonString = markdown.trim();
}
try {
const parsed = JSON.parse(jsonString);
if (Array.isArray(parsed)) return parsed;
return null;
} catch {
return null;
}
}
/**
* Draws bounding boxes and labels on a canvas context.
* @param ctx CanvasRenderingContext2D
* @param boxes Array of { bbox_2d: [x1, y1, x2, y2], label: string }
* @param options Optional: { color, lineWidth, font }
*/
export function drawBoundingBoxesOnCanvas(
ctx: CanvasRenderingContext2D,
boxes: { bbox_2d: number[]; label?: string }[],
options?: { color?: string; lineWidth?: number; font?: string }
) {
const color = options?.color || "#00FF00";
const lineWidth = options?.lineWidth || 2;
const font = options?.font || "16px Arial";
ctx.save();
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.font = font;
ctx.fillStyle = color;
boxes.forEach((obj) => {
const [x1, y1, x2, y2] = obj.bbox_2d;
ctx.beginPath();
ctx.rect(x1, y1, x2 - x1, y2 - y1);
ctx.stroke();
if (obj.label) {
ctx.fillText(obj.label, x1 + 4, y1 - 4 < 10 ? y1 + 16 : y1 - 4);
}
});
ctx.restore();
}