Skip to content

Chaining issue: X -> Grey -> Resize -> Gaussian !!->!! Median  #1529

Open

Description

@sschnug

Hi, i'm using skimage for the first time (one day of experience; it looks like a very very interesting library) for implementing a perceptual hash algorithm on images.

Playing around with my prototype-implementation (not that complex), i observed the following error:

    self.img = skimage.filters.median(self.img, self.preprocess_median_filter_ne
ighborhood)
  File "C:\Miniconda_v2\lib\site-packages\skimage\filters\rank\generic.py", line
 422, in median
    shift_x=shift_x, shift_y=shift_y)
  File "C:\Miniconda_v2\lib\site-packages\skimage\filters\rank\generic.py", line
 77, in _apply_scalar_per_pixel
    out_dtype)
  File "C:\Miniconda_v2\lib\site-packages\skimage\filters\rank\generic.py", line
 36, in _handle_input
    image = img_as_ubyte(image)
  File "C:\Miniconda_v2\lib\site-packages\skimage\util\dtype.py", line 364, in i
mg_as_ubyte
    return convert(image, np.uint8, force_copy)
  File "C:\Miniconda_v2\lib\site-packages\skimage\util\dtype.py", line 195, in c
onvert
    raise ValueError("Images of type float must be between -1 and 1.")
ValueError: Images of type float must be between -1 and 1.

I found the open issue #1334, but this didn't help and i think that my chain may be even simpler.

Let's look at the chaining-sequence i implemented:

img = skimage.data.load("x.jpg")
img = skimage.color.rgb2grey(img)
img = skimage.transform.resize(img, (512, 384)) # will be downscaled
img = skimage.filters.gaussian_filter(img, 1.0)
img = skimage.filters.median(img, skimage.morphology.disk(1))
# CRASHES HERE
# hist_equalization + a lot of statistics stuff follows -> will work for some images

This is working for 8 out of 9 manually tested images. One of these (not different in style; all img's are screenshots from video-media or transformed versions of these) will crash with the error posted above!

skimage print's out the following warning during the call to "filter.median" (printed once during my program; i assume this is printed at the first call to filter.median):

C:\Miniconda_v2\lib\site-packages\skimage\util\dtype.py:111: UserWarning: Possib
le precision loss when converting from float64 to uint8
  "%s to %s" % (dtypeobj_in, dtypeobj))
  • Any ideas for handling this error?
  • Is the chaining of a gaussian and a median-filter not valid?

Thanks!

  • Sascha

Edit 1: I just found #1419 "median only for integer-type images" -> I need to have a look at this, but skimage will accept my non-integer image when i call filter.median!

