| 1 |
use std::{f64::consts::PI, mem::size_of}; |
| 2 |
|
| 3 |
use v_frame::{ |
| 4 |
plane::Plane, |
| 5 |
prelude::{CastFromPrimitive, Pixel}, |
| 6 |
}; |
| 7 |
|
| 8 |
/// Estimates the amount of noise within a plane. |
| 9 |
/// Returns `None` if a reliable estimate cannot be obtained |
| 10 |
/// due to too few smooth pixels. |
| 11 |
/// |
| 12 |
/// Ranges seem to be approximately: |
| 13 |
/// |
| 14 |
/// - `0.0..0.5` = no noticeable noise |
| 15 |
/// - `0.5..1.0` = light noise, probably photon-noise-esque |
| 16 |
/// |
| 17 |
/// # Panics |
| 18 |
/// - If called with a `bit_depth` not between `8..=16` |
| 19 |
#[must_use] |
| 20 |
pub fn estimate_plane_noise<T: Pixel>(plane: &Plane<T>, bit_depth: usize) -> Option<f64> { |
| 21 |
const EDGE_THRESHOLD: u16 = 50; |
| 22 |
|
| 23 |
if size_of::<T>() == 1 { |
| 24 |
assert_eq!(bit_depth, 8); |
| 25 |
} else if size_of::<T>() == 2 { |
| 26 |
assert!(bit_depth > 8 && bit_depth <= 16); |
| 27 |
} else { |
| 28 |
unimplemented!("Bit depths greater than 16 are not currently supported"); |
| 29 |
} |
| 30 |
|
| 31 |
let width = plane.cfg.width; |
| 32 |
let height = plane.cfg.height; |
| 33 |
let stride = plane.cfg.stride; |
| 34 |
|
| 35 |
let mut accum = 0u64; |
| 36 |
let mut count = 0u64; |
| 37 |
for i in 1..(height - 1) { |
| 38 |
for j in 1..(width - 1) { |
| 39 |
// Setup a small 3x3 matrix. |
| 40 |
let center_idx = (i * stride + j) as isize; |
| 41 |
let mut mat = [[0i16; 3]; 3]; |
| 42 |
for ii in -1isize..=1isize { |
| 43 |
for jj in -1isize..=1isize { |
| 44 |
let idx = (center_idx + ii * stride as isize + jj) as usize; |
| 45 |
mat[(ii + 1) as usize][(jj + 1) as usize] = if size_of::<T>() == 1 { |
| 46 |
i16::cast_from(plane.data_origin()[idx]) |
| 47 |
} else { |
| 48 |
(u16::cast_from(plane.data_origin()[idx]) >> (bit_depth - 8usize)) as i16 |
| 49 |
}; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
// Compute sobel gradients |
| 54 |
let g_x = |
| 55 |
(mat[0][0] - mat[0][2]) + (mat[2][0] - mat[2][2]) + 2 * (mat[1][0] - mat[1][2]); |
| 56 |
let g_y = |
| 57 |
(mat[0][0] - mat[2][0]) + (mat[0][2] - mat[2][2]) + 2 * (mat[0][1] - mat[2][1]); |
| 58 |
let g_a = (g_x.abs() + g_y.abs()) as u16; |
| 59 |
// Accumulate Laplacian |
| 60 |
if g_a < EDGE_THRESHOLD { |
| 61 |
// Only count smooth pixels |
| 62 |
let v = 4 * mat[1][1] - 2 * (mat[0][1] + mat[2][1] + mat[1][0] + mat[1][2]) |
| 63 |
+ (mat[0][0] + mat[0][2] + mat[2][0] + mat[2][2]); |
| 64 |
accum += u64::from(v.unsigned_abs()); |
| 65 |
count += 1; |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
(count >= 16).then(|| accum as f64 / (6u64 * count) as f64 * (PI / 2f64).sqrt()) |
| 71 |
} |