Skip to content

Wrong gradient values for unsigned int data #15207

Closed

Description

@arares

Hi all,

The "numpy.gradient()" function returns wrong values for unsigned integer types. While the outputs are of np.float64 type, a part of the calculations seem to be done following the rules of the input data type (unsigned int). In our case, a negative gradient of -1 is wrapped around to a value of 255, -2 becomes 254, and so forth. The resulting gradient values can be non-integer because of some averaging taking place during the calculations.

I think the input data should first be cast to np.float64 and only then calculate the gradient.
It is useless to get correct digits after the comma, yet get huge errors before the comma.
Below you can find the code that highlights the erroneous behavior.

Best regards,

Andrei

Reproducing code example:

import numpy as np
a = np.array([[1, 1, 1], [2, 0, 1], [1, 1, 1]], dtype=np.uint8)
a  # Result:
# array([[1, 1, 1],
#        [2, 0, 1],
#        [1, 1, 1]], dtype=uint8)
dy, dx = np.gradient(a)
dy.dtype  # Result:
# dtype('float64')
dx.dtype  # Result:
# dtype('float64')
dy  # Result:
# array([[  1., 255.,   0.],
#        [  0.,   0.,   0.],
#        [255.,   1.,   0.]])
dx  # Result:
# array([[  0. ,   0. ,   0. ],
#        [254. , 127.5,   1. ],
#        [  0. ,   0. ,   0. ]])

Numpy/Python version information:

1.17.4 3.7.5 (default, Nov 7 2019, 10:50:52)
[GCC 8.3.0]

Activity

  1. WarrenWeckesser commented on Dec 31, 2019

    @WarrenWeckesser
    Member

    @arares, thanks for reporting the issue.

    The problem still exists in the development branch:

    In [1]: import numpy as np                                                      
    
    In [2]: x = np.array([5, 5, 4, 3, 2, 1, 1, 1], dtype=np.uint8)                  
    
    In [3]: np.gradient(x)                                                          
    Out[3]: array([  0. , 127.5, 127. , 127. , 127. , 127.5,   0. ,   0. ])
    
    In [4]: np.__version__                                                          
    Out[4]: '1.19.0.dev0+63ef78b'
    
  2. WarrenWeckesser commented on Dec 31, 2019

    @WarrenWeckesser
    Member

    Another broken case:

    In [62]: y = np.array([2.0, 3.0])
    
    In [63]: x = np.array([-10, 127], dtype=np.int8)
    
    In [64]: np.gradient(y, x)   # Incorrect.
    Out[64]: array([-0.00840336, -0.00840336])
    
    In [65]: np.gradient(y, x.astype(float))   # This gives the expected result.
    Out[65]: array([0.00729927, 0.00729927])
    
  3. added this to the 1.19.0 release milestone on Jan 2, 2020
  4. added a commit that references this issue on Jan 5, 2020
    c1ac694
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions