(注意:我对opencv不熟悉,但这似乎是一个小问题)
“非常慢”的部分是你在python字节码中循环,而不是让Cump速度的numpy循环.
尝试直接分配到(3维)切片,该切片会屏蔽您想要清零的区域.
import numpy as np
example = np.ones([500,500,500], dtype=np.uint8)
def slow():
img = example.copy()
height, width, depth = img.shape
for i in range(0, height): #looping at python speed...
for j in range(0, (width//4)): #...
for k in range(0,depth): #...
img[i,j,k] = 0
return img
def fast():
img = example.copy()
height, width, depth = img.shape
img[0:height, 0:width//4, 0:depth] = 0 # DO THIS INSTEAD
return img
np.alltrue(slow() == fast())
Out[22]: True
%timeit slow()
1 loops, best of 3: 6.13 s per loop
%timeit fast()
10 loops, best of 3: 40 ms per loop
以上显示左侧归零;为右侧做同样的事情是读者的练习.
如果numpy切片语法让你兴奋,我建议你阅读indexing docs.