使用python(OpenCV)在图像中进行像素迭代非常慢 [英] Iterations through pixels in an image are terribly slow with python (OpenCV)
问题描述
我知道使用OpenCV和C ++遍历像素并访问它们的值.现在,我正在尝试自己学习python ,我试图在python中做同样的事情.但是,当我运行以下代码时,需要花费很多时间(〜7-10秒)来显示图像.即使显示图像后,脚本也可以继续运行几秒钟.
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 thing in python. But when i am running the following code, it takes a lot of time (~7-10 seconds) to display the image. And the script keeps running on for few more seconds even after displaying the image.
我在SO的> ,但我无法理解在我的情况下如何使用numpy(因为我是python的初学者)以及是否真的需要它?
I found a similar question here at SO but i am not able to understand how do i use numpy in my case (because i am a beginner in python) and whether or not it is really required?
代码说明:我只是想在图像的左侧和右侧放置黑色像素.
Code Explanation: I am just trying to put the black pixels on the left and right side of the image.
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)
推荐答案
(注意:我对opencv
不熟悉,但这似乎是一个numpy
问题)
(note: I'm not familiar with opencv
, but this appears to be a numpy
issue)
非常慢"的部分是您要在python字节码中循环,而不是让numpy
以C速度循环.
The "terribly slow" part is that you're looping in python bytecode, rather than letting numpy
loop at C speed.
尝试直接分配给遮盖要归零区域的3维切片.
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.
这篇关于使用python(OpenCV)在图像中进行像素迭代非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!