Activity

  1. stefanv commented on May 26, 2015

    @stefanv
    Member

    @sschnug Could you please attach an example image for which the above fails? Thanks!

  2. sschnug commented on May 27, 2015

    @sschnug
    Author

    I constructed a minimal example (5 lines) which crashes for me.
    I'm afraid, that i can't attach my test-image because of shady legal-stuff, but i hope, that a link should be enough for now (maybe i will test some "standard images" later!)

    Code

    from skimage import data, transform, color, filters, morphology
    img = data.load("test.jpg") # replace with real image
    img = color.rgb2grey(img)
    img = transform.resize(img, (512,384))
    img = filters.gaussian_filter(img, 1.0)
    img = filters.median(img, morphology.disk(1))

    Image link

    image

    imagemagick's identify (to check for corruption)

    > identify test.jpg
    test.jpg JPEG 1200x900 1200x900+0+0 8-bit sRGB 301KB 0.000u 0:00.010
    

    Installed software

    Python 2.7.9 |Continuum Analytics, Inc.| (default, Dec 18 2014, 16:57:52) [MSC v.1500 64 bit (AMD64)] on win32
    
    > conda list
    conda                     3.11.0                   py27_0
    conda-env                 2.1.4                    py27_0
    conda311fix               1.0                           0
    numpy                     1.9.2                    py27_0
    pillow                    2.7.0                    py27_0
    pip                       6.1.1                    py27_0
    python                    2.7.9                         1
    scikit-image              0.11.3               np19py27_0
    scikit-learn              0.16.1               np19py27_0
    scipy                     0.15.1               np19py27_0
    

    Let me know, if you need more!

    • Sascha
  3. stefanv commented on May 27, 2015

    @stefanv
    Member
  4. sschnug commented on May 27, 2015

    @sschnug
    Author

    That was some task you gave me :-)
    And i don't understand, why my linked image is not failing for you.
    Are you using some newer development-version?

    Well, the following code fails for me with Win7 & Linux (inside VirtualBox).
    It was found by iterating random-seeds until some error occurs -> 545 iterations were needed!

    from skimage import data, transform, color, filters, morphology
    import numpy as np
    
    def process(img):
        img = color.rgb2grey(img)
        img = transform.resize(img, (512,384))
        img = filters.gaussian_filter(img, 1.0)
        img = filters.median(img, morphology.disk(1))
    
    np.random.seed(545)
    img = np.random.beta(
                1.0 - np.random.random(), 1.0 - np.random.random(),
                size=(np.random.randint(low=1, high=1921, size=2)))
    
    process(img)

    Assumptions made:

    • arrays with shape (x,y,3) and values within range [0,1] are always valid images (dimensions bounded by [1,1920])

    I hope that this random-process is a valid one for producing images in scikit-image!

    • Sascha
  5. JDWarner commented on May 28, 2015

    @JDWarner
    Contributor

    I do get the same traceback on master. From debugging inspection, the root cause is clear:

    ipdb> image.min()
    0.91935977496981636
    ipdb> image.max()
    1.0000000000000004

    The issue is rounding error in floating point calculations resulting in a maximum value that is slightly out of range (in this case, it is 4e-15 greater than 1).

    Investigating further, the call producing this is gaussian_filter. The behavior appears to resolve by setting mode='reflect' (the default mode is 'nearest'), but I'm unsure if this is a general solution. In any event, floating point errors are going to be unavoidable in complicated, compound workflows.

  6. sschnug commented on May 28, 2015

    @sschnug
    Author

    I will have a look at the modes you mentioned, but for now, i have some follow-up questions on "In any event, floating point errors are going to be unavoidable in complicated, compound workflows.":

    • Is it desired to let the program crash, if rounding-errors in internal filters are happening? (my opinion: this error above is not a rare event by any means!)?
    • Is the user responsible to ensure the [-1,1] bounds in images or should these filters offer a "trimming"-option to shift crossing-values back to [-1,1]?
    • Certain operations are losing precision and scikit-image will issue a warning about this: isn't this something which could be possible too in this case (with some trimming like mentioned above?)

    I know, that these are difficult design-questions and that floating-point values are complex.

    Personal opinion: I'm someone without much experience in image-processing, but i think, that my example is on the lower-end of usage-complexity and maybe something needs to be changed in the code.

    • Sascha
  7. jni commented on May 28, 2015

    @jni
    Member

    I'm with @sschnug. We explicitly define what we consider "valid" images and we do this explicitly so that functions can be chained, exactly as @sschnug did. There's a few design decisions to make but I think "floating points are hard, let's do nothing" is not an option.

    Possible options include:

    • having all functions clip output to [-1, 1] when the input was a valid image. (As I've mentioned before, when the input is not a "valid" image, we should turn off clipping.)
    • having our conversion functions img_as_float clip to valid input rather than crashing and burning. (with or without a warning.)
  8. JDWarner commented on May 28, 2015

    @JDWarner
    Contributor

    I strongly favor the first option, but it isn't a simple one. The second requires a fuzzy range around the true, valid range which is magically assumed to be incorrect and then gets clipped. This may not be the case, thus our magic always would have the potential to silently work against the user.

    A @clip_if_input_valid decorator would be ideal. However, it could only be applied to functions where it can be proven that for valid inputs, valid output will be obtained every time. And our "anything in, anything out" style makes this a challenge, as the output dtype may not match the input dtype. Here are a couple other issues off the top of my head:

    • Histogram/contrast adjustment of a valid uint8 image. Valid input means the decorator thinks it should clip, but the output should be floating point, retaining the input's range, to enable maximum fidelity in a workflow. You don't want to round this until the end. It incorrectly gets clipped to 1.0.
    • Valid image passed to util.random_noise with clip=False set deliberately, so the random noise input retains its full range. Instead, the decorator clips it.

    Also worth noting the solution can't be overly complicated or burdensome, as this would be yet another thing every new contributor/maintainer needs to learn and understand.

  9. stefanv commented on May 28, 2015

    @stefanv
    Member

    How about a simple rule that can be applied consistently: clip to the maximum input value and document it as such.

  10. JDWarner commented on May 28, 2015

    @JDWarner
    Contributor

    Won't work when dealing with higher order interpolation which can over/undershoot, by definition breaks contrast adjustments, also problematic if the output dtype is different from the input dtype (e.g., is that 50% of the range [-1, 1] or 50% of the range [0, 1]?).

    Seems like a simple issue, but this is very non-trivial.

  11. stefanv commented on May 28, 2015

    @stefanv
    Member

    If you change the dtype, you change the range in which you function, so if the max value was 90% of the old range, then clip to 90% of the new range. If interpolation overshoots, we can have a clip=True flag, on by default.

  12. stefanv commented on May 28, 2015

    @stefanv
    Member

    Actually, I believe it's called preserve_range, according to previous PRs.

  13. jni commented on May 29, 2015

    @jni
    Member

    @stefanv yes, preserve_range, so @JDWarner if you contrast-adjust a uint8 image, you convert to float, by definition it gets cast to [0, 1] unless preserve_range is set to True. The decorator can be aware of this keyword.

    At any rate, I'm not sure it can catch all use cases. ie maybe a decorator is not the right approach compared to a function-specific fix.

  14. vighneshbirodkar commented on May 29, 2015

    @vighneshbirodkar
    Contributor

    How about we change img_as_float such that, if the input is a floating point image, all values between 1 and 1 + epsilon will be rounded to 1 and raise an error when anything is above 1 + epsilon. Anyone who expects a floating point image can use that as a validator.

  15. JDWarner commented on May 29, 2015

    @JDWarner
    Contributor

    @vighneshbirodkar I would be fine with that approach, except that floating point math compounds this error such that every additional operation increases the combined error in the result. We don't track the number of individual operations in each function, so epsilon won't save us here.

    E.g., the result of this call to gaussian_filter is high by 4e-15 while np.finfo(float).eps is 2.2e-16. It's an order of magnitude worse than epsilon.

  16. vighneshbirodkar commented on May 29, 2015

    @vighneshbirodkar
    Contributor

    @JDWarner By epsilon I did not mean the minimum possible precision. It's only a small number, like 0.000001 by default.

  17. stefanv commented on May 29, 2015

    @stefanv
    Member
  18. jni commented on May 31, 2015

    @jni
    Member

    @stefanv what about clipping at 1 by default with a warning? I think this is preferable to the current behaviour of crashing and burning.

    (The warning should include the min/max values of the array so that the user knows when it is safe to ignore.)

  19. stefanv commented on May 31, 2015

    @stefanv
    Member

    @jni Clipping + preserve_range sounds OK to me.

  20. added this to the 0.14 milestone on Dec 24, 2016
  21. modified the milestones: 0.14, 0.15 on May 22, 2018
  22. modified the milestones: 0.15, 0.16 on Apr 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions