4
votes

I have two 3D numpy arrays and I would like to find out the difference between them.

>>>A.dtype
dtype('uint32')
>>>B.dtype
dtype('uint32')
>>>A.shape
(86, 50, 108)
>>>B.shape
(86, 50, 108)    
>>>A.min()
0
>>>B.min()
0
>>>A.max()
89478487
>>>B.max()
89115767

Now, if we do A - B

>>> diff = abs( A-B );
>>> diff.min()
0
>>> diff.max()
4294967292

Considering the min and max values of both matrices we cannot have 4294967292 as maximum value of the difference matrix. I have also done similar operations in Matlab and the difference diff and maximum value diff.max() are consistent. What is exactly A-B operation doing? My understanding is that the default behaviour for add, subtract, multiply and divide arrays with each other was element-wise operations however there is something funny happening here.

2

2 Answers

4
votes

You are using Unsigned 32 bit ints. So you're getting an overflow

>>> numpy.uint32(0) - numpy.uint32(1)
4294967295

Try changing your array's to type int…

>>> A = numpy.array([0,1,2],'uint32')
>>> B = numpy.array([1,2,3],'uint32')
>>> A-B
array([4294967295, 4294967295, 4294967295], dtype=uint32)
>>> A = A.astype(int)
>>> B = B.astype(int)
>>> A-B
array([-1, -1, -1])
3
votes

it is a little problematic to subtract unsigned ints from one another (unless you are certain the result is positive to begin with). So, why don't you work with signed integers?

diff = abs( A.astype('int32') - B.astype('int32') )

However, even this convertion will not give you results as in Matlab: becuase, for unsigned int types, Matlab clips the result at zero. For example (Matlab):

>> uint32(4)-uint32(5)

ans =

0

and not 4294967295 as in python.
So, if you want to mimic Matlab's behavior you'll need to clip the result

 >>> A = numpy.array([ 1,2,3], dtype='uint32')
 >>> B = numpy.array([2,2,2], dtype='uint32')
 >>> numpy.clip( A.astype(int) - B.astype(int), 0, numpy.iinfo(int).max )
 array([0, 0, 1])