imgref icon indicating copy to clipboard operation
imgref copied to clipboard

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

Open vilcans opened this issue 2 years ago • 1 comments

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?

vilcans avatar May 15 '23 09:05 vilcans

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

kornelski avatar May 15 '23 10:05 kornelski