img2svg 0.1.9

A rust native image to SVG converter in CLI/MCP/Library
Documentation
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
#[cfg(test)]
mod tests {
    use super::super::*;
    use crate::image_processor::ImageData;
    use rgb::RGBA8;

    fn create_test_mask(width: usize, height: usize, pattern: &str) -> Vec<bool> {
        let mut mask = vec![false; width * height];
        match pattern {
            "square" => {
                // Create a square in the center
                let margin = width / 4;
                for y in margin..height - margin {
                    for x in margin..width - margin {
                        mask[y * width + x] = true;
                    }
                }
            }
            "circle" => {
                // Create a circle in the center
                let cx = width / 2;
                let cy = height / 2;
                let radius = width.min(height) / 4;
                for y in 0..height {
                    for x in 0..width {
                        let dx = x as f64 - cx as f64;
                        let dy = y as f64 - cy as f64;
                        if (dx * dx + dy * dy).sqrt() <= radius as f64 {
                            mask[y * width + x] = true;
                        }
                    }
                }
            }
            "checkerboard" => {
                // Create a checkerboard pattern
                for y in 0..height {
                    for x in 0..width {
                        mask[y * width + x] = (x + y) % 2 == 0;
                    }
                }
            }
            "full" => {
                // All true
                mask = vec![true; width * height];
            }
            "donut" => {
                // Outer square with inner hole
                for y in 0..height {
                    for x in 0..width {
                        let in_outer = x >= width / 4 && x < 3 * width / 4
                            && y >= height / 4 && y < 3 * height / 4;
                        let in_inner = x >= 3 * width / 8 && x < 5 * width / 8
                            && y >= 3 * height / 8 && y < 5 * height / 8;
                        mask[y * width + x] = in_outer && !in_inner;
                    }
                }
            }
            "empty" => {
                // All false - already initialized
            }
            "horizontal_line" => {
                let mid_y = height / 2;
                for x in 0..width {
                    mask[mid_y * width + x] = true;
                }
            }
            "vertical_line" => {
                let mid_x = width / 2;
                for y in 0..height {
                    mask[y * width + mid_x] = true;
                }
            }
            "diagonal" => {
                for i in 0..width.min(height) {
                    mask[i * width + i] = true;
                }
            }
            _ => {}
        }
        mask
    }

    fn create_test_image(width: u32, height: u32, pixels: Vec<RGBA8>) -> ImageData {
        ImageData {
            width,
            height,
            pixels,
        }
    }

    fn create_two_color_image(width: u32, height: u32) -> ImageData {
        let mut pixels = Vec::with_capacity((width * height) as usize);
        for y in 0..height {
            for x in 0..width {
                // Create a simple square pattern
                let is_square = x > width / 4 && x < width * 3 / 4
                    && y > height / 4 && y < height * 3 / 4;
                if is_square {
                    pixels.push(RGBA8::new(255, 0, 0, 255));
                } else {
                    pixels.push(RGBA8::new(255, 255, 255, 255));
                }
            }
        }
        ImageData {
            width,
            height,
            pixels,
        }
    }

    // === Point Tests ===

    #[test]
    fn test_point_creation() {
        let p = Point { x: 10.5, y: 20.5 };
        assert_eq!(p.x, 10.5);
        assert_eq!(p.y, 20.5);
    }

    #[test]
    fn test_point_clone() {
        let p1 = Point { x: 5.0, y: 10.0 };
        let p2 = p1.clone();
        assert_eq!(p1.x, p2.x);
        assert_eq!(p1.y, p2.y);
    }

    // === Curve Tests ===

    #[test]
    fn test_curve_creation() {
        let curve = Curve {
            points: vec![Point { x: 0.0, y: 0.0 }, Point { x: 10.0, y: 10.0 }],
            color: (255, 0, 0, 255),
            is_closed: true,
            subpaths: vec![],
        };
        assert_eq!(curve.points.len(), 2);
        assert_eq!(curve.color, (255, 0, 0, 255));
        assert!(curve.is_closed);
    }

