使用两个Numpy数组执行数学运算-限制数量
我有两个Numpy数组,需要对它们执行一些基本的数学运算。使用两个Numpy数组执行数学运算-限制数量,numpy,Numpy,我有两个Numpy数组,需要对它们执行一些基本的数学运算。 但是,由于最后一个numpy数组(名为magnity)的类型(uint8),我也不能使此操作的结果大于255。有什么想法吗?除了遍历数组之外 # Notice that the data type is "np.uint8", also arrays are 2D magnitude = np.zeros((org_im_width,org_im_height), dtype=np.uint8) # "numpy_arr_1" and
但是,由于最后一个numpy数组(名为
magnity
)的类型(uint8
),我也不能使此操作的结果大于255。有什么想法吗?除了遍历数组之外
# Notice that the data type is "np.uint8", also arrays are 2D
magnitude = np.zeros((org_im_width,org_im_height), dtype=np.uint8)
# "numpy_arr_1" and "numpy_arr_2" both of the same size & type as "magnitude"
# In the following operation, I should limit the number to 255
magnitude = ( (np.int_(numpy_arr_1))**2 + (np.int_(numpy_arr_2))**2 )**0.5
# The following doesn't work obviously:
# magnitude = min(255,((np.int_(numpy_arr_1))**2+(np.int_(numpy_arr_2))**2)**0.5)
首先,如果在创建后指定
magnity=…
,则将用操作中获得的数组替换初始uint8数组,因此magnity将不再是uint8
无论如何,如果示例中只是一个错误,要执行您想要的操作,您可以钳制/剪裁
或规范化
结果操作的值:
您可以找到将数组的值限制为min
和max
值的原因:
>>> magnitude = np.clip(operation, 0, 255)
其中运算是您计算的量值。事实上,您可能想要的是:
>>> magnitude = np.clip(np.sqrt(a**2 + b**2), 0, 255).astype(np.uint8)
其中,a
和b
分别是您的np.int(numpy\u arr\u 1)
和np.int(numpy\u arr\u 2)
,为便于阅读而重命名
此外,与您的情况一样,所有值均为正值,您可以将np.clip
替换为np.minimum
:
>>> magnitude = np.minimum(np.sqrt(a**2 + b**2), 255).astype(np.uint8)
然而,这只是将向量的大小限制为255(您想要的),但是对于更高大小的点
,您将丢失大量信息。如果某个点的幅值为1000,它将被钳制为255,因此在最终数组中1000=255
。震级变化较大的两个点最终将具有相同的震级(本例中为1000和255)
为了避免这种情况,您可以(重新缩放)震级范围至[0255]
。这意味着,如果在初始计算中,震级数组在范围[0,1000]
内,则将其转换为[0,255]
,因此1000
之前将是255
之后,但255
之前现在将是63
(简单线性缩放)
tmp/tmp.max()
如果震级的较低范围不是0
,则可以执行从[200,1000]
到[0,255]
的操作,以更好地表示数据:
>>> tmp = np.sqrt(a**2 + b**2).astype(float)
>>> tmax, tmin = tmp.max(), tmp.min()
>>> magnitude = ((tmp - tmin) / (tmax - tmin) * 255).astype(np.uint8)
1.为什么选择使用np.sqrt
而不是**0.5
?2.关于信息丢失-我理解-我的目标是Numpy数组中的数据最终将成为uint8
,而忽略信息丢失。3.我不能执行线性缩放!它将更改不高于255的其他值。我的目标是执行该数学运算,并确保只有超过255的值才会更改为255。这是因为我的最终Numpy数组应该包含其类型为uint8
的数据。谢谢np.sqrt
和**0.5
执行相同的操作,并且两者都有效。我更喜欢np.sqrt
,因为它更具可读性。由于我不知道你手术的最终目标,我试图展示所有可能的选择<代码>np。最小值应适用于您。这不起作用:如果a
和b
是数据类型uint8
,当您执行a**2+b**2
时,任何超过255的结果将溢出,并且只保留LSB位,例如,如果您有a=np.array([15,17],dtype=np.uint8)
然后a**2
计算为数组([225,33],dtype=uint8)
,其中33=17*17%256
。因此,除非在执行操作之前将原始数组转换为float
dtype,否则您正确解释的剪辑无效。在这种情况下,您只需要像问题中的OP那样将a
和b
转换为int
。我只是假设。编辑以澄清。
>>> tmp = np.sqrt(a**2 + b**2).astype(float)
>>> tmax, tmin = tmp.max(), tmp.min()
>>> magnitude = ((tmp - tmin) / (tmax - tmin) * 255).astype(np.uint8)