快速将3D numpy数组(RGB图像)转换为布尔数组的方法

0 投票
2 回答
1235 浏览
提问于 2025-04-18 16:26

我该如何加快这个函数的速度?在处理一张512x512的图片时,它需要1.3秒。

def bool_map(image):
  '''
  Returns an np.array containing booleans,
  where True means a pixel has red value > 200.
  '''
  bool_map = np.zeros(image.shape, dtype=np.bool_)
  for row in range(image.shape[0]):
    for col in range(image.shape[0]):
      if image[row, col, 0] > 200:
        bool_map[row, col] = True
  return bool_map

2 个回答

1

跟C语言比起来,Python在处理数字数据时速度慢得多。为了让Python运行得更快,可以使用NumPy这个库,它可以处理大量数据的操作。

你的代码可以用下面这行来替代:

return image[:,:,0] > 200

6

利用numpy的向量运算,写成 image[:,:,0] > 200 这样会快很多。

>>> i = np.random.randint(0, 256, (512, 512, 3))
>>> b = i[:,:,0] > 200
>>> b
array([[False, False,  True, ..., False,  True, False],
       [False, False,  True, ..., False, False, False],
       [False,  True, False, ..., False, False, False],
       ..., 
       [False, False,  True, ..., False, False, False],
       [False,  True, False, ..., False, False, False],
       [ True, False,  True, ..., False, False, False]], dtype=bool)
>>> %timeit b = i[:,:,0] > 200
1000 loops, best of 3: 202 µs per loop

撰写回答