Repository navigation
Expand file tree
/
Copy pathreport.html
More file actions
900 lines (794 loc) · 42.8 KB
/
Copy pathreport.html
File metadata and controls
900 lines (794 loc) · 42.8 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebPlot AutoDigitizer — Project Report</title>
<style>
:root {
--blue: #2563eb;
--blue-light: #dbeafe;
--red: #dc2626;
--green: #16a34a;
--gray-50: #f8fafc;
--gray-100: #f1f5f9;
--gray-200: #e2e8f0;
--gray-600: #475569;
--gray-800: #1e293b;
--gray-900: #0f172a;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
line-height: 1.7;
color: var(--gray-800);
background: var(--gray-50);
padding: 0;
}
.hero {
background: linear-gradient(135deg, #1e3a5f 0%, #2563eb 100%);
color: white;
padding: 80px 40px;
text-align: center;
}
.hero h1 {
font-size: 2.8rem;
font-weight: 700;
margin-bottom: 12px;
}
.hero p {
font-size: 1.2rem;
opacity: 0.9;
max-width: 800px;
margin: 0 auto;
}
.container {
max-width: 100%;
margin: 0 auto;
padding: 40px 48px;
}
h2 {
font-size: 1.8rem;
color: var(--gray-900);
margin-top: 56px;
margin-bottom: 16px;
padding-bottom: 8px;
border-bottom: 3px solid var(--blue);
}
h3 {
font-size: 1.3rem;
color: var(--gray-800);
margin-top: 32px;
margin-bottom: 12px;
}
p, li {
font-size: 1.05rem;
color: var(--gray-600);
margin-bottom: 12px;
}
ul, ol {
padding-left: 24px;
margin-bottom: 20px;
}
li { margin-bottom: 8px; }
code {
background: var(--gray-100);
padding: 2px 6px;
border-radius: 4px;
font-size: 0.9em;
font-family: 'SF Mono', 'Fira Code', 'JetBrains Mono', monospace;
}
pre {
background: var(--gray-900);
color: #e2e8f0;
padding: 20px 24px;
border-radius: 8px;
overflow-x: auto;
margin: 16px 0 24px;
font-size: 0.9rem;
line-height: 1.6;
}
pre code {
background: none;
padding: 0;
color: inherit;
}
table {
width: 100%;
border-collapse: collapse;
margin: 16px 0 24px;
font-size: 0.95rem;
}
th, td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid var(--gray-200);
}
th {
background: var(--gray-100);
font-weight: 600;
color: var(--gray-900);
}
tr:hover td { background: var(--blue-light); }
.card {
background: white;
border: 1px solid var(--gray-200);
border-radius: 12px;
padding: 24px;
margin: 20px 0;
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
}
.card h4 {
font-size: 1.1rem;
color: var(--gray-900);
margin-bottom: 8px;
}
.phase-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
margin: 20px 0;
}
@media (max-width: 640px) {
.phase-grid { grid-template-columns: 1fr; }
.hero h1 { font-size: 2rem; }
}
.badge {
display: inline-block;
padding: 3px 10px;
border-radius: 99px;
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
}
.badge-green { background: #dcfce7; color: #166534; }
.badge-blue { background: var(--blue-light); color: #1e40af; }
.badge-amber { background: #fef3c7; color: #92400e; }
.stat-row {
display: flex;
gap: 24px;
flex-wrap: wrap;
margin: 20px 0;
}
.stat {
flex: 1;
min-width: 140px;
background: white;
border: 1px solid var(--gray-200);
border-radius: 8px;
padding: 16px;
text-align: center;
}
.stat .value {
font-size: 2rem;
font-weight: 700;
color: var(--blue);
}
.stat .label {
font-size: 0.85rem;
color: var(--gray-600);
margin-top: 4px;
}
.flow-diagram {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 8px;
margin: 24px 0;
}
.flow-step {
background: white;
border: 2px solid var(--blue);
border-radius: 8px;
padding: 12px 20px;
font-weight: 600;
color: var(--blue);
font-size: 0.95rem;
}
.flow-arrow {
font-size: 1.5rem;
color: var(--gray-600);
}
.toc {
background: white;
border: 1px solid var(--gray-200);
border-radius: 12px;
padding: 24px 32px;
margin: 32px 0;
}
.toc h3 { margin-top: 0; }
.toc ol { margin-bottom: 0; }
.toc a { color: var(--blue); text-decoration: none; }
.toc a:hover { text-decoration: underline; }
.highlight {
background: linear-gradient(120deg, #dbeafe 0%, #ede9fe 100%);
border-left: 4px solid var(--blue);
padding: 16px 20px;
border-radius: 0 8px 8px 0;
margin: 20px 0;
}
footer {
text-align: center;
padding: 40px;
color: var(--gray-600);
font-size: 0.9rem;
border-top: 1px solid var(--gray-200);
margin-top: 60px;
}
</style>
</head>
<body>
<div class="hero">
<h1>WebPlot AutoDigitizer</h1>
<p>A web application that extracts data points from scatterplot images and exports them as CSV. Built for researchers who need to digitize published figures.</p>
</div>
<div class="container">
<div class="toc">
<h3>Table of Contents</h3>
<ol>
<li><a href="#overview">Project Overview</a></li>
<li><a href="#how-it-works">How It Works</a></li>
<li><a href="#architecture">Architecture & Tech Stack</a></li>
<li><a href="#methods">Digitization Methods</a></li>
<li><a href="#clumps">Shape-Aware Clump Decomposition</a></li>
<li><a href="#calibration-ui">Calibration UI</a></li>
<li><a href="#testing">Test Harness & Evaluation</a></li>
<li><a href="#error-handling">Error Handling & Robustness</a></li>
<li><a href="#access">How to Access & Deploy</a></li>
<li><a href="#known-issues">Known Limitations</a></li>
<li><a href="#decisions">Key Design Decisions</a></li>
<li><a href="#timeline">Project Timeline</a></li>
</ol>
</div>
<!-- ======================================= -->
<h2 id="overview">1. Project Overview</h2>
<p>WebPlot AutoDigitizer solves a common research problem: you have a scatterplot image from a published paper and need the underlying data as numbers. This tool lets you upload the image, confirm the axis calibration via interactive handles, and receive all plotted points as a downloadable CSV file.</p>
<div class="stat-row">
<div class="stat">
<div class="value">91.9%</div>
<div class="label">Mean detection rate</div>
</div>
<div class="stat">
<div class="value">85</div>
<div class="label">Passing tests</div>
</div>
<div class="stat">
<div class="value">98</div>
<div class="label">Eval test plots</div>
</div>
<div class="stat">
<div class="value"><10s</div>
<div class="label">Response time</div>
</div>
<div class="stat">
<div class="value">100%</div>
<div class="label">Clump recall (filled)</div>
</div>
</div>
<p>The project was built across 16 phases, starting from a synthetic test harness (so we could measure accuracy before writing any detection code) through shape-aware clump decomposition, a precision calibration UI, and production deployment on Railway.</p>
<div class="highlight">
<p><strong>Live deployment:</strong> <a href="https://webplotautodigitizer-production.up.railway.app" style="color: var(--blue);">https://webplotautodigitizer-production.up.railway.app</a></p>
<p><strong>Source code:</strong> <a href="https://github.com/chchatham/WebPlotAutoDigitizer" style="color: var(--blue);">github.com/chchatham/WebPlotAutoDigitizer</a></p>
</div>
<!-- ======================================= -->
<h2 id="how-it-works">2. How It Works</h2>
<div class="flow-diagram">
<div class="flow-step">Upload Image</div>
<div class="flow-arrow">→</div>
<div class="flow-step">Detect Axes</div>
<div class="flow-arrow">→</div>
<div class="flow-step">User Calibrates</div>
<div class="flow-arrow">→</div>
<div class="flow-step">Digitize Points</div>
<div class="flow-arrow">→</div>
<div class="flow-step">Export CSV</div>
</div>
<h3>Step 1: Upload</h3>
<p>The user uploads a scatterplot image (PNG, JPG, or WEBP). The backend validates it (max 10MB, max 4000×4000 pixels), converts it to RGB, and stores it with a unique ID.</p>
<h3>Step 2: Axis Detection</h3>
<p>The system auto-detects the plot region using a dual-strategy approach: background-color detection (for ggplot2/seaborn-style plots with gray backgrounds) combined with Canny edge detection and Hough line transform. It identifies horizontal and vertical axis lines, computes the plot bounding box using whichever method returns the larger area, and optionally uses OCR (pytesseract) to read tick labels and determine the data range.</p>
<h3>Step 3: User Calibration</h3>
<p>The detected axes are shown as a canvas overlay with independent draggable handles: blue handles for the X-axis (horizontal movement repositions the handle, vertical movement translates both handles together) and green handles for the Y-axis (vertical to reposition, horizontal to translate). The axis lines themselves are also draggable. An 8× magnified zoom panel tracks the active handle for pixel-precise placement. An orange detection bounding box defines where to search for points, and four numeric inputs let the user enter the data ranges. An optional "Expected number of points" field guides the clump decomposition algorithm.</p>
<p>If the user clicks "Adjust calibration" from the results screen, all handle positions, data ranges, and the bounding box are restored from the previous calibration — the system never re-runs axis detection and discards the user's work.</p>
<h3>Step 4: Digitization</h3>
<p>The confirmed calibration is sent to the backend, which runs the HybridDigitizer. This combines blob detection (fast, ~1ms) with template matching (thorough, handles all marker shapes) and shape-aware clump decomposition (for overlapping markers). It uses an agreement-based confidence comparison to select the best result, and each detected point gets data coordinates computed via the calibration transform. All numeric values are sanitized (NaN/Infinity converted to 0.0, numpy scalars cast to native Python float) before serialization.</p>
<h3>Step 5: Export</h3>
<p>Results are displayed as translucent red circles overlaid on the original image (max opacity ~0.225 so original markers show through), plus a data table showing X, Y, and confidence for each point. The user can copy the CSV to clipboard or download it as a file, then go back to adjust calibration or start over.</p>
<!-- ======================================= -->
<h2 id="architecture">3. Architecture & Tech Stack</h2>
<h3>Backend (Python 3.11+ / FastAPI)</h3>
<div class="card">
<h4>Key files:</h4>
<ul>
<li><code>backend/main.py</code> — FastAPI app with 5 endpoints + SPA static serving + response sanitization</li>
<li><code>backend/models.py</code> — Pydantic models and dataclasses (AxisCalibration, DetectionResult, MarkerProfile, DetectionBounds, etc.)</li>
<li><code>backend/axis_detection.py</code> — Dual-strategy axis detection: background-color bbox (ggplot) + Hough lines (matplotlib)</li>
<li><code>backend/calibration.py</code> — Pixel ↔ data coordinate transform</li>
<li><code>backend/digitizers/blob_detector.py</code> — Method A: fast contour/blob detection with watershed splitting</li>
<li><code>backend/digitizers/template_matcher.py</code> — Method B: multi-scale template cross-correlation</li>
<li><code>backend/digitizers/hybrid.py</code> — Method C (production): agreement-based method selection + shape-aware routing</li>
<li><code>backend/digitizers/shape_aware.py</code> — Method D: marker profile estimation + clump decomposition</li>
<li><code>backend/image_utils.py</code> — Image normalization, validation, upload handling</li>
</ul>
</div>
<h3>Frontend (React 18 / TypeScript / Vite)</h3>
<div class="card">
<h4>Key components:</h4>
<ul>
<li><code>ImageUpload.tsx</code> — Drag-and-drop file picker with validation</li>
<li><code>AxisCalibration.tsx</code> — Canvas overlay with independent axis handles, zoom panel, detection bounding box, and expected-point-count input</li>
<li><code>ResultsView.tsx</code> — Translucent point overlay on image + scrollable data table with robust error recovery</li>
<li><code>CsvExport.tsx</code> — Copy-to-clipboard and download buttons</li>
<li><code>ErrorBoundary.tsx</code> — Catches render crashes and provides "Start over" recovery UI</li>
</ul>
</div>
<h3>API Endpoints</h3>
<table>
<thead>
<tr>
<th>Endpoint</th>
<th>Method</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>/health</code></td>
<td>GET</td>
<td>Health check</td>
</tr>
<tr>
<td><code>/api/upload</code></td>
<td>POST</td>
<td>Upload image (multipart form, max 10MB)</td>
</tr>
<tr>
<td><code>/api/image/{id}</code></td>
<td>GET</td>
<td>Retrieve stored image</td>
</tr>
<tr>
<td><code>/api/detect-axes</code></td>
<td>POST</td>
<td>Auto-detect axis bounding box (dual-strategy)</td>
</tr>
<tr>
<td><code>/api/digitize</code></td>
<td>POST</td>
<td>Extract data points; accepts optional <code>detection_bounds</code> and <code>expected_point_count</code></td>
</tr>
</tbody>
</table>
<h3>Dependencies</h3>
<table>
<thead>
<tr><th>Package</th><th>Role</th></tr>
</thead>
<tbody>
<tr><td>FastAPI + Uvicorn</td><td>Async web framework & ASGI server</td></tr>
<tr><td>OpenCV (headless)</td><td>Image processing, contour/Hough detection, template matching, distance transforms</td></tr>
<tr><td>NumPy / SciPy</td><td>Coordinate math, KDTree for eval/NMS, distance transforms</td></tr>
<tr><td>scikit-image</td><td>Additional image processing utilities</td></tr>
<tr><td>Pillow</td><td>Image format handling and validation</td></tr>
<tr><td>pytesseract</td><td>OCR for axis label reading (optional; fails on many real-world plots)</td></tr>
<tr><td>matplotlib</td><td>Test-only: synthetic plot generation</td></tr>
<tr><td>React 18 + Vite</td><td>Frontend UI framework & build tool</td></tr>
</tbody>
</table>
<!-- ======================================= -->
<h2 id="methods">4. Digitization Methods</h2>
<p>We implemented four detection methods and compared them empirically across 98 synthetic test plots spanning different marker shapes, sizes, opacities, backgrounds, grid settings, overlap levels, and fill styles.</p>
<h3>Method A: Blob Detection</h3>
<div class="card">
<h4>How it works</h4>
<p>Converts the plot region to grayscale, applies adaptive thresholding relative to the background median, then uses morphological operations and contour detection to find marker blobs. Merged contours (area >1.3× median or elongation >1.4) are split via distance-transform watershed with progressive peak thresholds (0.35, 0.25, 0.18). Computes centroids via image moments and derives a circularity-based confidence score.</p>
<h4>Strengths</h4>
<ul>
<li>Extremely fast (~1ms per image)</li>
<li>High accuracy on circles, squares, and diamonds (95%+ detection)</li>
<li>Built-in watershed splitting for overlapping markers</li>
</ul>
<h4>Weaknesses</h4>
<ul>
<li>Fails on triangle markers (0% — triangles don't form solid blobs after thresholding)</li>
<li>Struggles with X-shaped markers (thin cross shapes)</li>
<li>Confused by grid line intersections</li>
</ul>
<p><span class="badge badge-blue">Mean: 85.4%</span> <span class="badge badge-green">Speed: ~1ms</span></p>
</div>
<h3>Method B: Template Matching</h3>
<div class="card">
<h4>How it works</h4>
<p>Generates a library of marker templates (circle, square, triangle, X, diamond) at multiple scales (7, 11, 15, 21 pixels). Runs normalized cross-correlation against the plot region for each template/scale combination, picks peaks above a threshold (0.4), applies non-maximum suppression, and selects the template/scale combo with the highest average score.</p>
<h4>Strengths</h4>
<ul>
<li>Handles all marker shapes including triangles</li>
<li>Catches adversarial cases that blob detection misses</li>
<li>Multi-scale approach handles varying marker sizes</li>
</ul>
<h4>Weaknesses</h4>
<ul>
<li>Slow on grid plots (300–4000ms due to many false correlations)</li>
<li>More false positives overall</li>
<li>Lower precision on standard circular markers than blob detection</li>
</ul>
<p><span class="badge badge-blue">Mean: 78.5%</span> <span class="badge badge-amber">Speed: 300-4000ms</span></p>
</div>
<h3>Method C: Hybrid (Production Router)</h3>
<div class="card">
<h4>How it works</h4>
<p>The production digitizer combines all other methods via intelligent routing:</p>
<ol>
<li>Always runs blob detection first (fast baseline)</li>
<li>Checks for significant clumping: >5% of contour area in merged blobs, or user provided an expected point count</li>
<li>If clumps detected: runs ShapeAwareDetector (Method D) and compares — prefers shape-aware if it finds more points with reasonable confidence</li>
<li>Otherwise: runs template matching and computes agreement with blob results</li>
<li>If agreement ≥50%: pick whichever method has higher average confidence</li>
<li>If agreement <50%: prefer template unless blob confidence is significantly higher</li>
<li>Fallback: merge both point sets with deduplication</li>
</ol>
<p><span class="badge badge-green">Mean: 91.9%</span> <span class="badge badge-green">Median: 95%</span></p>
</div>
<h3>Final Comparison Table</h3>
<table>
<thead>
<tr>
<th>Method</th>
<th>Mean Rate</th>
<th>Median Rate</th>
<th>Speed</th>
<th>Best On</th>
<th>Worst On</th>
</tr>
</thead>
<tbody>
<tr>
<td>A: Blob</td>
<td>85.4%</td>
<td>95%</td>
<td>~1ms</td>
<td>Circles, squares, diamonds</td>
<td>Triangles (0%)</td>
</tr>
<tr>
<td>B: Template</td>
<td>78.5%</td>
<td>78%</td>
<td>300–4000ms</td>
<td>Triangles, challenge plots</td>
<td>Grid plots (slow)</td>
</tr>
<tr style="background: #f0fdf4;">
<td><strong>C: Hybrid</strong></td>
<td><strong>91.9%</strong></td>
<td><strong>95%</strong></td>
<td>1–4000ms</td>
<td>All shapes</td>
<td>Triangle+grid (0%)</td>
</tr>
<tr>
<td>D: Shape-Aware</td>
<td>Additive</td>
<td>—</td>
<td>5–50ms</td>
<td>Overlapping/clumped markers</td>
<td>Requires 3+ singletons</td>
</tr>
</tbody>
</table>
<!-- ======================================= -->
<h2 id="clumps">5. Shape-Aware Clump Decomposition</h2>
<p>Real-world scatterplots frequently have overlapping or touching markers. A naive blob detector sees merged markers as a single large contour and reports one point where there are two or more. Phase 14 added a four-stage pipeline to handle this.</p>
<h3>Stage 1: Marker Profile Estimation</h3>
<div class="card">
<p>Before decomposing clumps, the system learns what a single marker looks like by analyzing isolated singletons in the image:</p>
<ul>
<li>Finds all contours, filters by area (0.005%–2% of ROI), computes median area</li>
<li>Identifies singletons: contours within [0.4x, 1.8x] median area</li>
<li>Filters for isolation: removes contours with neighbors within 2.5x median radius (KDTree)</li>
<li>Computes profile: median radius, area, circularity, fill ratio</li>
<li>Hollow detection: fill_ratio < 0.7 means unfilled/hollow markers</li>
<li>Requires minimum 3 singletons; falls back to standard blob detection if insufficient</li>
</ul>
<p>Output: <code>MarkerProfile(mean_radius_px, std_radius_px, mean_area_px, is_hollow, edge_width_px, circularity, fill_ratio, n_singletons)</code></p>
</div>
<h3>Stage 2: Clump Classification</h3>
<div class="card">
<p>Each contour is classified as a singleton or clump based on:</p>
<ul>
<li><strong>Area threshold:</strong> contour area > 1.15× (with hint) or 1.3× (without hint) the marker profile's mean area</li>
<li><strong>Elongation:</strong> bounding box aspect ratio > 1.3 AND area > mean area (catches peanut-shaped 2-point overlaps)</li>
</ul>
</div>
<h3>Stage 3: Filled-Marker Decomposition</h3>
<div class="card">
<p>For filled markers, multiple strategies compete to find the best centroid placement:</p>
<ol>
<li><strong>Erosion split:</strong> progressively erodes the clump mask until it separates into N components; most accurate centroids when it works</li>
<li><strong>Ellipse-based placement:</strong> fits an ellipse to the contour, distributes N points along the major axis at geometrically correct spacing (<code>half_len = major/2 - radius</code>), then refines each point by finding the local distance-transform maximum</li>
<li><strong>Distance-transform NMS:</strong> computes the distance transform, finds local maxima with non-maximum suppression at 0.6× radius spacing, tries multiple threshold fractions (0.1–0.5)</li>
<li><strong>Label-based decomposition:</strong> thresholds the distance transform at progressively lower values, labels connected components, computes their centroids</li>
<li><strong>Skeleton spacing:</strong> for large clumps (3+ points), distributes points evenly along the morphological skeleton</li>
</ol>
<p>The strategy producing the count closest to the estimated N wins. The DT refinement step uses mutual exclusion: after placing a point, the distance transform is suppressed around it so the next point can't collapse to the same peak.</p>
<p><span class="badge badge-green">Clump recall: 100% at 2% tolerance (filled, ≤50% overlap)</span></p>
</div>
<h3>Stage 4: Hollow-Marker Decomposition</h3>
<div class="card">
<p>For hollow/unfilled markers, Hough Circle Detection is preferred since the circular edges are well-defined:</p>
<ul>
<li>Extracts a sub-ROI around the clump with 2× radius padding</li>
<li>Searches with radius tolerance ±max(4, 35% of radius) pixels</li>
<li>Sweeps 5 Hough parameter configurations (dp, minDist, Canny threshold, accumulator threshold)</li>
<li>Adaptive Gaussian blur kernel sized proportional to marker radius</li>
<li>Confidence based on how close detected radius matches the profile: <code>conf = 0.6 + 0.3 × (1 - radius_diff)</code></li>
<li>Falls back to filled decomposition if Hough finds too few circles</li>
</ul>
<p><span class="badge badge-green">Clump recall: 91–100% at 2% tolerance (hollow, ≤50% overlap)</span></p>
</div>
<h3>User Point Count Hint</h3>
<p>The frontend provides an optional "Expected number of points" input. When provided, it acts as a soft constraint (weight 0.3) that biases decomposition thresholds and always activates the ShapeAwareDetector regardless of clump area percentage. The hint never forces exact agreement — the algorithm degrades gracefully when given an incorrect count.</p>
<!-- ======================================= -->
<h2 id="calibration-ui">6. Calibration UI</h2>
<p>The calibration screen is the most complex part of the frontend. It combines multiple interactive overlays on a single canvas:</p>
<div class="card">
<h4>Independent Axis Handles</h4>
<ul>
<li><strong>X-axis (blue):</strong> two handles connected by a horizontal line. Horizontal drag repositions that handle's X coordinate; vertical drag translates both handles together (moves the X-axis line up/down).</li>
<li><strong>Y-axis (green):</strong> two handles connected by a vertical line. Vertical drag repositions that handle's Y coordinate; horizontal drag translates both handles together (moves the Y-axis line left/right).</li>
<li>The axis lines themselves are also draggable for quick repositioning.</li>
</ul>
</div>
<div class="card">
<h4>8× Precision Zoom Panel</h4>
<p>A 200×200px panel that magnifies the area around the active handle at 8× zoom with crosshairs. Reads from the original-resolution image (not the scaled canvas) for pixel-precise alignment. Uses <code>imageSmoothingEnabled = false</code> for crisp magnification.</p>
</div>
<div class="card">
<h4>Detection Bounding Box</h4>
<p>An orange dashed rectangle with 4 draggable corner handles defining WHERE to search for points. Initialized with 15% padding beyond the axis range, clamped to image dimensions. This is independent from the axis handles (which define HOW to map pixel coordinates to data coordinates).</p>
</div>
<!-- ======================================= -->
<h2 id="testing">7. Test Harness & Evaluation</h2>
<h3>Philosophy: Test First, Always</h3>
<p>The test harness was built before any digitization code. This was a non-negotiable design principle — we needed to measure accuracy objectively before and after every change. No "it looks right" testing.</p>
<h3>Synthetic Plot Generator</h3>
<p>The generator (<code>tests/generate_plots.py</code>) creates matplotlib scatterplots with known ground-truth coordinates, parameterized across:</p>
<ul>
<li><strong>Point count:</strong> 5, 20, 50, 100, 200</li>
<li><strong>Marker shapes:</strong> circle, square, triangle, X, diamond</li>
<li><strong>Marker sizes:</strong> small (20), medium (40), large (80), xlarge (120)</li>
<li><strong>Fill style:</strong> filled or unfilled (with configurable edge width)</li>
<li><strong>Marker color:</strong> black, red, blue, or any matplotlib color</li>
<li><strong>Opacity:</strong> 1.0, 0.7, 0.4</li>
<li><strong>Overlaps:</strong> configurable overlap fraction (15–70%), pair count, triple count, isolated count</li>
<li><strong>Axis ranges:</strong> integers, floats, negative values</li>
<li><strong>Grid lines:</strong> on/off</li>
<li><strong>Background:</strong> white, light gray, medium gray</li>
</ul>
<p>Each plot is saved as a PNG with a companion JSON containing the exact x/y data values, axis ranges, and generation parameters.</p>
<h3>Eval Scorer</h3>
<p>The scorer (<code>tests/eval_digitizer.py</code>) uses a spatial KDTree approach with two matching modes:</p>
<ol>
<li>Normalize predicted and ground-truth points by the tolerance (default: 1% of axis range per axis)</li>
<li>Build a KDTree from predicted points, query each ground-truth point for its nearest neighbor</li>
<li><strong>Standard matching:</strong> any prediction within tolerance counts as a match (multiple truths can match the same prediction)</li>
<li><strong>Unique matching:</strong> greedy assignment sorted by distance — each prediction matches at most one truth point (more realistic for clump evaluation)</li>
<li>Report: matched %, mean error X/Y, max error, false positives, false negatives, clump recall, singleton recall, clump precision</li>
</ol>
<h3>Test Suite Stats</h3>
<div class="stat-row">
<div class="stat">
<div class="value">60</div>
<div class="label">Baseline test plots</div>
</div>
<div class="stat">
<div class="value">38</div>
<div class="label">Overlap test configs</div>
</div>
<div class="stat">
<div class="value">85</div>
<div class="label">Pytest tests passing</div>
</div>
<div class="stat">
<div class="value">≤2%</div>
<div class="label">Positional error target</div>
</div>
</div>
<h3>Overlap Test Categories</h3>
<table>
<thead>
<tr><th>Category</th><th>Count</th><th>Description</th></tr>
</thead>
<tbody>
<tr><td>A: Filled overlaps</td><td>9</td><td>20–70% overlap, chains, dense clusters</td></tr>
<tr><td>B: Hollow overlaps</td><td>6</td><td>Unfilled circles at 20–50% overlap</td></tr>
<tr><td>C: Background variants</td><td>6</td><td>Gray backgrounds, grid lines, colored markers</td></tr>
<tr><td>D: Size variants</td><td>3</td><td>Small and xlarge markers with overlap</td></tr>
<tr><td>E: Mixed</td><td>3</td><td>40+ isolated points with 5–8 clump pairs</td></tr>
<tr><td>F: Point count hints</td><td>3</td><td>Tests with/without expected count</td></tr>
<tr><td>G: Dense + sparse clumps</td><td>8</td><td>100-point plots with 2–5 subtle overlapping pairs</td></tr>
</tbody>
</table>
<!-- ======================================= -->
<h2 id="error-handling">8. Error Handling & Robustness</h2>
<p>Several production bugs were discovered and fixed during deployment, leading to comprehensive error hardening:</p>
<div class="card">
<h4>Frontend</h4>
<ul>
<li><strong>Error Boundary:</strong> wraps all app content; catches render crashes and shows a "Start over" recovery button instead of a blank page</li>
<li><strong>Robust catch handlers:</strong> Promise <code>.catch()</code> uses <code>e instanceof Error ? e.message : String(e ?? "Unknown error")</code> — never assumes <code>e</code> has a <code>.message</code> property</li>
<li><strong>Response validation:</strong> <code>api.ts</code> validates that digitize responses have a <code>points</code> array before returning</li>
</ul>
</div>
<div class="card">
<h4>Backend</h4>
<ul>
<li><strong>Digitize try/except:</strong> wraps <code>digitizer.digitize()</code> and returns 500 with a descriptive message on failure</li>
<li><strong>Pixel range validation:</strong> rejects zero-width pixel ranges with 400 (prevents ZeroDivisionError)</li>
<li><strong>NaN/Infinity sanitization:</strong> all numeric output is checked and converted to 0.0 if not finite</li>
<li><strong>numpy scalar casting:</strong> <code>sanitize()</code> calls <code>float(v)</code> on all values to convert <code>numpy.float32</code> to native Python float before FastAPI serialization</li>
</ul>
</div>
<!-- ======================================= -->
<h2 id="access">9. How to Access & Deploy</h2>
<h3>Live Deployment</h3>
<div class="highlight">
<p>The app is deployed on Railway and accessible at: <a href="https://webplotautodigitizer-production.up.railway.app" style="color: var(--blue);">https://webplotautodigitizer-production.up.railway.app</a></p>
</div>
<h3>Option 1: Docker (Recommended)</h3>
<pre><code># Build and start the app
docker-compose up
# Access at:
# http://localhost:8000</code></pre>
<p>The multi-stage Dockerfile first builds the React frontend with Node 20, then packages the Python backend with the compiled static files. The final image includes OpenCV dependencies (using <code>libgl1</code> for Debian Trixie compatibility) and serves the SPA from FastAPI's static file handler.</p>
<h3>Option 2: Local Development (No Docker)</h3>
<pre><code># Backend
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
uvicorn backend.main:app --reload
# Backend at http://localhost:8000
# Frontend (separate terminal)
cd frontend
npm install
npm run dev
# Frontend at http://localhost:5173 (proxies API calls to :8000)</code></pre>
<h3>Option 3: Cloud Deployment (Railway / Render / Fly.io)</h3>
<ol>
<li>Push to GitHub (or connect your repo directly)</li>
<li>Connect the repo to your hosting provider</li>
<li>The platform auto-detects the Dockerfile</li>
<li>Set <code>PORT</code> environment variable if required (Railway sets this automatically)</li>
<li>The app serves both the API and frontend on a single port</li>
</ol>
<div class="card">
<h4>Environment Variables</h4>
<table>
<thead><tr><th>Variable</th><th>Default</th><th>Description</th></tr></thead>
<tbody>
<tr><td><code>PORT</code></td><td>8000</td><td>Server port (Railway sets this dynamically)</td></tr>
<tr><td><code>VITE_API_URL</code></td><td><em>(empty string)</em></td><td>Frontend API base URL; empty = same-origin relative paths</td></tr>
</tbody>
</table>
</div>
<h3>Running Tests</h3>
<pre><code>source .venv/bin/activate
python -m pytest tests/ -v
# 85 tests, ~40 seconds</code></pre>
<!-- ======================================= -->
<h2 id="known-issues">10. Known Limitations</h2>
<table>
<thead>
<tr><th>Issue</th><th>Impact</th><th>Reason</th></tr>
</thead>
<tbody>
<tr>
<td>Triangle + grid combination</td>
<td>0% detection</td>
<td>Grid line intersections create false contours that overwhelm both methods' ability to isolate triangle markers</td>
</tr>
<tr>
<td>X-shaped markers</td>
<td>60–75% detection</td>
<td>Thin cross shapes don't form solid blobs, and template correlation is weak for line-based markers</td>
</tr>
<tr>
<td>Clumps with very tight spacing (<0.5% of axis range)</td>
<td>Reduced splitting accuracy</td>
<td>Distance transform peaks merge when markers are nearly fully overlapping</td>
</tr>
<tr>
<td>OCR axis labels</td>
<td>Often fails on real-world plots</td>
<td>pytesseract struggles with small/rotated text; falls back to user-entered values</td>
</tr>
<tr>
<td>Uploaded images ephemeral</td>
<td>Lost on container restart</td>
<td>Stored in <code>/tmp</code>; would need persistent volume or object storage for durability</td>
</tr>
</tbody>
</table>
<!-- ======================================= -->
<h2 id="decisions">11. Key Design Decisions</h2>
<h3>Why Test-First?</h3>
<p>Image processing is notoriously hard to evaluate by eye. A point detection algorithm might look "good enough" on one image but fail catastrophically on another. By building the synthetic test harness first (Phase 1, before any detection code), we ensured every method was evaluated on the same plots with the same scoring criteria. This let us make data-driven decisions about which approach to ship.</p>
<h3>Why Multiple Methods?</h3>
<p>No single computer vision technique handles all marker shapes equally well. Blob detection is fast and precise for filled shapes but fails on triangles and crosses. Template matching handles everything but is slow and produces more false positives. Shape-aware decomposition handles overlaps but requires singletons to calibrate. By implementing all four and routing intelligently, the hybrid gets the best of each.</p>
<h3>Why User Calibration is King</h3>
<p>Auto-detected axes are a convenience, not a requirement. Real-world plots have legends, annotations, insets, and non-standard layouts that confuse automated detection. The draggable fiducial handles let users correct any axis detection errors, and calibration state persists when the user goes back to adjust — their work is never lost.</p>
<h3>Why CPU-Only?</h3>
<p>The target deployment is cheap cloud hosting (Railway, Render, Fly.io) without GPU access. All image processing uses OpenCV and NumPy on CPU. The hybrid digitizer completes in under 4 seconds even in worst-case scenarios, well within the 10-second budget.</p>
<h3>Why a Single Docker Port?</h3>
<p>In production, the FastAPI backend serves the compiled React frontend as static files from the same port. This eliminates CORS issues, simplifies deployment to a single container, and means users access everything at one URL.</p>
<h3>Why Unique Matching in Scoring?</h3>
<p>Standard KDTree matching lets multiple ground-truth points match the same prediction, inflating recall when clumped points collapse to a single detection. Unique matching (greedy assignment) gives a realistic measure of how many individual points the detector resolves. This was critical for measuring clump decomposition quality.</p>
<!-- ======================================= -->
<h2 id="timeline">12. Project Timeline</h2>
<div class="phase-grid">
<div class="card">
<h4>Phase 0: Scaffolding</h4>
<p>FastAPI + React setup, Docker config, health endpoint, upload round-trip.</p>
</div>
<div class="card">
<h4>Phase 1: Test Harness</h4>
<p>Synthetic plot generator, eval scorer, 60 baseline plots, pytest fixtures.</p>
</div>
<div class="card">
<h4>Phase 2: Axis Detection</h4>
<p>Hough line detection, OCR label reading, AxisCalibration dataclass, calibration UI.</p>
</div>
<div class="card">
<h4>Phase 3: Blob Detection</h4>
<p>Contour-based method, 85.4% mean accuracy, fast but fails on triangles.</p>
</div>
<div class="card">
<h4>Phase 4: Template Matching</h4>
<p>Cross-correlation with marker library, 78.5% mean, handles all shapes but slower.</p>
</div>
<div class="card">
<h4>Phase 5–6: Hybrid & Hardening</h4>
<p>Agreement-based method selection (91.9% mean), confidence scores, edge case handling.</p>
</div>
<div class="card">
<h4>Phase 7–8: UI & Deploy</h4>
<p>Full wizard UI, responsive layout, Docker deployment, landing page, end-to-end testing.</p>
</div>
<div class="card">
<h4>Phase 9: Cloud Deploy</h4>
<p>GitHub repo, Railway deployment, production CORS/PORT fixes, live URL.</p>
</div>
<div class="card">
<h4>Phase 10: Refinements</h4>
<p>About page, translucent overlays, independent axis handles, clump tests.</p>
</div>
<div class="card">
<h4>Phase 11: Precision Calibration</h4>
<p>Constrained handles, zoom panel, detection bounding box, dual bbox detection.</p>
</div>
<div class="card">
<h4>Phase 12–13: Fixes & Persistence</h4>
<p>Bounding box clamping, Y-coordinate fix, calibration persistence, fluid layout.</p>
</div>
<div class="card">
<h4>Phase 14: Clump Decomposition</h4>
<p>Shape-aware detection: marker profiling, filled/hollow decomposition, 100%/91% clump recall, 38 overlap test configs.</p>
</div>
<div class="card">
<h4>Phase 15–16: Bug Fixes</h4>
<p>Blank page fix (Error Boundary), numpy serialization fix, response validation, NaN sanitization.</p>
</div>
<div class="card">
<h4>Phase 17: Recall Tuning</h4>
<p>Fixed test calibration offset, unique matching scorer, erosion split & DT refinement, clump recall targets achieved.</p>
</div>
</div>
</div>
<footer>
<p>WebPlot AutoDigitizer — Project Report<br>
Last updated 2026-05-04 | Built with Python, FastAPI, OpenCV, React, TypeScript<br>
<a href="https://github.com/chchatham/WebPlotAutoDigitizer" style="color: var(--blue);">View on GitHub</a></p>
</footer>
</body>
</html>