fast-canny 0.1.0

Industrial-grade Zero-Allocation SIMD Canny Edge Detector
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
//! 多维度视觉验证 Demo
//!
//! 验证维度:
//!   1. 均匀图像 → 无边缘(sanity check)
//!   2. 阶跃边缘 → 单像素宽垂直线
//!   3. 棋盘格   → 网格边缘
//!   4. 圆形     → 闭合曲线
//!   5. 噪声图   → 阈值鲁棒性
//!   6. 渐变图   → 无边缘(低梯度)
//!   7. 真实感场景(同心矩形框)→ 多边缘
//!   8. 多帧复用 → workspace reset 正确性
//!
//! 运行:
//!   cargo run --example visual_demo
//!
//! 输出:target/visual_demo/*.png

use fast_canny::{CannyConfig, CannyWorkspace, canny};
use image::GrayImage;
use std::fs;
use std::time::Instant;

// ── 输出目录 ──────────────────────────────────────────────────────
const OUT_DIR: &str = "target/visual_demo";

// ── 通用工具 ──────────────────────────────────────────────────────

/// 将 f32 灰度切片(值域任意)归一化到 [0, 255] 后保存为 PNG
fn save_f32_as_gray(pixels: &[f32], w: usize, h: usize, path: &str) {
    let max = pixels.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
    let min = pixels.iter().cloned().fold(f32::INFINITY, f32::min);
    let range = (max - min).max(1e-6);
    let data: Vec<u8> = pixels
        .iter()
        .map(|&v| ((v - min) / range * 255.0) as u8)
        .collect();
    save_gray(&data, w, h, path);
}

/// 保存 u8 灰度图
fn save_gray(pixels: &[u8], w: usize, h: usize, path: &str) {
    let img = GrayImage::from_raw(w as u32, h as u32, pixels.to_vec())
        .expect("failed to create GrayImage");
    img.save(path).expect("failed to save image");
    log::info!("[save] {}", path);
}

/// 统计边缘像素数量及密度
fn edge_stats(edge_map: &[u8], w: usize, h: usize) -> (usize, f64) {
    let count = edge_map.iter().filter(|&&v| v == 255).count();
    let density = count as f64 / (w * h) as f64 * 100.0;
    (count, density)
}

/// 断言:edge_map 只含 {0, 255}(hysteresis 后不变式)
fn assert_binary(edge_map: &[u8], label: &str) {
    for (i, &v) in edge_map.iter().enumerate() {
        assert!(
            v == 0 || v == 255,
            "[{}] non-binary value {} at idx {}",
            label,
            v,
            i
        );
    }
}

// ── 图像生成器 ────────────────────────────────────────────────────

fn make_uniform(w: usize, h: usize, value: f32) -> Vec<f32> {
    vec![value; w * h]
}

fn make_horizontal_step(w: usize, h: usize) -> Vec<f32> {
    (0..w * h)
        .map(|i| if i / w < h / 2 { 0.0 } else { 255.0 })
        .collect()
}

fn make_vertical_step(w: usize, h: usize) -> Vec<f32> {
    (0..w * h)
        .map(|i| if i % w < w / 2 { 0.0 } else { 255.0 })
        .collect()
}

fn make_checkerboard(w: usize, h: usize, cell: usize) -> Vec<f32> {
    (0..w * h)
        .map(|i| {
            let x = i % w;
            let y = i / w;
            if (x / cell + y / cell) % 2 == 0 {
                0.0
            } else {
                255.0
            }
        })
        .collect()
}

fn make_circle(w: usize, h: usize, radius: f32) -> Vec<f32> {
    let cx = w as f32 / 2.0;
    let cy = h as f32 / 2.0;
    (0..w * h)
        .map(|i| {
            let x = (i % w) as f32 - cx;
            let y = (i / w) as f32 - cy;
            if (x * x + y * y).sqrt() < radius {
                255.0
            } else {
                0.0
            }
        })
        .collect()
}

fn make_noise(w: usize, h: usize, seed: u64) -> Vec<f32> {
    // 简单 LCG 伪随机,无需外部依赖
    let mut state = seed;
    (0..w * h)
        .map(|_| {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) & 0xFF) as f32
        })
        .collect()
}

fn make_gradient(w: usize, h: usize) -> Vec<f32> {
    if w <= 1 {
        return vec![0.0f32; w * h];
    }
    (0..w * h)
        .map(|i| (i % w) as f32 / (w - 1) as f32 * 255.0)
        .collect()
}

