brendan-duncan / image

Dart Image Library for opening, manipulating, and saving various different image file formats.
MIT License
1.14k stars 255 forks source link

The function `minMax` fails to give the right values in multi-channel images #657

Open dalonsoa opened 3 weeks ago

dalonsoa commented 3 weeks ago

Problem

The function minMax can be used to find the minimum and maximum pixel values of an image. However, when applied to a multi-channel image, the values it produces are wrong if the min or maximum are in the first pixel and the image has more than one channel.

Steps to reproduce

Just create a multi-channel image with the maximum value in the first pixel, like in the example below. I would expect it to return 0 as the minimum value and 100 as the maximum one, but it returns 0 for both:

var image = Image(width: 100, height: 100);
image.setPixel(0, 0, ColorRgb8(100, 0, 0));

var mM = minMax(image);
expect(mM[0], 0);
expect(mM[1], image.getPixel(0, 0).r);  /// <- This fails. mM[1] is also 0

Solution

I think the error is just that setting first = false is in the wrong place. It is in the outer loop - the loop over pixels - and it should be in the inner loop - the loop over channels - so as soon as the first channel of the first pixel is assessed, it is no longer the first pass and the evaluation of the maximum and minimum is done properly.

I'm happy to open a PR on this, if this seems like the right solution.