File size: 1,608 Bytes
1a9c884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**

 * 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();
}