/// 同心矩形框(模拟真实感场景)
fn make_concentric_rects(w: usize, h: usize) -> Vec<f32> {
    let mut img = vec![0.0f32; w * h];
    for margin in [10usize, 25, 45, 70] {
        if margin * 2 >= w || margin * 2 >= h {
            break;
        }
        for x in margin..w - margin {
            img[margin * w + x] = 255.0;
            img[(h - margin - 1) * w + x] = 255.0;
        }
        for y in margin..h - margin {
            img[y * w + margin] = 255.0;
            img[y * w + (w - margin - 1)] = 255.0;
        }
    }
    img
}

// ── 单个测试用例 ──────────────────────────────────────────────────

struct Case {
    label: &'static str,
    src: Vec<f32>,
    w: usize,
    h: usize,
    cfg: CannyConfig,
    /// 期望边缘数量范围(None = 不检查)
    expect_min: Option<usize>,
    expect_max: Option<usize>,
}

impl Case {
    fn run(&self, ws: &mut CannyWorkspace) {
        let t0 = Instant::now();

        // 保存输入图
        let src_path = format!("{}/{}_src.png", OUT_DIR, self.label);
        save_f32_as_gray(&self.src, self.w, self.h, &src_path);

        // 执行 Canny
        let edge_map = canny(&self.src, ws, &self.cfg)
            .unwrap_or_else(|e| panic!("[{}] canny failed: {}", self.label, e));

        // 不变式验证
        assert_binary(edge_map, self.label);
        assert_eq!(
            edge_map.len(),
            self.w * self.h,
            "[{}] output length mismatch",
            self.label
        );

        // 统计
        let (count, density) = edge_stats(edge_map, self.w, self.h);

        // 数量断言
        if let Some(min) = self.expect_min {
            assert!(
                count >= min,
                "[{}] too few edges: {} < {} (density={:.2}%)",
                self.label,
                count,
                min,
                density
            );
        }
        if let Some(max) = self.expect_max {
            assert!(
                count <= max,
                "[{}] too many edges: {} > {} (density={:.2}%)",
                self.label,
                count,
                max,
                density
            );
        }

        // 保存边缘图
        let edge_path = format!("{}/{}_edge.png", OUT_DIR, self.label);
        save_gray(edge_map, self.w, self.h, &edge_path);

        // 保存叠加图(边缘用红色标注,输出为 RGB)
        save_overlay(
            &self.src,
            edge_map,
            self.w,
            self.h,
            &format!("{}/{}_overlay.png", OUT_DIR, self.label),
        );

        log::info!(
            "[{}] edges={} ({:.2}%), elapsed={:.2}ms",
            self.label,
            count,
            density,
            t0.elapsed().as_secs_f64() * 1000.0
        );
        println!(
            "  ✓ {:30} edges={:6} ({:5.2}%)  [{:.2}ms]",
            self.label,
            count,
            density,
            t0.elapsed().as_secs_f64() * 1000.0
        );
    }
}

/// 将边缘叠加到原图上(边缘=红色,其余=灰度),保存为 RGB PNG
fn save_overlay(src: &[f32], edge_map: &[u8], w: usize, h: usize, path: &str) {
    use image::RgbImage;
    let max = src.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
    let min = src.iter().cloned().fold(f32::INFINITY, f32::min);
    let range = (max - min).max(1e-6);

    let mut img = RgbImage::new(w as u32, h as u32);
    for (i, pixel) in img.pixels_mut().enumerate() {
        let gray = ((src[i] - min) / range * 255.0) as u8;
        if edge_map[i] == 255 {
            *pixel = image::Rgb([255u8, 0, 0]); // 红色标注边缘
        } else {
            *pixel = image::Rgb([gray, gray, gray]);
        }
    }
    img.save(path).expect("failed to save overlay");
    log::info!("[save] {}", path);
}

// ── 多帧复用验证 ──────────────────────────────────────────────────

