[英]How to speed up the loop over an OpenCV image in Python using Numpy?
目标是通过使用numpy
的内置函数来克服 python 中嵌套循环执行缓慢的问题。
在下面的代码中,我将带有imread
(颜色:BGR)的图像读取到src
(一个 numpy 数组)中,并为每种颜色(分别为 BGR)定义了阈值。 然后我逐个像素地循环遍历src
(有两个for
嵌套循环),在每次迭代中我测试当前像素是否满足阈值(每个值的三个条件:蓝色、绿色和红色),在正情况下(像素满足条件)我将其坐标保存在列表中(行号: i
,列号: j
)。
import cv2
src = cv2.imread('path_to_the_image') # A numpy array with shape: (width, height, 3) ["3" for BGR]
cond = [10, 20, 30] # A threshold for each color: Blue, Green and Red respectively
indexes = [] # To save pixel's coordinates which satisfies all three conditions
for i in range(0, src.shape[0]): # Loop over lines (width)
for j in range(0, src.shape[1]): # Loop over columns (height)
if src[i, j, 0] >= cond[0] and src[i, j, 1] >= cond[1] and src[i, j, 2] >= cond[2]:
indexes.append((i, j))
那么,我想知道如何使用numpy
内置函数重写此代码以从其速度中受益?
你可以这样做:
a = np.array([[[1,2,3], [10,20,30]],
[[40,50,60], [10, 30, 20]]
])
[*zip(*np.where((a > (10,20,30)).all(-1)))]
输出:
[(1, 0)]
注意: np.where((a > (10,20,30)).all(-1))
单独会给你[array([1]), array([0])]
在某些情况下可能会更好.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.