image-rs / image

Encoding and decoding images in Rust
Apache License 2.0
4.87k stars 600 forks source link

`DynamicImage::crop()` is slow because `to_image()` is slow #2295

Open Shnatsel opened 1 month ago

Shnatsel commented 1 month ago

In v0.25.2, the crop operation is implemented as:

https://github.com/image-rs/image/blob/e176cd414ac6cc73909ff162e5d0b677f9d4fb08/src/dynimage.rs#L422

which obtains a view into an image, and then calls to_image() on it to turn it into a new image buffer. And to_image() shuffles pixels one by one in a purely scalar fashion and with bounds checks on every pixel:

https://github.com/image-rs/image/blob/e176cd414ac6cc73909ff162e5d0b677f9d4fb08/src/image.rs#L1131-L1136

A much better way would be iterating over the rows, and copying over entire rows with slice::copy_from_slice(). That would both leverage vector instructions and reduce the amount of bounds checks from n^2 to n.

jamninetyfive commented 2 weeks ago

same here. do a PR?