fn verify_multiframe_reset(ws: &mut CannyWorkspace) {
    let w = ws.width;
    let h = ws.height;
    let cfg = CannyConfig::builder()
        .sigma(0.0)
        .thresholds(10.0, 30.0)
        .build()
        .unwrap();

    // 帧 1:阶跃图像(有边缘)
    let src_step = make_vertical_step(w, h);
    let edge1 = canny(&src_step, ws, &cfg).unwrap().to_vec();
    let (count1, _) = edge_stats(&edge1, w, h);

    // 帧 2:均匀图像(无边缘)
    let src_uniform = make_uniform(w, h, 128.0);
    let edge2 = canny(&src_uniform, ws, &cfg).unwrap().to_vec();
    let (count2, _) = edge_stats(&edge2, w, h);

    // 帧 3:再次阶跃(应与帧 1 一致)
    let edge3 = canny(&src_step, ws, &cfg).unwrap().to_vec();
    let (count3, _) = edge_stats(&edge3, w, h);

    assert_eq!(
        count2, 0,
        "frame2 (uniform) should have 0 edges, got {}",
        count2
    );
    assert_eq!(
        count1, count3,
        "frame1 and frame3 (same input) should have same edge count: {} vs {}",
        count1, count3
    );
    assert_eq!(
        edge1, edge3,
        "frame1 and frame3 edge maps must be identical"
    );

    println!(
        "  ✓ frame1(step)={} edges, frame2(uniform)={} edges, frame3(step)={} edges — reset OK",
        count1, count2, count3
    );
    log::info!(
        "[multiframe] count1={}, count2={}, count3={}",
        count1,
        count2,
        count3
    );
}

// ── 阈值敏感性扫描 ────────────────────────────────────────────────

fn threshold_sensitivity_scan(ws: &mut CannyWorkspace) {
    println!("\n[阈值敏感性扫描 — 棋盘格 128x128]");
    let (w, h) = (128, 128);
    let src = make_checkerboard(w, h, 16);

    let configs: &[(&str, f32, f32)] = &[
        ("very_low", 5.0, 15.0),
        ("low", 20.0, 60.0),
        ("medium", 50.0, 150.0),
        ("high", 100.0, 200.0),
        ("very_high", 200.0, 400.0),
    ];

    for &(label, low, high) in configs {
        let cfg = CannyConfig::builder()
            .sigma(1.0)
            .thresholds(low, high)
            .build()
            .unwrap();
        let edge_map = canny(&src, ws, &cfg).unwrap();
        let (count, density) = edge_stats(edge_map, w, h);
        let path = format!("{}/threshold_{}_{}_edge.png", OUT_DIR, label, w);
        save_gray(edge_map, w, h, &path);
        println!(
            "  {:12} low={:5.0} high={:5.0}  edges={:5} ({:.2}%)",
            label, low, high, count, density
        );
    }
}

// ── sigma 敏感性扫描 ──────────────────────────────────────────────

fn sigma_sensitivity_scan(ws: &mut CannyWorkspace) {
    println!("\n[Sigma 敏感性扫描 — 圆形 128x128]");
    let (w, h) = (128, 128);
    let src = make_circle(w, h, 40.0);

    let sigmas: &[f32] = &[0.0, 0.5, 1.0, 2.0, 4.0];

    for &sigma in sigmas {
        let cfg = CannyConfig::builder()
            .sigma(sigma)
            .thresholds(20.0, 60.0)
            .build()
            .unwrap();
        let edge_map = canny(&src, ws, &cfg).unwrap();
        let (count, density) = edge_stats(edge_map, w, h);
        let label = format!("sigma_{:.1}", sigma).replace('.', "_");
        let path = format!("{}/circle_{}_edge.png", OUT_DIR, label);
        save_gray(edge_map, w, h, &path);
        println!("  sigma={:.1}  edges={:5} ({:.2}%)", sigma, count, density);
    }
}

// ── 主函数 ────────────────────────────────────────────────────────

fn main() {
    // 初始化日志(RUST_LOG=info 可见详细输出)
    env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .init();

    // 创建输出目录
    fs::create_dir_all(OUT_DIR).expect("failed to create output dir");
    println!("输出目录:{}\n", OUT_DIR);

    // ── 构建测试用例 ──────────────────────────────────────────────
    let cfg_default = || {
        CannyConfig::builder()
            .sigma(1.0)
            .thresholds(30.0, 90.0)
            .build()
            .unwrap()
    };
    let cfg_sharp = || {
        CannyConfig::builder()
            .sigma(0.0)
            .thresholds(10.0, 30.0)
            .build()
            .unwrap()
    };

    let (w, h) = (256, 256);

    let cases: Vec<Case> = vec![
        // 1. 均匀图像 → 零边缘
        Case {
            label: "01_uniform",
            src: make_uniform(w, h, 128.0),
            w,
            h,
            cfg: cfg_default(),
            expect_min: None,
            expect_max: Some(0),
        },
        // 2. 垂直阶跃 → 单列边缘
        Case {
            label: "02_vertical_step",
            src: make_vertical_step(w, h),
            w,
            h,
            cfg: cfg_sharp(),
            expect_min: Some(1),
            expect_max: None,
        },
        // 3. 水平阶跃 → 单行边缘
        Case {
            label: "03_horizontal_step",
            src: make_horizontal_step(w, h),
            w,
            h,
            cfg: cfg_sharp(),
            expect_min: Some(1),
            expect_max: None,
        },
        // 4. 棋盘格 → 网格边缘
        Case {
            label: "04_checkerboard",
            src: make_checkerboard(w, h, 32),
            w,
            h,
            cfg: cfg_default(),
            expect_min: Some(10),
            expect_max: None,
        },
        // 5. 圆形 → 闭合曲线
        Case {
            label: "05_circle",
            src: make_circle(w, h, 80.0),
            w,
            h,
            cfg: cfg_default(),
            expect_min: Some(10),
            expect_max: None,
        },
        // 6. 噪声图(高阈值)→ 稀疏边缘
        Case {
            label: "06_noise_high_thresh",
            src: make_noise(w, h, 42),
            w,
            h,
            cfg: CannyConfig::builder()
                .sigma(1.5)
                .thresholds(80.0, 200.0)
                .build()
                .unwrap(),
            expect_min: None,
            expect_max: None,
        },
        // 7. 噪声图(低阈值)→ 密集边缘
        Case {
            label: "07_noise_low_thresh",
            src: make_noise(w, h, 42),
            w,
            h,
            cfg: CannyConfig::builder()
                .sigma(0.5)
                .thresholds(10.0, 30.0)
                .build()
                .unwrap(),
            expect_min: None,
            expect_max: None,
        },
        // 8. 线性渐变 → 无边缘(梯度均匀,低于阈值)
        Case {
            label: "08_gradient",
            src: make_gradient(w, h),
            w,
            h,
            cfg: CannyConfig::builder()
                .sigma(1.0)
                .thresholds(100.0, 200.0)
                .build()
                .unwrap(),
            expect_min: None,
            expect_max: None,
        },
        // 9. 同心矩形框 → 多条平行边缘
        Case {
            label: "09_concentric_rects",
            src: make_concentric_rects(w, h),
            w,
            h,
            cfg: cfg_sharp(),
            expect_min: Some(10),
            expect_max: None,
        },
        // 10. 最小尺寸 3×3
        Case {
            label: "10_min_size_3x3",
            src: make_vertical_step(3, 3),
            w: 3,
            h: 3,
            cfg: CannyConfig::builder()
                .sigma(0.0)
                .thresholds(1.0, 10.0)
                .build()
                .unwrap(),
            expect_min: None,
            expect_max: None,
        },
    ];

    // ── 创建 workspace(最大尺寸复用)────────────────────────────
    let mut ws = CannyWorkspace::new(w, h).expect("workspace creation failed");

    // ── 执行所有用例 ──────────────────────────────────────────────
    println!("=== 基础用例验证 ===");
    for case in &cases {
        // 小图需要独立 workspace
        if case.w != w || case.h != h {
            let mut small_ws =
                CannyWorkspace::new(case.w, case.h).expect("small workspace creation failed");
            case.run(&mut small_ws);
        } else {
            case.run(&mut ws);
        }
    }

    // ── 多帧复用验证 ──────────────────────────────────────────────
    let mut ws64 = CannyWorkspace::new(64, 64).unwrap();
    verify_multiframe_reset(&mut ws64);

    // ── 阈值敏感性扫描 ────────────────────────────────────────────
    let mut ws128 = CannyWorkspace::new(128, 128).unwrap();
    threshold_sensitivity_scan(&mut ws128);

    // ── sigma 敏感性扫描 ──────────────────────────────────────────
    sigma_sensitivity_scan(&mut ws128);

    println!("\n✅ 所有验证通过,结果图像已保存至:{}/", OUT_DIR);
    println!("   每个用例生成三张图:_src.png / _edge.png / _overlay.png");
}