使用python(OpenCV),图像中像素的迭代速度非常慢

skm*_*skm 4 python opencv numpy

我知道使用OpenCV和C++迭代像素并访问它们的值.现在,我正在尝试自己学习python,我试图在python中做同样的事情.但是当我运行以下代码时,显示图像需要花费很多时间(约7-10秒).并且即使在显示图像之后,脚本也会继续运行几秒钟.

我发现了一个类似的问题在这里SO,但我无法理解我如何在我的情况下,使用numpy的(因为我在python初学者)和它是否真的需要?

代码说明:我只想将黑色像素放在图像的左侧和右侧.

import numpy as np
import cv2 as cv

#reading an image
img = cv.imread('image.jpg')
height, width, depth = img.shape

for i in range(0, height):
    for j in range(0, (width/4)):
        img[i,j] = [0,0,0]  

for i in range(0, height):
    for j in range(3*(width/4), width):
        img[i,j] = [0,0,0]        

cv.imshow('image',img)

cv.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

roi*_*ppi 10

(注意:我不熟悉opencv,但这似乎是一个numpy问题)

"非常慢"的部分是你在python字节码中循环,而不是以numpyC速度循环.

尝试直接分配到(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
Run Code Online (Sandbox Code Playgroud)

以上显示左侧归零; 为右侧做同样的事情是读者的练习.

如果numpy切片语法绊倒你,我建议阅读索引文档.

  • 或者更简单地说,`img [:,:width/4,:] = 0`,而对于另一个边缘,`img [:, - width/4:,:] = 0` (2认同)