File size: 2,036 Bytes
1a9c884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebefe10
1a9c884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e2739c
1a9c884
96b5215
1a9c884
 
 
2e2739c
 
1a9c884
 
 
 
 
 
 
 
 
2e2739c
 
 
 
1a9c884
2e2739c
1a9c884
 
96b5215
1a9c884
 
 
 
96b5215
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
55
56
57
58
59
60
61
62
/**

 * 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;
    if (typeof parsed === "object" && parsed !== null) return [parsed]; // <-- Wrap object in array
    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, scaleX?: number, scaleY?: number }

) {
  if (!Array.isArray(boxes)) return; // Prevent errors if boxes is undefined/null
  const color = options?.color || "#00FF00";
  const lineWidth = options?.lineWidth || 2;
  const font = options?.font || "16px Arial";
  const scaleX = options?.scaleX ?? 1;
  const scaleY = options?.scaleY ?? 1;

  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;
    const sx1 = x1 * scaleX;
    const sy1 = y1 * scaleY;
    const sx2 = x2 * scaleX;
    const sy2 = y2 * scaleY;
    ctx.beginPath();
    ctx.rect(sx1, sy1, sx2 - sx1, sy2 - sy1);
    ctx.stroke();
    if (obj.label) {
      ctx.fillText(obj.label, sx1 + 4, sy1 - 4 < 10 ? sy1 + 16 : sy1 - 4);
    }
  });

  ctx.restore();
}