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

4 投票
2 回答
1734 浏览
提问于 2025-04-18 12:01

我有两个三维的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 个回答

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

撰写回答