【问题标题】:Numpy greenkey : operands could not be broadcast together with shapesNumpy greenkey:操作数无法与形状一起广播
【发布时间】:2019-07-20 14:38:05
【问题描述】:

我正在尝试创建最简单的绿屏算法。我已经生成了形状为(1920,1080)并包含布尔值的“key”数组。仅仅使用foreground*key + background*inverted_key 是行不通的,因为前景和背景的形状是 (1920,1080,3),所以它会提升 Value error: operands could not be broadcast together with shapes (1920,1080,3) (1920,1080)。那我该怎么做这个操作呢? 另外,我已经尝试过使用形状为 (3,3,3) 和 (3,3) 的数组 - 它工作得很好。请解释一下发生了什么,我很困惑。

【问题讨论】:

标签: python numpy valueerror


【解决方案1】:

Python广播规则很简单:

  1. 在维数较少的数组形状中添加前导 1
  2. 放大所有 1 以匹配其他数组中的维度
  3. 在前两步之后,所有维度都必须匹配

因此,当您将 (3, 3, 3) 和 (3, 3) 相乘时,首先将第二个数组扩展一维 (1, 3, 3),然后缩放所有 1 以匹配您相乘的意思(3, 3, 3) 通过 (3, 3, 3) 最后。 当您将 (1920, 1000, 3) 乘以 (1920, 1000) 时,第二个数组将扩展到 (1, 1920, 1000),然后将 1 放大,所以最后您尝试将 (1920, 1000, 3) 相乘) 乘以 (1920, 1920, 1000) 因此错误。

你可以这样做:

key3dim = np.tile(key.reshape(key.shape[0], key.shape[1], 1), 3)
# or
key3dim = np.repeat(key.reshape(key.shape[0], key.shape[1], 1), 3, 2)
# or
key3dim = key.reshape(key.shape[0], key.shape[1], 1).repeat(3, 2)
foreground*key3dim + background*~key3dim

examples of broadcasting here

【讨论】:

  • 为什么不利用广播,简单地将键重塑为 (1920,1080,1) 并直接用于混合公式?
猜你喜欢
  • 2012-08-05
  • 2020-06-20
  • 2014-08-24
  • 1970-01-01
  • 2015-05-18
  • 2017-09-09
  • 2020-09-06
  • 2012-10-31
  • 2013-04-07
相关资源
最近更新 更多