Iterations through pixels in an image are terribly slow with python (OpenCV)

前端 未结 1 1730
心在旅途
心在旅途 2020-12-19 07:01

I am aware of iterating through pixels and accessing their values using OpenCV with C++. Now, i am trying to learn python myself and i tried to do the same

相关标签:
1条回答
  • 2020-12-19 07:47

    (note: I'm not familiar with opencv, but this appears to be a numpy issue)

    The "terribly slow" part is that you're looping in python bytecode, rather than letting numpy loop at C speed.

    Try directly assigning to a (3-dimensional) slice that masks the region you want to zero out.

    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
    

    The above shows zeroing out the left side; doing the same for the right side is an exercise for the reader.

    If the numpy slicing syntax trips you up, I suggest reading through the indexing docs.

    0 讨论(0)
提交回复
热议问题