File size: 2,059 Bytes
0e0cc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import type { Detection, DiameterGroup } from './types'

export function exportJson(
  detections: Detection[],
  groups: DiameterGroup[],
  counts: Record<number, number>,
): void {
  const payload = {
    total: detections.length,
    groups: groups.map((g) => ({
      id: g.id,
      label: g.label,
      count: counts[g.id] ?? 0,
      expected: g.expected ?? null,
    })),
    detections: detections.map((d, i) => ({
      id: i + 1,
      groupId: d.groupId,
      confidence: d.confidence,
      xmin: Math.round(d.xmin),
      ymin: Math.round(d.ymin),
      xmax: Math.round(d.xmax),
      ymax: Math.round(d.ymax),
      manual: d.manual ?? false,
    })),
    exportedAt: new Date().toISOString(),
  }
  downloadBlob(JSON.stringify(payload, null, 2), 'pipe-count.json', 'application/json')
}

export function exportCsv(
  detections: Detection[],
  groups: DiameterGroup[],
): void {
  const groupMap = Object.fromEntries(groups.map((g) => [g.id, g.label]))
  const lines = ['id,group,group_label,xmin,ymin,xmax,ymax,confidence,manual']
  detections.forEach((d, i) => {
    lines.push(
      [
        i + 1,
        d.groupId,
        `"${groupMap[d.groupId] ?? ''}"`,
        Math.round(d.xmin),
        Math.round(d.ymin),
        Math.round(d.xmax),
        Math.round(d.ymax),
        d.confidence.toFixed(3),
        d.manual ? 1 : 0,
      ].join(','),
    )
  })
  downloadBlob(lines.join('\n'), 'pipe-count.csv', 'text/csv')
}

export function exportCanvasPng(canvas: HTMLCanvasElement): void {
  canvas.toBlob((blob) => {
    if (!blob) {
      return
    }
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'pipe-count-result.png'
    a.click()
    URL.revokeObjectURL(url)
  })
}

function downloadBlob(content: string, filename: string, type: string): void {
  const blob = new Blob([content], { type })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}