kornelski / imgref

A trivial Rust struct for interchange of pixel buffers with width, height & stride
https://lib.rs/crates/imgref
Apache License 2.0
59 stars 6 forks source link

Simple way to iterate over all pixels of an image, with their coordinates #20

Open vilcans opened 1 year ago

vilcans commented 1 year ago

I sometimes need to iterate over all pixels of an image and do some operation depending on their coordinates.

I typically want to do this mutably, which I can do like this:

    for (y, row) in image.rows_mut().enumerate() {
        for (x, pixel) in row.iter_mut().enumerate() {
            *pixel = shade_pixel(x, y);
        }
    }

But this requires a nested loop and hence an additional level of indentation, and a bit too much code for my taste. Wouldn't it be neat with an iterator that yields (x, y, pixel) instead, that could be used like this:

    for (x, y, pixel) in image.enumerate_pixels_mut() {
        *pixel = shade_pixel(x, y);
    }

I used the name enumerate_pixels_mut, which should have a matching enumerate_pixels for immutable iteration.

Is it a good idea, or can be done neatly with the functionality that already exists?

kornelski commented 1 year ago

Yeah, good point. There isn't anything currently in this library. Personally I use the nested two-loop version, because it optimizes best.