deconvolution 0.2.1

Rust image deconvolution and restoration 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
//! Basic analytic PSF generators.
//!
//! Use this module for common 2D and 3D kernels such as [`gaussian2d`],
//! [`motion_linear`], and [`disk`].

use ndarray::{Array2, Array3};

use crate::{Error, Kernel2D, Kernel3D, Result};

/// Build a 2D impulse PSF with one sample at the center.
///
/// `dims` is `(height, width)`.
///
/// # Errors
///
/// Returns an error when either dimension is `0`.
pub fn delta2d(dims: (usize, usize)) -> Result<Kernel2D> {
    let (height, width) = dims;
    if height == 0 || width == 0 {
        return Err(Error::InvalidParameter);
    }

    let mut kernel = Array2::zeros((height, width));
    kernel[[height / 2, width / 2]] = 1.0;
    Kernel2D::new(kernel)
}

/// Build a 3D impulse PSF with one sample at the center.
///
/// `dims` is `(depth, height, width)`.
///
/// # Errors
///
/// Returns an error when any dimension is `0`.
pub fn delta3d(dims: (usize, usize, usize)) -> Result<Kernel3D> {
    let (depth, height, width) = dims;
    if depth == 0 || height == 0 || width == 0 {
        return Err(Error::InvalidParameter);
    }

    let mut kernel = Array3::zeros((depth, height, width));
    kernel[[depth / 2, height / 2, width / 2]] = 1.0;
    Kernel3D::new(kernel)
}

/// Build a normalized 2D Gaussian PSF.
///
/// `dims` is `(height, width)` and `sigma` is in pixels.
///
/// # Errors
///
/// Returns an error for empty dimensions, non-positive or non-finite `sigma`,
/// non-finite samples, or a kernel that cannot be normalized.
pub fn gaussian2d(dims: (usize, usize), sigma: f32) -> Result<Kernel2D> {
    let (height, width) = dims;
    validate_dims_2d(height, width)?;
    validate_sigma(sigma)?;

    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let sigma2 = sigma * sigma;

    let mut kernel = Array2::zeros((height, width));
    for y in 0..height {
        let dy = (y as f32) - cy;
        for x in 0..width {
            let dx = (x as f32) - cx;
            let exponent = -0.5 * (dx * dx + dy * dy) / sigma2;
            let value = exponent.exp();
            if !value.is_finite() {
                return Err(Error::NonFiniteInput);
            }
            kernel[[y, x]] = value;
        }
    }

    normalize_kernel2d(kernel)
}

/// Build a normalized 3D Gaussian PSF.
///
/// `dims` is `(depth, height, width)` and `sigma` is in pixels.
///
/// # Errors
///
/// Returns an error for empty dimensions, non-positive or non-finite `sigma`,
/// non-finite samples, or a kernel that cannot be normalized.
pub fn gaussian3d(dims: (usize, usize, usize), sigma: f32) -> Result<Kernel3D> {
    let (depth, height, width) = dims;
    validate_dims_3d(depth, height, width)?;
    validate_sigma(sigma)?;

    let cd = center_coordinate(depth)?;
    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let sigma2 = sigma * sigma;

    let mut kernel = Array3::zeros((depth, height, width));
    for d in 0..depth {
        let dd = (d as f32) - cd;
        for y in 0..height {
            let dy = (y as f32) - cy;
            for x in 0..width {
                let dx = (x as f32) - cx;
                let exponent = -0.5 * (dx * dx + dy * dy + dd * dd) / sigma2;
                let value = exponent.exp();
                if !value.is_finite() {
                    return Err(Error::NonFiniteInput);
                }
                kernel[[d, y, x]] = value;
            }
        }
    }

    normalize_kernel3d(kernel)
}