    #[test]
    fn test_curve_clone() {
        let curve1 = Curve {
            points: vec![Point { x: 0.0, y: 0.0 }],
            color: (128, 128, 128, 255),
            is_closed: false,
            subpaths: vec![],
        };
        let curve2 = curve1.clone();
        assert_eq!(curve1.color, curve2.color);
    }

    // === Polygon Area Tests ===

    #[test]
    fn test_polygon_area_triangle() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 0.0 },
            Point { x: 5.0, y: 10.0 },
        ];
        let area = polygon_area(&points);
        assert!((area - 50.0).abs() < 0.01);
    }

    #[test]
    fn test_polygon_area_square() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
            Point { x: 0.0, y: 10.0 },
        ];
        let area = polygon_area(&points);
        assert!((area - 100.0).abs() < 0.01);
    }

    #[test]
    fn test_polygon_area_empty() {
        let points: Vec<Point> = vec![];
        let area = polygon_area(&points);
        assert_eq!(area, 0.0);
    }

    #[test]
    fn test_polygon_area_line() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
        ];
        let area = polygon_area(&points);
        assert_eq!(area, 0.0);
    }

    // === Point to Line Distance Tests ===

    #[test]
    fn test_point_to_line_distance_on_line() {
        let line_start = Point { x: 0.0, y: 0.0 };
        let line_end = Point { x: 10.0, y: 0.0 };
        let point = Point { x: 5.0, y: 0.0 };
        let dist = point_to_line_distance(&point, &line_start, &line_end);
        assert!((dist - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_point_to_line_distance_perpendicular() {
        let line_start = Point { x: 0.0, y: 0.0 };
        let line_end = Point { x: 10.0, y: 0.0 };
        let point = Point { x: 5.0, y: 3.0 };
        let dist = point_to_line_distance(&point, &line_start, &line_end);
        assert!((dist - 3.0).abs() < 0.01);
    }

    #[test]
    fn test_point_to_line_distance_vertical() {
        let line_start = Point { x: 0.0, y: 0.0 };
        let line_end = Point { x: 0.0, y: 10.0 };
        let point = Point { x: 4.0, y: 5.0 };
        let dist = point_to_line_distance(&point, &line_start, &line_end);
        assert!((dist - 4.0).abs() < 0.01);
    }

    #[test]
    fn test_point_to_line_distance_diagonal() {
        let line_start = Point { x: 0.0, y: 0.0 };
        let line_end = Point { x: 10.0, y: 10.0 };
        let point = Point { x: 5.0, y: 7.0 };
        let dist = point_to_line_distance(&point, &line_start, &line_end);
        // Distance from (5,7) to line y=x is |7-5|/sqrt(2) = 2/sqrt(2) ≈ 1.414
        assert!((dist - 1.414).abs() < 0.01);
    }

    #[test]
    fn test_point_to_line_distance_degenerate() {
        let line_start = Point { x: 5.0, y: 5.0 };
        let line_end = Point { x: 5.0, y: 5.0 };
        let point = Point { x: 8.0, y: 9.0 };
        let dist = point_to_line_distance(&point, &line_start, &line_end);
        // Should be distance from point to the single point
        let dx: f64 = 8.0 - 5.0;
        let dy: f64 = 9.0 - 5.0;
        let expected = (dx * dx + dy * dy).sqrt();
        assert!((dist - expected).abs() < 0.01);
    }

    // === RDP Simplify Tests ===

    #[test]
    fn test_rdp_simplify_empty() {
        let points: Vec<Point> = vec![];
        let result = rdp_simplify(&points, 1.0);
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_rdp_simplify_single_point() {
        let points = vec![Point { x: 5.0, y: 5.0 }];
        let result = rdp_simplify(&points, 1.0);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_rdp_simplify_two_points() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
        ];
        let result = rdp_simplify(&points, 1.0);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_rdp_simplify_straight_line() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 2.0, y: 2.0 },
            Point { x: 4.0, y: 4.0 },
            Point { x: 6.0, y: 6.0 },
            Point { x: 8.0, y: 8.0 },
            Point { x: 10.0, y: 10.0 },
        ];
        let result = rdp_simplify(&points, 1.0);
        // Should reduce to just endpoints
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].x, 0.0);
        assert_eq!(result[1].x, 10.0);
    }

    #[test]
    fn test_rdp_simplify_triangle() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 5.0, y: 0.1 }, // Very close to line
            Point { x: 10.0, y: 0.0 },
            Point { x: 5.0, y: 10.0 },
        ];
        let result = rdp_simplify(&points, 1.0);
        // Should keep the triangle corner
        assert!(result.len() >= 3);
    }

    // === Smooth Boundary Tests ===

    #[test]
    fn test_smooth_boundary_empty() {
        let points: Vec<Point> = vec![];
        let result = smooth_boundary(&points, 1);
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_smooth_boundary_single_point() {
        let points = vec![Point { x: 5.0, y: 5.0 }];
        let result = smooth_boundary(&points, 1);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_smooth_boundary_two_points() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
        ];
        let result = smooth_boundary(&points, 1);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_smooth_boundary_square() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
            Point { x: 0.0, y: 10.0 },
        ];
        let result = smooth_boundary(&points, 1);
        assert_eq!(result.len(), 4);
        // Should smooth the corners - check that values have changed
        assert!(result[0].x >= 0.0);
        assert!(result[0].y >= 0.0);
        // The smoothing averages each point with its neighbors
        // For a closed loop, this should shift all points toward their neighbors
    }

    #[test]
    fn test_smooth_boundary_zero_level() {
        let points = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
        ];
        let result = smooth_boundary(&points, 0);
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].x, 0.0);
        assert_eq!(result[1].x, 10.0);
    }

    // === Marching Squares Tests ===

    #[test]
    fn test_marching_squares_empty_mask() {
        let mask = create_test_mask(10, 10, "empty");
        let contours = marching_squares_contours(&mask, 10, 10);
        assert_eq!(contours.len(), 0);
    }

    #[test]
    fn test_marching_squares_full_mask() {
        let mask = create_test_mask(10, 10, "full");
        let contours = marching_squares_contours(&mask, 10, 10);
        // Should have one contour around the border
        assert!(!contours.is_empty());
        // Check that contour is closed and roughly rectangular
        if !contours.is_empty() {
            assert!(contours[0].len() >= 4);
        }
    }

    #[test]
    fn test_marching_squares_square() {
        let mask = create_test_mask(20, 20, "square");
        let contours = marching_squares_contours(&mask, 20, 20);
        // Should find at least one contour
        assert!(!contours.is_empty());
        // Each contour should have enough points
        for contour in &contours {
            assert!(contour.len() >= 4);
        }
    }

    #[test]
    fn test_marching_squares_circle() {
        let mask = create_test_mask(20, 20, "circle");
        let contours = marching_squares_contours(&mask, 20, 20);
        // Should find at least one contour
        assert!(contours.len() >= 1);
    }

    #[test]
    fn test_marching_squares_horizontal_line() {
        let mask = create_test_mask(20, 20, "horizontal_line");
        let contours = marching_squares_contours(&mask, 20, 20);
        // Should find contours for the line
        assert!(contours.len() >= 1);
    }

    #[test]
    fn test_marching_squares_vertical_line() {
        let mask = create_test_mask(20, 20, "vertical_line");
        let contours = marching_squares_contours(&mask, 20, 20);
        // Should find contours for the line
        assert!(contours.len() >= 1);
    }

    #[test]
    fn test_marching_squares_checkerboard() {
        let mask = create_test_mask(10, 10, "checkerboard");
        let contours = marching_squares_contours(&mask, 10, 10);
        // Should find multiple contours
        assert!(contours.len() > 0);
    }

    // === Vectorize Tests ===

    #[test]
    fn test_vectorize_two_color_image() {
        let img = create_two_color_image(50, 50);
        let result = vectorize(&img, 2, 0.1, 0, false);
        assert!(result.is_ok());

        let vectorized = result.unwrap();
        assert_eq!(vectorized.width, 50);
        assert_eq!(vectorized.height, 50);
        // Should have a background color and at least one curve
        assert!(vectorized.background_color == (255, 255, 255, 255)
            || vectorized.background_color == (255, 0, 0, 255));
    }

    #[test]
    fn test_vectorize_with_smoothing() {
        let img = create_two_color_image(50, 50);

        let result_no_smooth = vectorize(&img, 2, 0.1, 0, false);
        let result_smooth = vectorize(&img, 2, 0.1, 3, false);

        assert!(result_no_smooth.is_ok());
        assert!(result_smooth.is_ok());

        let v_no_smooth = result_no_smooth.unwrap();
        let v_smooth = result_smooth.unwrap();

        // Both should produce valid results
        assert_eq!(v_no_smooth.width, v_smooth.width);
        assert_eq!(v_no_smooth.height, v_smooth.height);
    }

    #[test]
    fn test_vectorize_single_color() {
        let img = create_test_image(
            10,
            10,
            vec![RGBA8::new(255, 0, 0, 255); 100],
        );
        let result = vectorize(&img, 1, 0.1, 0, false);
        assert!(result.is_ok());

        let vectorized = result.unwrap();
        // With single color, should only have background, no curves
        assert_eq!(vectorized.curves.len(), 0);
        assert_eq!(vectorized.background_color, (255, 0, 0, 255));
    }

    #[test]
    fn test_vectorize_preserves_dimensions() {
        let img = create_two_color_image(100, 75);
        let result = vectorize(&img, 8, 0.1, 0, false);
        assert!(result.is_ok());

        let vectorized = result.unwrap();
        assert_eq!(vectorized.width, 100);
        assert_eq!(vectorized.height, 75);
    }

    #[test]
    fn test_vectorized_data_structure() {
        let img = create_two_color_image(50, 50);
        let result = vectorize(&img, 2, 0.1, 0, false);
        assert!(result.is_ok());

        let vectorized = result.unwrap();
        // Check that the structure is valid
        assert_eq!(vectorized.width, 50);
        assert_eq!(vectorized.height, 50);
        assert_eq!(vectorized.background_color.3, 255); // Alpha should be 255

        for curve in &vectorized.curves {
            assert_eq!(curve.color.3, 255); // All colors should have alpha 255
        }
    }

    // === Geometry helper tests ===

    #[test]
    fn test_signed_polygon_area_ccw_vs_cw() {
        let ccw = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 1.0, y: 0.0 },
            Point { x: 1.0, y: 1.0 },
            Point { x: 0.0, y: 1.0 },
        ];
        // Note: marching squares produces CW outer boundaries
        let cw = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 0.0, y: 1.0 },
            Point { x: 1.0, y: 1.0 },
            Point { x: 1.0, y: 0.0 },
        ];
        assert!(signed_polygon_area(&ccw) > 0.0);
        assert!(signed_polygon_area(&cw) < 0.0);
    }

    #[test]
    fn test_point_in_polygon() {
        let square = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
            Point { x: 0.0, y: 10.0 },
        ];
        assert!(point_in_polygon(&Point { x: 5.0, y: 5.0 }, &square));
        assert!(!point_in_polygon(&Point { x: 15.0, y: 5.0 }, &square));
        // Point on edge
        assert!(point_in_polygon(&Point { x: 0.0, y: 5.0 }, &square));
    }

    #[test]
    fn test_has_holes_detects_nested_subpaths() {
        let outer = vec![
            Point { x: 0.0, y: 0.0 },
            Point { x: 10.0, y: 0.0 },
            Point { x: 10.0, y: 10.0 },
            Point { x: 0.0, y: 10.0 },
        ];
        let inner = vec![
            Point { x: 3.0, y: 3.0 },
            Point { x: 3.0, y: 7.0 },
            Point { x: 7.0, y: 7.0 },
            Point { x: 7.0, y: 3.0 },
        ];
        assert!(has_holes(&[outer.clone(), inner.clone()]));
        assert!(!has_holes(&[outer]));
        assert!(!has_holes(&[inner]));
    }

    // === Hierarchical mode tests ===

    #[test]
    fn test_marching_squares_donut_produces_two_contours() {
        let mask = create_test_mask(40, 40, "donut");
        let contours = marching_squares_contours(&mask, 40, 40);
        assert_eq!(contours.len(), 2, "Donut should produce outer + inner contour");
        // Outer boundary has negative signed area (CW), inner (hole) has positive (CCW)
        let areas: Vec<f64> = contours.iter().map(|c| signed_polygon_area(c)).collect();
        let outer_count = areas.iter().filter(|&&a| a < 0.0).count();
        let hole_count = areas.iter().filter(|&&a| a > 0.0).count();
        assert_eq!(outer_count, 1, "Expected one outer boundary");
        assert_eq!(hole_count, 1, "Expected one hole boundary");
    }

    #[test]
    fn test_vectorize_non_hierarchical_filters_holes() {
        let img = create_test_image(40, 40, {
            let mut px = Vec::new();
            for y in 0..40u32 {
                for x in 0..40u32 {
                    let in_outer = x >= 10 && x < 30 && y >= 10 && y < 30;
                    let in_inner = x >= 15 && x < 25 && y >= 15 && y < 25;
                    if in_outer && !in_inner {
                        px.push(RGBA8::new(255, 0, 0, 255));
                    } else {
                        px.push(RGBA8::new(255, 255, 255, 255));
                    }
                }
            }
            px
        });
        // Non-hierarchical: should discard hole contour, keeping only outer
        let result = vectorize(&img, 2, 0.1, 0, false).unwrap();
        // White background is largest; red ring should be the only curve
        assert!(
            !result.curves.is_empty(),
            "Expected at least one non-background curve"
        );
        // Find the non-background curve (not white)
        let ring_curve = result
            .curves
            .iter()
            .find(|c| c.color != (255, 255, 255, 255));
        assert!(ring_curve.is_some(), "Expected a non-white curve for the ring");
        // Only one subpath (outer boundary); hole was filtered out
        assert_eq!(ring_curve.unwrap().subpaths.len(), 1);
    }

    #[test]
    fn test_vectorize_hierarchical_keeps_holes() {
        let img = create_test_image(40, 40, {
            let mut px = Vec::new();
            for y in 0..40u32 {
                for x in 0..40u32 {
                    let in_outer = x >= 10 && x < 30 && y >= 10 && y < 30;
                    let in_inner = x >= 15 && x < 25 && y >= 15 && y < 25;
                    if in_outer && !in_inner {
                        px.push(RGBA8::new(255, 0, 0, 255));
                    } else {
                        px.push(RGBA8::new(255, 255, 255, 255));
                    }
                }
            }
            px
        });
        // Hierarchical: should keep both outer and hole contours
        let result = vectorize(&img, 2, 0.1, 0, true).unwrap();
        let ring_curve = result
            .curves
            .iter()
            .find(|c| c.color != (255, 255, 255, 255));
        assert!(ring_curve.is_some(), "Expected a non-white curve for the ring");
        // Both outer and hole subpaths present
        assert!(
            ring_curve.unwrap().subpaths.len() >= 2,
            "Expected at least 2 subpaths (outer + hole)"
        );
    }
}