【问题标题】:Apply thresholding logic to one column of NumPy array将阈值逻辑应用于 NumPy 数组的一列
【发布时间】:2020-12-16 06:49:50
【问题描述】:

我有一个 3D NumPy 数组,它本质上是 RGBA 格式的图像数据,如下所示:

[
  [
    [233 228 230 120]
    [233 228 230 0]
    [232 227 229 212]
    ...
  ]
  ...
]

在上面的示例中,最后(第 4)列代表 Alpha 通道。由于我不能有半透明像素(0 或 255 以外的值),我需要对该列设置阈值。任何低于 255 的值都应变为 0。

我所拥有的是下面的行。

image[...,3][image[...,3] < 255] = 0

它确实有效,但我想问是否有更短更优雅的东西可以完成这项工作。谢谢。

【问题讨论】:

  • 你能发布你的图片形状吗?

标签: python numpy


【解决方案1】:

编辑:@Lior Cohen 确实是对的!道歉。

# if your channels are in the last axis, this should work
image[:,:,3][image[:,:,3] < 255] = 0

# another alternative, but not as elegant as what @Lior proposed
image[:,:,3] = np.where(image[:,:,3] < 255, 0, 255)

【讨论】:

  • 我认为这会将 RGB 截断为 0 而不仅仅是 alpha
  • @LiorCohen 你是对的!我忽略了它。你的回答应该被接受。
【解决方案2】:

另外两个选项基于/255 运算符,将小于 255 的整数切为 0。

  1. image[...,3] = image[...,3] // 255 * 255
    
  2. image[...,3] //= 255
    image[...,3] *= 255
    

【讨论】:

    猜你喜欢
    • 2017-07-10
    • 2011-04-23
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2018-04-21
    相关资源
    最近更新 更多