沿 3D 数组中的轴计算大于 2D 数组中的阈值的值
Counting values along an axis in a 3D array that are greater than threshold values from a 2D array
我有一个维度为 (200,200,3) 的 3D 数组。这些是使用 numpy.dstack 堆叠的维度 (200,200) 的图像。我想计算沿 axis=2 大于相应二维阈值数组维度 (200,200) 的值的数量。输出计数数组的维度应为 (200,200)。到目前为止,这是我的代码。
import numpy as np
stacked_images=np.random.rand(200,200,3)
threshold=np.random.rand(200,200)
counts=(stacked_images<threshold).sum(axis=2)
我收到以下错误。
ValueError: operands could not be broadcast together with shapes (200,200,3) (200,200)
如果阈值是 integer/float 值,则代码有效。例如。
threshold=0.3
counts=(stacked_images<threshold).sum(axis=2)
如果 threshold 是一个二维数组,有没有一种简单的方法可以做到这一点?我想我没有正确理解 numpy 广播规则。
numpy 期望进行逐值运算。在您的情况下,您似乎想知道完整 Z(轴 = 2)轨迹中的任何值是否超过阈值中的等效 x、y 值。
因此,只需确保阈值具有相同的形状,即使用您喜欢的任何方法构建 3D 阈值。既然你提到了 numpy.dstack:
import numpy as np
stacked_images = np.random.rand(10, 10, 3)
t = np.random.rand(10, 10)
threshold = np.dstack([t, t, t])
counts = (stacked_images < threshold).sum(axis=2)
print(counts)
,结果为:
[[2 0 3 3 1 3 1 0 1 2]
[0 1 2 0 0 1 0 0 1 3]
[2 1 3 0 3 2 1 3 1 3]
[2 0 0 3 3 2 0 2 0 1]
[1 3 0 0 0 3 0 2 1 2]
[1 1 3 2 3 0 0 3 0 3]
[3 1 0 1 2 0 3 0 0 0]
[3 1 2 1 3 0 3 2 0 2]
[3 1 1 2 0 0 1 0 1 0]
[0 2 2 0 3 0 0 2 3 1]]
我有一个维度为 (200,200,3) 的 3D 数组。这些是使用 numpy.dstack 堆叠的维度 (200,200) 的图像。我想计算沿 axis=2 大于相应二维阈值数组维度 (200,200) 的值的数量。输出计数数组的维度应为 (200,200)。到目前为止,这是我的代码。
import numpy as np
stacked_images=np.random.rand(200,200,3)
threshold=np.random.rand(200,200)
counts=(stacked_images<threshold).sum(axis=2)
我收到以下错误。
ValueError: operands could not be broadcast together with shapes (200,200,3) (200,200)
如果阈值是 integer/float 值,则代码有效。例如。
threshold=0.3
counts=(stacked_images<threshold).sum(axis=2)
如果 threshold 是一个二维数组,有没有一种简单的方法可以做到这一点?我想我没有正确理解 numpy 广播规则。
numpy 期望进行逐值运算。在您的情况下,您似乎想知道完整 Z(轴 = 2)轨迹中的任何值是否超过阈值中的等效 x、y 值。
因此,只需确保阈值具有相同的形状,即使用您喜欢的任何方法构建 3D 阈值。既然你提到了 numpy.dstack:
import numpy as np
stacked_images = np.random.rand(10, 10, 3)
t = np.random.rand(10, 10)
threshold = np.dstack([t, t, t])
counts = (stacked_images < threshold).sum(axis=2)
print(counts)
,结果为:
[[2 0 3 3 1 3 1 0 1 2]
[0 1 2 0 0 1 0 0 1 3]
[2 1 3 0 3 2 1 3 1 3]
[2 0 0 3 3 2 0 2 0 1]
[1 3 0 0 0 3 0 2 1 2]
[1 1 3 2 3 0 0 3 0 3]
[3 1 0 1 2 0 3 0 0 0]
[3 1 2 1 3 0 3 2 0 2]
[3 1 1 2 0 0 1 0 1 0]
[0 2 2 0 3 0 0 2 3 1]]