/// Build a normalized linear-motion PSF.
///
/// `length` is in pixels and `angle_deg` is measured counterclockwise in degrees.
/// The output side length is the next odd size that can contain the line.
///
/// # Errors
///
/// Returns an error for non-positive length, non-finite parameters, non-finite
/// samples, or a kernel that cannot be normalized.
pub fn motion_linear(length: f32, angle_deg: f32) -> Result<Kernel2D> {
    if !length.is_finite() || length <= 0.0 {
        return Err(Error::InvalidParameter);
    }
    if !angle_deg.is_finite() {
        return Err(Error::InvalidParameter);
    }

    let side = odd_size_from_length(length)?;
    let center = center_coordinate(side)?;
    let angle_rad = angle_deg.to_radians();
    let dir_x = angle_rad.cos();
    let dir_y = angle_rad.sin();
    let half = (length - 1.0).max(0.0) * 0.5;
    let start_x = -half * dir_x;
    let start_y = -half * dir_y;
    let end_x = half * dir_x;
    let end_y = half * dir_y;

    let mut kernel = Array2::zeros((side, side));
    for y in 0..side {
        let py = (y as f32) - center;
        for x in 0..side {
            let px = (x as f32) - center;
            let distance = point_segment_distance(px, py, start_x, start_y, end_x, end_y);
            let value = (1.0 - distance).max(0.0);
            if !value.is_finite() {
                return Err(Error::NonFiniteInput);
            }
            kernel[[y, x]] = value;
        }
    }

    if kernel.iter().all(|value| *value <= 0.0) {
        kernel[[side / 2, side / 2]] = 1.0;
    }

    normalize_kernel2d(kernel)
}

/// Build a normalized circular disk PSF.
///
/// `radius` is in pixels.
///
/// # Errors
///
/// Returns an error for non-positive or non-finite `radius`, non-finite samples,
/// or a kernel that cannot be normalized.
pub fn disk(radius: f32) -> Result<Kernel2D> {
    pillbox(radius)
}

/// Build a normalized binary pillbox PSF.
///
/// `radius` is in pixels and the output side length is odd.
///
/// # Errors
///
/// Returns an error for non-positive or non-finite `radius`, non-finite samples,
/// or a kernel that cannot be normalized.
pub fn pillbox(radius: f32) -> Result<Kernel2D> {
    let kernel = binary_disk(radius)?;
    normalize_kernel2d(kernel)
}

/// Build a normalized antialiased defocus disk PSF.
///
/// `radius` is in pixels and each output pixel is sampled on an `8 x 8` grid.
///
/// # Errors
///
/// Returns an error for non-positive or non-finite `radius`, non-finite samples,
/// or a kernel that cannot be normalized.
pub fn defocus(radius: f32) -> Result<Kernel2D> {
    validate_radius(radius)?;
    let side = odd_size_from_radius(radius)?;
    let center = center_coordinate(side)?;
    let samples = 8_usize;
    let sample_scale = samples as f32;
    let mut kernel = Array2::zeros((side, side));

    for y in 0..side {
        for x in 0..side {
            let mut inside = 0_usize;
            for sy in 0..samples {
                let oy = ((sy as f32) + 0.5) / sample_scale - 0.5;
                let py = (y as f32) - center + oy;
                for sx in 0..samples {
                    let ox = ((sx as f32) + 0.5) / sample_scale - 0.5;
                    let px = (x as f32) - center + ox;
                    if px * px + py * py <= radius * radius {
                        inside += 1;
                    }
                }
            }
            kernel[[y, x]] = (inside as f32) / ((samples * samples) as f32);
        }
    }

    if kernel.iter().all(|value| *value <= 0.0) {
        kernel[[side / 2, side / 2]] = 1.0;
    }

    normalize_kernel2d(kernel)
}

/// Build a normalized 2D box PSF.
///
/// `dims` is `(height, width)`.
///
/// # Errors
///
/// Returns an error when either dimension is `0`.
pub fn box2d(dims: (usize, usize)) -> Result<Kernel2D> {
    let (height, width) = dims;
    validate_dims_2d(height, width)?;
    let kernel = Array2::ones((height, width));
    normalize_kernel2d(kernel)
}

/// Build a normalized 3D box PSF.
///
/// `dims` is `(depth, height, width)`.
///
/// # Errors
///
/// Returns an error when any dimension is `0`.
pub fn box3d(dims: (usize, usize, usize)) -> Result<Kernel3D> {
    let (depth, height, width) = dims;
    validate_dims_3d(depth, height, width)?;
    let kernel = Array3::ones((depth, height, width));
    normalize_kernel3d(kernel)
}

/// Build a normalized anisotropic Gaussian PSF.
///
/// `dims` is `(height, width)`, sigmas are in pixels, and `angle_deg` is the
/// major-axis angle in degrees.
///
/// # Errors
///
/// Returns an error for empty dimensions, non-positive or non-finite sigmas,
/// non-finite angles, non-finite samples, or a kernel that cannot be normalized.
pub fn oriented_gaussian(
    dims: (usize, usize),
    sigma_major: f32,
    sigma_minor: f32,
    angle_deg: f32,
) -> Result<Kernel2D> {
    let (height, width) = dims;
    validate_dims_2d(height, width)?;
    validate_sigma(sigma_major)?;
    validate_sigma(sigma_minor)?;
    if !angle_deg.is_finite() {
        return Err(Error::InvalidParameter);
    }

    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let theta = angle_deg.to_radians();
    let cos_t = theta.cos();
    let sin_t = theta.sin();
    let major2 = sigma_major * sigma_major;
    let minor2 = sigma_minor * sigma_minor;

    let mut kernel = Array2::zeros((height, width));
    for y in 0..height {
        let dy = (y as f32) - cy;
        for x in 0..width {
            let dx = (x as f32) - cx;
            let xr = cos_t * dx + sin_t * dy;
            let yr = -sin_t * dx + cos_t * dy;
            let exponent = -0.5 * (xr * xr / major2 + yr * yr / minor2);
            let value = exponent.exp();
            if !value.is_finite() {
                return Err(Error::NonFiniteInput);
            }
            kernel[[y, x]] = value;
        }
    }

    normalize_kernel2d(kernel)
}

fn normalize_kernel2d(kernel: Array2<f32>) -> Result<Kernel2D> {
    let mut kernel = Kernel2D::new(kernel)?;
    kernel.normalize()?;
    Ok(kernel)
}

fn normalize_kernel3d(kernel: Array3<f32>) -> Result<Kernel3D> {
    let mut kernel = Kernel3D::new(kernel)?;
    kernel.normalize()?;
    Ok(kernel)
}

fn binary_disk(radius: f32) -> Result<Array2<f32>> {
    validate_radius(radius)?;
    let side = odd_size_from_radius(radius)?;
    let center = center_coordinate(side)?;
    let radius2 = radius * radius;

    let mut kernel = Array2::zeros((side, side));
    for y in 0..side {
        let dy = (y as f32) - center;
        for x in 0..side {
            let dx = (x as f32) - center;
            if dx * dx + dy * dy <= radius2 {
                kernel[[y, x]] = 1.0;
            }
        }
    }

    if kernel.iter().all(|value| *value <= 0.0) {
        kernel[[side / 2, side / 2]] = 1.0;
    }

    Ok(kernel)
}

fn validate_dims_2d(height: usize, width: usize) -> Result<()> {
    if height == 0 || width == 0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_dims_3d(depth: usize, height: usize, width: usize) -> Result<()> {
    if depth == 0 || height == 0 || width == 0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_sigma(sigma: f32) -> Result<()> {
    if !sigma.is_finite() || sigma <= 0.0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_radius(radius: f32) -> Result<()> {
    if !radius.is_finite() || radius <= 0.0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn odd_size_from_length(length: f32) -> Result<usize> {
    let ceil_len = length.ceil();
    if !ceil_len.is_finite() || ceil_len <= 0.0 {
        return Err(Error::InvalidParameter);
    }
    let base = ceil_len as usize;
    odd_size(base)
}

fn odd_size_from_radius(radius: f32) -> Result<usize> {
    let ceil_radius = radius.ceil();
    if !ceil_radius.is_finite() || ceil_radius <= 0.0 {
        return Err(Error::InvalidParameter);
    }
    let r = ceil_radius as usize;
    let diameter = r
        .checked_mul(2)
        .and_then(|value| value.checked_add(1))
        .ok_or(Error::InvalidParameter)?;
    odd_size(diameter)
}

fn odd_size(value: usize) -> Result<usize> {
    if value == 0 {
        return Err(Error::InvalidParameter);
    }
    if value % 2 == 1 {
        return Ok(value);
    }
    value.checked_add(1).ok_or(Error::InvalidParameter)
}

fn center_coordinate(length: usize) -> Result<f32> {
    if length == 0 {
        return Err(Error::InvalidParameter);
    }
    Ok((length as f32 - 1.0) * 0.5)
}

fn point_segment_distance(px: f32, py: f32, sx0: f32, sy0: f32, sx1: f32, sy1: f32) -> f32 {
    let vx = sx1 - sx0;
    let vy = sy1 - sy0;
    let wx = px - sx0;
    let wy = py - sy0;
    let vv = vx * vx + vy * vy;
    if vv <= f32::EPSILON {
        return ((px - sx0) * (px - sx0) + (py - sy0) * (py - sy0)).sqrt();
    }

    let t = ((wx * vx + wy * vy) / vv).clamp(0.0, 1.0);
    let dx = px - (sx0 + t * vx);
    let dy = py - (sy0 + t * vy);
    (dx * dx + dy * dy).sqrt()
}