How can I speed up this function? It takes 1.3 seconds on a 512x512 image.
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.
>>> 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. To make this faster, leverage NumPy's bulk array operations.
Your code can be replaced with the equivalent:
return image[:,:,0] > 200
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.