ImageSegment save method saves masks incorrectly

At the moment, the ImageSegment class inherits it’s save() method from Image. However, the Image save function looks like the below.

def save(self, fn:PathOrStr):
    "Save the image to `fn`."
    x = image2np(self.data*255).astype(np.uint8)
    PIL.Image.fromarray(x).save(fn)

The self.data*255 section is problematic for saving a mask (ImageSegment). It assumes the image data being saved was normalized by dividing by 255 (values 0 to 1). Mask data is not normalized, and therefore should not be multiplied by 255 to denormalize it. I propose a new save() method gets created in the ImageSegment class that fixes this.

def save(self, fn:PathOrStr):
    "Save the image segment to `fn`."
    x = image2np(self.data).astype(np.uint8)
    PIL.Image.fromarray(x).save(fn)

I have created a fork of this and implemented it myself here https://github.com/mjhough/fastai/tree/img-segment-save-fix, however, I have no tests. There doesn’t seem to be an Image.save() test and I am not familiar with Python tests. Is there a way I should write this test? And where should it go?

Thanks.

1 Like

You can go ahead and suggest a PR with your change, it seems reasonable. Testing this method is a bit tricky, and as you pointed out, Image.save isn’t tested either.

1 Like

Thanks. Done.

1 Like