简体   繁体   English

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

[英]Fast way to convert 3d numpy array (RGB image) to a boolean array

How can I speed up this function? 如何加快此功能? It takes 1.3 seconds on a 512x512 image. 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

Take advantage of numpy's vector operations and write image[:,:,0] > 200 : this should be much faster. 利用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

Python positively crawls compared to C, especially when working with numeric data. 与C相比,Python积极抓取,尤其是在处理数字数据时。 To make this faster, leverage NumPy's bulk array operations. 为了加快速度,请利用NumPy的批量阵列操作。

Your code can be replaced with the equivalent: 您的代码可以替换为等效的代码:

return image[:,:,0] > 200

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM