【发布时间】:2021-12-04 02:14:52
【问题描述】:
我有一段代码如下:
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 ...
这段代码没有像我预期的那样运行得足够快。我想我可以通过一一应用所有条件来使其更快,即:
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
上述方法可以加速我的代码吗?以及如何做到这一点?非常感谢!
【问题讨论】:
-
mask[red > 100 & red > green & red > blue] = 255怎么样?或者更好:mask = (red > 100 & red > green & red > blue) * 255。np.where通常是不必要的,而且是浪费时间。 -
bgr = np.int16(image)-- 希望达到什么目的? -
@DanMašek cv2 将图像读取为 uint8 格式。如果不转换为 int16,我的过滤器将不再工作
标签: python numpy opencv image-processing colorfilter