【问题标题】:Iterations through pixels in an image are terribly slow with python (OpenCV)使用 python (OpenCV) 迭代图像中的像素非常慢
【发布时间】:2014-10-18 22:23:19
【问题描述】:

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

我发现了一个类似的问题here at 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)

【问题讨论】:

    标签: python opencv numpy


    【解决方案1】:

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

    “非常慢”的部分是您在 python 字节码中循环,而不是让 numpy 以 C 速度循环。

    尝试直接分配给一个(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

    【讨论】:

    • 感谢您的回复。正如我所提到的,我对 python 完全陌生,所以如果你能解释你的代码的基本思想,这对我很有帮助。
    • 我不确定你在问什么;我解释说你需要分配给一个 3D 切片,并评论了我这样做的那一行。更具体地说明您不了解的内容。
    • 或者更简单地说,img[:,:width/4,:] = 0,对于另一边,img[:,-width/4:,:] = 0
    • 如果您想在一行中完成,img[:,np.r_[:width/4,-width/4:],:] = 0
    • 在这一行:img[0:height, 0:width//4, 0:depth] = 00 可以是一个自定义函数,应用于每个像素吗?
    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2019-08-25
    相关资源
    最近更新 更多