NumPy - Faster way to implement threshold value ceiling
image-processing, numpy, python
Solution
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
Problem
I'm writing a script to modify the luminance of a RGB image using NumPy and CV2 via converting from RGB to YCrCb and back again. However, the loop I'm using takes a while to execute, and am wondering if there is a faster way. ``` import cv2 as cv, numpy as np threshold = 64 image = cv.imread("motorist.jpg", -1) image.shape # Evaluates to (1000, 1500, 3) im = cv.cvtColor(image, cv.COLOR_RGB2YCR_CB) for row in image: for col in row: if col[0] > threshold: col[0] = threshold image = cv.cvtColor(im, cv.COLOR_YCR_CB2RGB) cv.imwrite("motorist_filtered.jpg", image) ``` That nested loop implementing the threshold comparison takes at least 5-7 seconds to execute. Is there a faster method to implement this functionality?