【问题标题】:Counting values along an axis in a 3D array that are greater than threshold values from a 2D array沿 3D 数组中的轴计数值大于 2D 数组中的阈值
【发布时间】:2017-05-24 03:13:22
【问题描述】:

我有一个 3D 维度数组 (200,200,3)。这些是使用 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)

如果阈值是整数/浮点值,则代码有效。例如。

threshold=0.3
counts=(stacked_images<threshold).sum(axis=2)

如果阈值是二维数组,有没有一种简单的方法可以做到这一点?我想我没有正确理解 numpy 广播规则。

【问题讨论】:

  • thresh 扩展到3D : (stacked_images &gt; threshold[...,None]).sum(2)
  • @kazemakase 我查看了您之前提供的链接。给出的一般答案是正确查看 numpy 广播规则。但是,我不知道如何将我的数组扩展到 3D。
  • @Divakar 您的解决方案有效。谢谢! :)

标签: arrays python-3.x numpy multidimensional-array array-broadcasting


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 2017-06-10
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2017-08-10
    相关资源
    最近更新 更多