Skip to content

interpolation: mode='constant' edge behaviour #1514

Closed

Description

@grlee77

The interpolation functions within skimage/_shared/interpolation.pxd treat the mode='constant' case differently than the NI_GeometricTransform function defined in scipy/ndimage/src/ni_interpolation.c that gets called by functions such as scipy.ndimage.map_coordinates.

Specifically, any coordinates outside the range of the image will be assigned a value exactly equal to cval in the ndimage implementation. For the skimage case, however, the values are interpolated between cval and the edge pixels. I am not sure this is necessarily a bug, but rather an inconsistency with scipy and I was not sure if this is intended behaviour or not.

It is fairly simple to get the scipy-like behaviour with slight modifications. e.g. in bilinear_interpolation, the following can be placed before the bilinear interpolation:

if (minr < 0) or (maxr >= rows) or (minc < 0) or (maxc >= cols):
    return cval
else:
    ...

If you agree that this is a bug, I can make a pull request with solutions similar to the above

Activity

  1. stefanv commented on May 16, 2015

    @stefanv
    Member
  2. grlee77 commented on May 16, 2015

    @grlee77
    ContributorAuthor

    @stefanv: I am in Cincinnati

  3. grlee77 commented on May 19, 2015

    @grlee77
    ContributorAuthor

    @stefanv, @ahojnnes
    Here are a couple of concrete examples.

    In the first example below, when order=0, 1, or 3 rescale will eventually call the _warp_fast function from skimage.transform._warps_cy.pyx which in turn calls functions from _shared/interpolation.pyx
    The order 2, 4, 5 cases, call scipy.ndimage.map_coordinates instead.

    import numpy as np
    from skimage.transform import rescale
    import matplotlib.pyplot as plt
    f, ax = plt.subplots(1, 7)
    img = np.ones((7, 7))
    img[2:5, 2:5] = 0.0
    scale_factor = 2.0
    ax[0].imshow(img)
    # ax[0].set_axis_off()
    ax[0].set_title('original')
    for order in range(7):
        ax[order+1].imshow(rescale(img, scale_factor, order=order, mode='constant',
                                   preserve_range=False),
                           vmin=0, vmax=1)
        # ax[order+1].set_axis_off()
        ax[order+1].set_title('order={}'.format(order))

    interp_example2
    Here the first and last coordinates end up outside the original range and are set to cval for the orders that call scipy, but are interpolated using a pixel value of cval in the skimage cases.

    Also, strangely, if the image is all ones, the interpolation is no longer apparent at the edges for order = 1 or 3. See below:

    f, ax = plt.subplots(1, 6)
    img = np.ones((4, 4))
    img[3:5, 3:5] = 0.0
    scale_factor = 2.0
    for order in range(6):
        ax[order].imshow(rescale(img, scale_factor, order=order, mode='constant'),
                         vmin=0, vmax=1)
        ax[order].set_axis_off()
        ax[order].set_title('order={}'.format(order))

    interp_example

    In this case, the coordinates that are getting passed to map_coordinates along each axis are:
    [-0.25, 0.25, 0.75, 1.25, 1.75, 2.25, 2.75, 3.25]
    -0.25 and 3.25 are outside the original range of [0, 1, 2, 3], and get mapped to cval=0

  4. stefanv commented on May 19, 2015

    @stefanv
    Member

    @rgommers @jaimefrio As reported here, there is an inconsistency with scipy w.r.t interpolation around image edges. When we hit a coordinate outside of the image and mode is set to 'constant' with cval 0, then we simply take that point to be zero and complete the interpolation. Scipy, on the other hand, does not even try to complete the interpolation, but immediately returns cval. Should this be considered a bug or a feature on the scipy end? And if a feature, would it be feasible to also add a mode that does the same thing scikit-image currently does?

  5. rgommers commented on May 21, 2015

    @rgommers

    @stefanv the ndimage.map_coordinates behavior is what I'd expect (maybe because I'm used to it). Also, I'm not even sure what "complete the interpolation" even means. If you've filled the actual point you're interpolating to with cval, then any order interpolation still should yield cval as the final value. The figure just above looks like cval is completely ignored, but I guess I'm missing something.

    Maybe you can make a concrete proposal for the string value to add to mode and what it should do?

  6. stefanv commented on May 22, 2015

    @stefanv
    Member

    Perhaps this sketch will help to identify the issue:

    skimage_interpolation

    Red == known values, black == cval

  7. jni commented on May 22, 2015

    @jni
    Member

    @stefanv @rgommers an alternate example: image = np.ones((2, 2)). A pixel is not a little square, but rather a point sample at integer coordinates. So @stefanv argues that cval=0 means that the samples extending the grid e.g. at (-1, 0) and (-1, 1), are taken to be equal to 0, but a sample at (-0.5, 0.5) needs to be interpolated. Using a linear interpolation, that sample's value would be equal to 0.5: the average of 1 at (0, 0), 1 at (0, 1), 0 at (-1, 0) and 0 at (-1, 1).

    However, map_coordinates returns cval in this case, regardless of the order of the interpolation.

    It's unclear to me what the "correct" behaviour should be, but smoothness arguments would favour @stefanv's expectation...

  8. grlee77 commented on May 22, 2015

    @grlee77
    ContributorAuthor

    @stefanv, @jni, @rgommers
    I thought about this some more and I think using cval in the interpolation is technically correct for warping to coordinates outside the image range. As a second point of agreement, I get the same result as in scikit.image's linear interpolation when using OpenCV's remap function:

    import numpy as np
    import cv2
    img = np.ones((7, 7))
    img[2:5, 2:5] = 0.0
    scale_factor = 2.0
    output_shape = scale_factor * np.asarray(img.shape)
    # destination coordinates
    axis_slices = tuple([slice(d) for d in output_shape])
    nd_coords = np.mgrid[axis_slices]
    map2_coord_arrays = [1/scale_factor * (nd_coords[i] + 0.5) - 0.5
                         for i, d in enumerate(output_shape)]
    cv2_map = np.concatenate((map2_coord_arrays[0][..., np.newaxis],
                              map2_coord_arrays[1][..., np.newaxis]), axis=2)
    img_cv2_remap = cv2.remap(img,
                              map1=cv2_map.astype(np.float32),
                              map2=None,
                              interpolation=cv2.INTER_LINEAR,
                              borderMode=cv2.BORDER_CONSTANT,
                              borderValue=0.)
    f, ax = plt.subplots(1, 2)
    ax[0].imshow(img)
    ax[0].set_title('original')
    ax[1].imshow(img_cv2_remap)
    ax[1].set_title('opencv remap')

    opencv_result

    Perhaps a simple solution to avoid potentially confusing edge results like the above during simple rescalings would be to change the default mode for resize and rescale to reflect. In that mode, regardless which underlying interpolation is used, the results should be the same.
    The result for 'reflect' intuitively looks more like one would expect for upscaling the source by two:
    opencv_reflect

    As another OpenCV comparison:
    OpenCV has a resize() function, which does not have an option to specify the border behavior. However, in practice it seems that for most interpolation types, any coordinates that fall outside the image range get clipped to the source coordinate range (e.g. see here (where sx is the floor of the destination x coordinate and gets clipped to [0, width -1] for most interpolation types)
    https://github.com/Itseez/opencv/blob/8e392251baf353c7bbcf23d3c96a9f18dde3230d/modules/imgproc/src/imgwarp.cpp#L3392-3405
    In practice I think that should be equivalent to mode='reflect'

  9. JDWarner commented on Jun 8, 2015

    @JDWarner
    Contributor

    I agree with @grlee77 - I would use 'reflect' here and reasonably expect a simple rescaling algorithm to default to that behavior.

  10. grlee77 commented on Aug 14, 2015

    @grlee77
    ContributorAuthor

    @JDWarner, @ahojnnes : I would like to put a PR to use mode symmetric (the np.pad equivalent name for reflect to take into account the naming conventions decided on in #1583) as the default for resize. This should also fix the specific example shown in #1585 (although due to a bug in ndimage the mode wrap could still give an inconsistent result between 2D and 3D cases).

    The only down side I see to the change is that this will change results for any users that did not previously explicitly specify the mode argument. Is there a way to raise a deprecation for the default 'constant' only in the case that the user didn't explicitly pass mode='constant'? (i.e. can we detect if mode was passed as an argument vs. just getting set to the default)

  11. JDWarner commented on Aug 14, 2015

    @JDWarner
    Contributor

    Generally, we deprecate improvements for two minor point releases. However,
    we immediately fix and document bugs which require API changes.

    Looking back at #1585, I'm inclined to consider this a bug and recommend a
    breaking fix.

    On Friday, August 14, 2015, Gregory R. Lee [email protected] wrote:

    @JDWarner https://github.com/JDWarner, @ahojnnes
    https://github.com/ahojnnes : I would like to put a PR to use mode
    symmetric (the np.pad equivalent name for reflect to take into account
    the naming conventions decided on in #1583
    #1583) as the default
    for resize. This should also fix the specific example shown in #1585
    #1585 (although due
    to a bug in ndimage the mode wrap could still give an inconsistent result
    between 2D and 3D cases).

    The only down side I see to the change is that this will change results
    for any users that did not previously explicitly specify the mode argument.
    Is there a way to raise a deprecation for the default 'constant' only in
    the case that the user didn't explicitly pass mode='constant'? (i.e. can
    we detect if mode was passed as an argument vs. just getting set to the
    default)

    —
    Reply to this email directly or view it on GitHub
    #1514 (comment)
    .

  12. ahojnnes commented on Aug 14, 2015

    @ahojnnes
    Member

    How about making it mode=None, then:

    if mode is None:
        mode = "constant" or "reflect"
        print deprecation/breaking fix warning
    

    On Fri, Aug 14, 2015 at 8:55 AM, Josh Warner [email protected]
    wrote:

    Generally, we deprecate improvements for two minor point releases. However,
    we immediately fix and document bugs which require API changes.

    Looking back at #1585, I'm inclined to consider this a bug and recommend a
    breaking fix.

    On Friday, August 14, 2015, Gregory R. Lee [email protected]
    wrote:

    @JDWarner https://github.com/JDWarner, @ahojnnes
    https://github.com/ahojnnes : I would like to put a PR to use mode
    symmetric (the np.pad equivalent name for reflect to take into account
    the naming conventions decided on in #1583
    #1583) as the default
    for resize. This should also fix the specific example shown in #1585
    #1585 (although due
    to a bug in ndimage the mode wrap could still give an inconsistent result
    between 2D and 3D cases).

    The only down side I see to the change is that this will change results
    for any users that did not previously explicitly specify the mode
    argument.
    Is there a way to raise a deprecation for the default 'constant' only in
    the case that the user didn't explicitly pass mode='constant'? (i.e. can
    we detect if mode was passed as an argument vs. just getting set to the
    default)

    —
    Reply to this email directly or view it on GitHub
    <
    #1514 (comment)

    .

    —
    Reply to this email directly or view it on GitHub
    #1514 (comment)
    .

  13. JDWarner commented on Aug 14, 2015

    @JDWarner
    Contributor

    👍 for this approach. Warn the user the default changed in 0.12, and how
    to restore the previous behavior.
    On Aug 14, 2015 11:31 AM, "Johannes Schönberger" [email protected]
    wrote:

    How about making it mode=None, then:

    if mode is None:
    mode = "constant" or "reflect"
    print deprecation/breaking fix warning
    

    On Fri, Aug 14, 2015 at 8:55 AM, Josh Warner [email protected]
    wrote:

    Generally, we deprecate improvements for two minor point releases.
    However,
    we immediately fix and document bugs which require API changes.

    Looking back at #1585, I'm inclined to consider this a bug and recommend
    a
    breaking fix.

    On Friday, August 14, 2015, Gregory R. Lee [email protected]
    wrote:

    @JDWarner https://github.com/JDWarner, @ahojnnes
    https://github.com/ahojnnes : I would like to put a PR to use mode
    symmetric (the np.pad equivalent name for reflect to take into account
    the naming conventions decided on in #1583
    #1583) as the
    default
    for resize. This should also fix the specific example shown in #1585
    #1585 (although
    due
    to a bug in ndimage the mode wrap could still give an inconsistent
    result
    between 2D and 3D cases).

    The only down side I see to the change is that this will change results
    for any users that did not previously explicitly specify the mode
    argument.
    Is there a way to raise a deprecation for the default 'constant' only
    in
    the case that the user didn't explicitly pass mode='constant'? (i.e.
    can
    we detect if mode was passed as an argument vs. just getting set to the
    default)

    —
    Reply to this email directly or view it on GitHub
    <

    #1514 (comment)

    .

    —
    Reply to this email directly or view it on GitHub
    <
    #1514 (comment)

    .

    —
    Reply to this email directly or view it on GitHub
    #1514 (comment)
    .

  14. grlee77 commented on Aug 14, 2015

    @grlee77
    ContributorAuthor

    I will take that approach. thanks

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions