leptonica 0.4.0

Rust port of Leptonica image processing 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
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
//! Edge detection and enhancement operations

use crate::core::{Numa, Pix, PixelDepth, pix::RgbComponent};
use crate::filter::{FilterError, FilterResult, Kernel, blockconv_gray, convolve_gray};

/// Edge detection orientation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeOrientation {
    /// Detect horizontal edges
    Horizontal,
    /// Detect vertical edges
    Vertical,
    /// Detect all edges
    All,
}

/// Apply Sobel edge detection
///
/// Applies a 3x3 Sobel gradient filter and normalizes by dividing
/// by 8 (the sum of the absolute kernel weights), matching C
/// Leptonica `pixSobelEdgeFilter()`.
///
/// # Arguments
/// * `pix` - Input 8-bit grayscale image
/// * `orientation` - Which edges to detect
pub fn sobel_edge(pix: &Pix, orientation: EdgeOrientation) -> FilterResult<Pix> {
    check_grayscale(pix)?;

    // Add 1-pixel mirrored border, matching C pixAddMirroredBorder(pixs,1,1,1,1)
    let bordered = pix.add_mirrored_border(1, 1, 1, 1)?;

    match orientation {
        EdgeOrientation::Horizontal => {
            let kernel = Kernel::sobel_horizontal();
            sobel_convolve_and_abs(&bordered, pix.width(), pix.height(), &kernel)
        }
        EdgeOrientation::Vertical => {
            let kernel = Kernel::sobel_vertical();
            sobel_convolve_and_abs(&bordered, pix.width(), pix.height(), &kernel)
        }
        EdgeOrientation::All => {
            let h_kernel = Kernel::sobel_horizontal();
            let v_kernel = Kernel::sobel_vertical();
            sobel_combined(&bordered, pix.width(), pix.height(), &h_kernel, &v_kernel)
        }
    }
}

/// Apply Laplacian edge detection
pub fn laplacian_edge(pix: &Pix) -> FilterResult<Pix> {
    check_grayscale(pix)?;
    let kernel = Kernel::laplacian();
    convolve_and_abs(pix, &kernel)
}

/// Sobel-specific convolution: convolve bordered image, take absolute
/// value, and normalize by >>3 (divide by 8).
///
/// `bordered` is the source image with 1-pixel mirrored border already added.
/// `out_w` / `out_h` are the dimensions of the original (unbordered) image.
fn sobel_convolve_and_abs(
    bordered: &Pix,
    out_w: u32,
    out_h: u32,
    kernel: &Kernel,
) -> FilterResult<Pix> {
    let kw = kernel.width();
    let kh = kernel.height();
    let kcx = kernel.center_x() as i32;
    let kcy = kernel.center_y() as i32;

    let out_pix = Pix::new(out_w, out_h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    // The bordered image has 1-pixel padding on each side, so pixel (x, y)
    // of the original maps to (x + 1, y + 1) in bordered.
    for y in 0..out_h {
        for x in 0..out_w {
            let mut sum = 0i32;

            for ky in 0..kh {
                for kx in 0..kw {
                    // In the bordered image, pixel (x+1, y+1) is the centre.
                    // Kernel offset from centre is (kx - kcx, ky - kcy).
                    let bx = (x as i32 + 1 + kx as i32 - kcx) as u32;
                    let by = (y as i32 + 1 + ky as i32 - kcy) as u32;

                    let pixel = bordered.get_pixel_unchecked(bx, by) as i32;
                    let k = kernel.get(kx, ky).unwrap_or(0.0) as i32;
                    sum += pixel * k;
                }
            }

            // Normalise: >>3 (divide by 8), matching C leptonica
            let result = (sum.abs() >> 3) as u32;
            out_mut.set_pixel_unchecked(x, y, result);
        }
    }

    Ok(out_mut.into())
}

/// Convolve and take absolute value (for non-Sobel edge detection, e.g. Laplacian)
fn convolve_and_abs(pix: &Pix, kernel: &Kernel) -> FilterResult<Pix> {
    let w = pix.width();
    let h = pix.height();
    let kw = kernel.width();
    let kh = kernel.height();
    let kcx = kernel.center_x() as i32;
    let kcy = kernel.center_y() as i32;

    let out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    for y in 0..h {
        for x in 0..w {
            let mut sum = 0.0f32;

            for ky in 0..kh {
                for kx in 0..kw {
                    let sx = x as i32 + (kx as i32 - kcx);
                    let sy = y as i32 + (ky as i32 - kcy);

                    let sx = sx.clamp(0, w as i32 - 1) as u32;
                    let sy = sy.clamp(0, h as i32 - 1) as u32;

                    let pixel = pix.get_pixel_unchecked(sx, sy) as f32;
                    let k = kernel.get(kx, ky).unwrap_or(0.0);
                    sum += pixel * k;
                }
            }

            let result = sum.abs().clamp(0.0, 255.0) as u32;
            out_mut.set_pixel_unchecked(x, y, result);
        }
    }

    Ok(out_mut.into())
}

/// Combined Sobel: magnitude of both gradient directions, with >>3
/// normalization on each component before summing, matching C
/// `pixSobelEdgeFilter(pixs, L_ALL_EDGES)`.
///
/// `bordered` is the source image with 1-pixel mirrored border.
/// `out_w` / `out_h` are the original (unbordered) dimensions.
fn sobel_combined(
    bordered: &Pix,
    out_w: u32,
    out_h: u32,
    h_kernel: &Kernel,
    v_kernel: &Kernel,
) -> FilterResult<Pix> {
    let kw = h_kernel.width();
    let kh = h_kernel.height();
    let kcx = h_kernel.center_x() as i32;
    let kcy = h_kernel.center_y() as i32;

    let out_pix = Pix::new(out_w, out_h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    for y in 0..out_h {
        for x in 0..out_w {
            let mut sum_h = 0i32;
            let mut sum_v = 0i32;

            for ky in 0..kh {
                for kx in 0..kw {
                    let bx = (x as i32 + 1 + kx as i32 - kcx) as u32;
                    let by = (y as i32 + 1 + ky as i32 - kcy) as u32;

                    let pixel = bordered.get_pixel_unchecked(bx, by) as i32;
                    sum_h += pixel * h_kernel.get(kx, ky).unwrap_or(0.0) as i32;
                    sum_v += pixel * v_kernel.get(kx, ky).unwrap_or(0.0) as i32;
                }
            }

            // Normalize each component by >>3, then sum with L_MIN(255, gx+gy)
            let gx = sum_v.abs() >> 3;
            let gy = sum_h.abs() >> 3;
            let result = (gx + gy).min(255) as u32;
            out_mut.set_pixel_unchecked(x, y, result);
        }
    }

    Ok(out_mut.into())
}

/// Apply sharpening filter
pub fn sharpen(pix: &Pix) -> FilterResult<Pix> {
    check_grayscale(pix)?;
    let kernel = Kernel::sharpen();
    convolve_gray(pix, &kernel)
}

/// Apply unsharp masking
///
/// # Arguments
/// * `pix` - Input image
/// * `radius` - Blur radius
/// * `amount` - Sharpening strength (0.0-1.0 typical, can be higher)
pub fn unsharp_mask(pix: &Pix, radius: u32, amount: f32) -> FilterResult<Pix> {
    check_grayscale(pix)?;

    let w = pix.width();
    let h = pix.height();

    // 1. Create blurred version
    let size = 2 * radius + 1;
    let blur_kernel = Kernel::gaussian(size, radius as f32)?;
    let blurred = convolve_gray(pix, &blur_kernel)?;

    // 2. Compute: result = original + amount * (original - blurred)
    let out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    for y in 0..h {
        for x in 0..w {
            let orig = pix.get_pixel_unchecked(x, y) as f32;
            let blur = blurred.get_pixel_unchecked(x, y) as f32;

            let diff = orig - blur;
            let result = orig + amount * diff;
            let result = result.round().clamp(0.0, 255.0) as u32;

            out_mut.set_pixel_unchecked(x, y, result);
        }
    }

    Ok(out_mut.into())
}

/// Fast unsharp masking using block convolution
///
/// Uses block convolution for faster blurring instead of Gaussian convolution.
/// Only supports halfwidth=1 (3x3) or halfwidth=2 (5x5) for speed.
///
/// # Arguments
/// * `pix` - Input image (8 bpp grayscale for grayfast, 32 bpp for color)
/// * `halfwidth` - Kernel half-width (1 or 2; kernel size = 2*halfwidth+1)
/// * `amount` - Sharpening strength (typically 0.2-0.7)
pub fn unsharp_masking_fast(pix: &Pix, halfwidth: u32, amount: f32) -> FilterResult<Pix> {
    let depth = pix.depth();

    // Check supported depths
    if depth != PixelDepth::Bit8 && depth != PixelDepth::Bit32 {
        return Err(FilterError::UnsupportedDepth {
            expected: "8 or 32 bpp",
            actual: depth.bits(),
        });
    }

    // If 8bpp, dispatch to gray_fast
    if depth == PixelDepth::Bit8 {
        return unsharp_masking_gray_fast(pix, halfwidth, amount);
    }

    // 32bpp: extract R, G, B channels, apply gray_fast to each, recombine
    let pix_r = pix.get_rgb_component(RgbComponent::Red)?;
    let pix_g = pix.get_rgb_component(RgbComponent::Green)?;
    let pix_b = pix.get_rgb_component(RgbComponent::Blue)?;

    let pix_rs = unsharp_masking_gray_fast(&pix_r, halfwidth, amount)?;
    let pix_gs = unsharp_masking_gray_fast(&pix_g, halfwidth, amount)?;
    let pix_bs = unsharp_masking_gray_fast(&pix_b, halfwidth, amount)?;

    let mut result = Pix::create_rgb_image(&pix_rs, &pix_gs, &pix_bs)?;

    // If the original had alpha channel (spp=4), copy it
    if pix.spp() == 4 {
        let pix_a = pix.get_rgb_component(RgbComponent::Alpha)?;
        let mut result_mut = result.try_into_mut().unwrap();
        result_mut.set_rgb_component(&pix_a, RgbComponent::Alpha)?;
        result = result_mut.into();
    }

    Ok(result)
}

/// Fast unsharp masking for grayscale images
///
/// Uses block convolution for faster blurring.
pub fn unsharp_masking_gray_fast(pix: &Pix, halfwidth: u32, amount: f32) -> FilterResult<Pix> {
    // Validate input
    if pix.depth() != PixelDepth::Bit8 {
        return Err(FilterError::UnsupportedDepth {
            expected: "8-bpp grayscale",
            actual: pix.depth().bits(),
        });
    }

    // If amount <= 0.0, return a clone (no sharpening)
    if amount <= 0.0 {
        return Ok(pix.clone());
    }

    // Validate halfwidth
    if halfwidth != 1 && halfwidth != 2 {
        return Err(FilterError::InvalidParameters(
            "halfwidth must be 1 or 2".to_string(),
        ));
    }

    let w = pix.width();
    let h = pix.height();

    // Use block convolution for fast blurring
    // blockconv_gray(pix, None, wc, hc) where kernel size = 2*halfwidth+1
    let blurred = blockconv_gray(pix, None, halfwidth, halfwidth)?;

    // Compute: result = original + amount * (original - blurred)
    let out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    for y in 0..h {
        for x in 0..w {
            let orig = pix.get_pixel_unchecked(x, y) as f32;
            let blur = blurred.get_pixel_unchecked(x, y) as f32;

            let diff = orig - blur;
            let result = orig + amount * diff;
            let result = result.round().clamp(0.0, 255.0) as u32;

            out_mut.set_pixel_unchecked(x, y, result);
        }
    }

    Ok(out_mut.into())
}

/// Apply emboss effect
///
/// Output values are centered around 128 (flat regions produce ~128,
/// edges produce values above or below 128 depending on gradient direction).
/// This differs from edge detection functions which output absolute magnitudes.
pub fn emboss(pix: &Pix) -> FilterResult<Pix> {
    check_grayscale(pix)?;

    let kernel = Kernel::emboss();
    let w = pix.width();
    let h = pix.height();
    let kw = kernel.width();
    let kh = kernel.height();
    let kcx = kernel.center_x() as i32;
    let kcy = kernel.center_y() as i32;

    let out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    for y in 0..h {
        for x in 0..w {
            let mut sum = 0.0f32;

            for ky in 0..kh {
                for kx in 0..kw {
                    let sx = x as i32 + (kx as i32 - kcx);
                    let sy = y as i32 + (ky as i32 - kcy);

                    let sx = sx.clamp(0, w as i32 - 1) as u32;
                    let sy = sy.clamp(0, h as i32 - 1) as u32;

                    let pixel = pix.get_pixel_unchecked(sx, sy) as f32;
                    let k = kernel.get(kx, ky).unwrap_or(0.0);
                    sum += pixel * k;
                }
            }

            // Add 128 to center the emboss effect
            let result = (sum + 128.0).round().clamp(0.0, 255.0) as u32;
            out_mut.set_pixel_unchecked(x, y, result);
        }
    }

    Ok(out_mut.into())
}

/// Side from which to measure an edge profile
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeSide {
    /// Scan from the left side
    FromLeft,
    /// Scan from the right side
    FromRight,
    /// Scan from the top
    FromTop,
    /// Scan from the bottom
    FromBottom,
}

/// Two-sided edge filter
///
/// Detects edges by computing directional gradients on both sides of a
/// transition.  Only registers edges where gradients have the same sign,
/// storing the minimum absolute gradient.  This suppresses single-pixel
/// noise.
///
/// # Arguments
/// * `pix` - Input 8bpp grayscale image
/// * `orientation` - `Horizontal` or `Vertical` (not `All`)
///
/// # See also
///
/// C Leptonica: `pixTwoSidedEdgeFilter()` in `edge.c`
pub fn two_sided_edge_filter(pix: &Pix, orientation: EdgeOrientation) -> FilterResult<Pix> {
    check_grayscale(pix)?;
    if orientation == EdgeOrientation::All {
        return Err(FilterError::InvalidParameters(
            "orientflag must be Horizontal or Vertical, not All".to_string(),
        ));
    }

    let w = pix.width();
    let h = pix.height();

    if orientation == EdgeOrientation::Vertical && w < 2 {
        return Err(FilterError::InvalidParameters(
            "image width must be >= 2 for vertical edge filter".to_string(),
        ));
    }
    if orientation == EdgeOrientation::Horizontal && h < 2 {
        return Err(FilterError::InvalidParameters(
            "image height must be >= 2 for horizontal edge filter".to_string(),
        ));
    }

    let out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    if orientation == EdgeOrientation::Vertical {
        for y in 0..h {
            let mut cval = pix.get_pixel_unchecked(1, y) as i32;
            let mut lgrad = cval - pix.get_pixel_unchecked(0, y) as i32;
            for x in 1..w - 1 {
                let rval = pix.get_pixel_unchecked(x + 1, y) as i32;
                let rgrad = rval - cval;
                if lgrad * rgrad > 0 {
                    let val = if lgrad < 0 {
                        -lgrad.max(rgrad) // both negative: max is less negative
                    } else {
                        lgrad.min(rgrad)
                    };
                    out_mut.set_pixel_unchecked(x, y, val as u32);
                }
                lgrad = rgrad;
                cval = rval;
            }
        }
    } else {
        // Horizontal edges
        for x in 0..w {
            let mut cval = pix.get_pixel_unchecked(x, 1) as i32;
            let mut tgrad = cval - pix.get_pixel_unchecked(x, 0) as i32;
            for y in 1..h - 1 {
                let bval = pix.get_pixel_unchecked(x, y + 1) as i32;
                let bgrad = bval - cval;
                if tgrad * bgrad > 0 {
                    let val = if tgrad < 0 {
                        -tgrad.max(bgrad)
                    } else {
                        tgrad.min(bgrad)
                    };
                    out_mut.set_pixel_unchecked(x, y, val as u32);
                }
                tgrad = bgrad;
                cval = bval;
            }
        }
    }

    Ok(out_mut.into())
}

/// Get edge profile from a binary image
///
/// Extracts foreground edge pixel positions from one side of the image.
/// For left/right scans, returns a Numa of length `h` with x-positions.
/// For top/bottom scans, returns a Numa of length `w` with y-positions.
///
/// # Arguments
/// * `pix` - Input 1bpp binary image
/// * `side` - Which side to scan from
///
/// # See also
///
/// C Leptonica: `pixGetEdgeProfile()` in `edge.c`
pub fn get_edge_profile(pix: &Pix, side: EdgeSide) -> FilterResult<Numa> {
    if pix.depth() != PixelDepth::Bit1 {
        return Err(FilterError::UnsupportedDepth {
            expected: "1-bpp binary",
            actual: pix.depth().bits(),
        });
    }

    let w = pix.width();
    let h = pix.height();
    let mut na = Numa::with_capacity(
        if matches!(side, EdgeSide::FromLeft | EdgeSide::FromRight) {
            h as usize
        } else {
            w as usize
        },
    );

    match side {
        EdgeSide::FromLeft => {
            // For each row, find the leftmost ON pixel
            for y in 0..h {
                let mut loc = 0i32;
                for x in 0..w {
                    if pix.get_pixel_unchecked(x, y) == 1 {
                        loc = x as i32;
                        break;
                    }
                    if x == w - 1 {
                        loc = 0;
                    }
                }
                na.push(loc as f32);
            }
        }
        EdgeSide::FromRight => {
            // For each row, find the rightmost ON pixel
            for y in 0..h {
                let mut loc = (w - 1) as i32;
                for x in (0..w).rev() {
                    if pix.get_pixel_unchecked(x, y) == 1 {
                        loc = x as i32;
                        break;
                    }
                    if x == 0 {
                        loc = (w - 1) as i32;
                    }
                }
                na.push(loc as f32);
            }
        }
        EdgeSide::FromTop => {
            // For each column, find the topmost ON pixel
            for x in 0..w {
                let mut loc = 0i32;
                for y in 0..h {
                    if pix.get_pixel_unchecked(x, y) == 1 {
                        loc = y as i32;
                        break;
                    }
                    if y == h - 1 {
                        loc = 0;
                    }
                }
                na.push(loc as f32);
            }
        }
        EdgeSide::FromBottom => {
            // For each column, find the bottommost ON pixel
            for x in 0..w {
                let mut loc = (h - 1) as i32;
                for y in (0..h).rev() {
                    if pix.get_pixel_unchecked(x, y) == 1 {
                        loc = y as i32;
                        break;
                    }
                    if y == 0 {
                        loc = (h - 1) as i32;
                    }
                }
                na.push(loc as f32);
            }
        }
    }

    Ok(na)
}

/// Measure edge smoothness of a binary image
///
/// Quantifies edge smoothness by measuring jumps and reversals in the
/// edge profile.
///
/// # Arguments
/// * `pix` - Input 1bpp binary image
/// * `side` - Which side to scan from
/// * `minjump` - Minimum pixel jump to count (>= 1)
/// * `minreversal` - Minimum reversal depth to count (>= 1)
///
/// # Returns
/// `(jumps_per_length, jumpsum_per_length, reversals_per_length)`
///
/// # See also
///
/// C Leptonica: `pixMeasureEdgeSmoothness()` in `edge.c`
pub fn measure_edge_smoothness(
    pix: &Pix,
    side: EdgeSide,
    minjump: u32,
    minreversal: u32,
) -> FilterResult<(f32, f32, f32)> {
    if pix.depth() != PixelDepth::Bit1 {
        return Err(FilterError::UnsupportedDepth {
            expected: "1-bpp binary",
            actual: pix.depth().bits(),
        });
    }
    if minjump < 1 {
        return Err(FilterError::InvalidParameters(
            "minjump must be >= 1".to_string(),
        ));
    }
    if minreversal < 1 {
        return Err(FilterError::InvalidParameters(
            "minreversal must be >= 1".to_string(),
        ));
    }

    let na = get_edge_profile(pix, side)?;
    let n = na.len();
    if n < 2 {
        return Ok((0.0, 0.0, 0.0));
    }

    // Compute jumps
    let mut njumps = 0u32;
    let mut jumpsum = 0u32;
    let mut val = na.get_i32(0).unwrap_or(0);
    for i in 1..n {
        let nval = na.get_i32(i).unwrap_or(0);
        let diff = (nval - val).unsigned_abs();
        if diff >= minjump {
            njumps += 1;
            jumpsum += diff;
        }
        val = nval;
    }
    let len = (n - 1) as f32;
    let jpl = njumps as f32 / len;
    let jspl = jumpsum as f32 / len;

    // Compute reversals
    let nae = na
        .find_extrema(minreversal as f32)
        .map_err(|e| FilterError::InvalidParameters(format!("find_extrema failed: {e}")))?;
    let nreversal = if nae.len() > 1 { nae.len() - 1 } else { 0 };
    let rpl = nreversal as f32 / len;

    Ok((jpl, jspl, rpl))
}

fn check_grayscale(pix: &Pix) -> FilterResult<()> {
    if pix.depth() != PixelDepth::Bit8 {
        return Err(FilterError::UnsupportedDepth {
            expected: "8-bpp grayscale",
            actual: pix.depth().bits(),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_image() -> Pix {
        let pix = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // Create a pattern with edges
        for y in 0..10 {
            for x in 0..10 {
                let val = if x < 5 { 50 } else { 200 };
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }

        pix_mut.into()
    }

    #[test]
    fn test_sobel_vertical() {
        let pix = create_test_image();
        let edges = sobel_edge(&pix, EdgeOrientation::Vertical).unwrap();

        // Vertical edge at x=4-5 should be detected
        let edge_val = edges.get_pixel_unchecked(4, 5);
        let non_edge_val = edges.get_pixel_unchecked(1, 5);

        assert!(edge_val > non_edge_val);
    }

    #[test]
    fn test_sobel_all() {
        let pix = create_test_image();
        let edges = sobel_edge(&pix, EdgeOrientation::All).unwrap();

        assert_eq!(edges.width(), pix.width());
        assert_eq!(edges.height(), pix.height());
    }

    #[test]
    fn test_laplacian() {
        let pix = create_test_image();
        let edges = laplacian_edge(&pix).unwrap();

        assert_eq!(edges.width(), pix.width());
    }

    #[test]
    fn test_sharpen() {
        let pix = create_test_image();
        let sharpened = sharpen(&pix).unwrap();

        assert_eq!(sharpened.width(), pix.width());
    }

    #[test]
    fn test_unsharp_mask() {
        let pix = create_test_image();
        let sharpened = unsharp_mask(&pix, 1, 0.5).unwrap();

        assert_eq!(sharpened.width(), pix.width());
    }

    #[test]
    fn test_emboss() {
        let pix = create_test_image();
        let embossed = emboss(&pix).unwrap();

        assert_eq!(embossed.width(), pix.width());
    }

    #[test]
    fn test_unsharp_masking_gray_fast_basic() {
        let pix = create_test_image();

        // Test with halfwidth=1, amount=0.5
        let result = unsharp_masking_gray_fast(&pix, 1, 0.5).unwrap();

        assert_eq!(result.width(), pix.width());
        assert_eq!(result.height(), pix.height());
        assert_eq!(result.depth(), PixelDepth::Bit8);
    }

    #[test]
    fn test_unsharp_masking_gray_fast_halfwidth2() {
        let pix = create_test_image();

        // Test with halfwidth=2, amount=0.7
        let result = unsharp_masking_gray_fast(&pix, 2, 0.7).unwrap();

        assert_eq!(result.width(), pix.width());
        assert_eq!(result.height(), pix.height());
    }

    #[test]
    fn test_unsharp_masking_gray_fast_no_op() {
        let pix = create_test_image();

        // Test with amount=0.0 (should return clone)
        let result = unsharp_masking_gray_fast(&pix, 1, 0.0).unwrap();

        // Should be a clone of original
        assert_eq!(result.width(), pix.width());
        assert_eq!(result.height(), pix.height());
    }

    #[test]
    fn test_unsharp_masking_gray_fast_rejects_non_8bpp() {
        let pix = Pix::new(10, 10, PixelDepth::Bit32).unwrap();

        let result = unsharp_masking_gray_fast(&pix, 1, 0.5);

        assert!(result.is_err());
    }

    #[test]
    fn test_unsharp_masking_fast_8bpp() {
        let pix = create_test_image();

        // Test with 8bpp image
        let result = unsharp_masking_fast(&pix, 1, 0.5).unwrap();

        assert_eq!(result.width(), pix.width());
        assert_eq!(result.height(), pix.height());
        assert_eq!(result.depth(), PixelDepth::Bit8);
    }

    #[test]
    fn test_unsharp_masking_fast_32bpp_rgb() {
        // Create a 32bpp RGB test image
        let pix = Pix::new(10, 10, PixelDepth::Bit32).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        for y in 0..10 {
            for x in 0..10 {
                // Create RGB pattern
                let r = if x < 5 { 50 } else { 200 };
                let g = if y < 5 { 60 } else { 180 };
                let b = 128;
                let pixel = (r << 24) | (g << 16) | (b << 8) | 0xFF;
                pix_mut.set_pixel_unchecked(x, y, pixel);
            }
        }
        let pix = pix_mut.into();

        // Test with 32bpp image
        let result = unsharp_masking_fast(&pix, 1, 0.5).unwrap();

        assert_eq!(result.width(), pix.width());
        assert_eq!(result.height(), pix.height());
        assert_eq!(result.depth(), PixelDepth::Bit32);
    }
}