I have a piece of code as bellow:
import cv2
import numpy as np
import operator
from functools import reduce
image = cv2.imread("<some image path>")
bgr = np.int16(image)
h, w, _ = image.shape
mask = np.zeros((h, w), np.uint8)
# Get all channels
blue = bgr[:,:,0]
green = bgr[:,:,1]
red = bgr[:,:,2]
rules = np.where(reduce(operator.and_, [(red > 100), (red > green), (red > blue)]
# Create mask using above rules
mask[rules] = 255
### Then use cv2.findContours ...
This piece of code doesn't run enough fast as I expected. I think I can make it more faster by apply all conditions one by one, ie:
rule_1 = np.where(red > 100)
rule_2 = np.where(red[rule_1] > green)
rule_3 = np.where(red[rule_2] > blue)
mask[rule_3] = 255
Can the above method speed up my code? And how to do that? Many thanks!
A great way is (adapted from Cris Luengo's comment)
but if you need faster, you can use Numba
Notice that
prangeis used instead ofrange. This tells Numba that the loops are parallelizable.On my computer the Numba version is about 3x faster.
Best of luck!