![](/img/trans.png)
[英]How to convert a 3d RGB NumPy array to float without changing the image?
[英]Fast way to convert 3d numpy array (RGB image) to a boolean array
如何加快此功能? 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
利用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
与C相比,Python积极抓取,尤其是在处理数字数据时。 为了加快速度,请利用NumPy的批量阵列操作。
您的代码可以替换为等效的代码:
return image[:,:,0] > 200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.