NumPy - Faster way to implement threshold value ceiling
The idea is to create a mask that lets you use the numpy's vectorization. Since the shape is (n,m,3)
, loop over the first two dimensions and grab the first index of the last dimension with [:,:,0]
idx = image[:,:,0] > threshold
image[idx,0] = threshold
You can use clip
:
- http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html
Usage:
result = im.copy()
result[..., 0] = np.clip(im[..., 0], 0, threshold)
Or to modify in-place:
np.clip(im[..., 0], 0, threshold, out=im[..., 0])