image-rs / imageproc

Image processing operations
MIT License
755 stars 148 forks source link

Add in-place map functions #466

Closed naisuuuu closed 2 years ago

naisuuuu commented 3 years ago

It would be nice to have an option to run the map::map_... functions in-place.

I'd be happy to implement those, before I go ahead and do it please let me know if this approach would be appropriate (based on map_colors):

/// Applies `f` to the color of each pixel in the input image in place.
///
/// # Examples
/// ```
/// # extern crate image;
/// # #[macro_use]
/// # extern crate imageproc;
/// # fn main() {
/// use image::Luma;
/// use imageproc::map::map_colors_mut;
///
/// let mut image = gray_image!(
///     1, 2;
///     3, 4);
///
/// let want = gray_image!(
///     2, 4;
///     6, 8);
///
/// map_colors_mut(&mut image, |p| { Luma([2 * p[0]])});
///
/// assert_pixels_eq!(
///     image,
///     want);
/// # }
/// ```
pub fn map_colors_mut<I, P, F>(image: &mut I, f: F)
where
    I: GenericImage<Pixel = P>,
    P: Pixel,
    F: Fn(P) -> P,
{
    let (width, height) = image.dimensions();

    for y in 0..height {
        for x in 0..width {
            unsafe {
                let pix = image.unsafe_get_pixel(x, y);
                image.unsafe_put_pixel(x, y, f(pix));
            }
        }
    }
}
theotherphil commented 3 years ago

This would be.a useful addition, thanks.