在Python和Matlab中减去3D numpy数组

4

我有两个3D numpy数组,想要找出它们之间的差异。

>>>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

现在,如果我们执行 A - B
>>> diff = abs( A-B );
>>> diff.min()
0
>>> diff.max()
4294967292

考虑到两个矩阵的minmax值,我们不能将4294967292作为差值矩阵的最大值。我还在Matlab中进行了类似的操作,差值diff和最大值diff.max()是一致的。那么A-B操作到底是什么呢?我的理解是,对数组进行加、减、乘、除操作的默认行为是逐元素操作,但这里发生了一些有趣的事情。

2个回答

4

您正在使用无符号32位整数,因此出现了溢出问题。

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

尝试将你的数组类型更改为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])

@_Charles 有没有什么方法可以避免这种情况? - Manolete
你可以使用普通的“int”,A = A.astype(int),B = B.astype(int),A-B 应该可以工作。 - Charles

3

从无符号整数中减去另一个无符号整数有点问题(除非您确定结果一定是正数)。那么,为什么不使用有符号整数呢?

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

然而,即使进行这种转换也不会像Matlab中一样产生结果: 因为对于无符号整型,Matlab将结果截断为零。例如(Matlab):
>> uint32(4)-uint32(5)

ans =

0

与Python不同的是,结果不是4294967295。
因此,如果您想模仿Matlab的行为,您需要剪辑结果。

 >>> 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])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接