可能的进一步改进可以是将帧捕获操作放入单独的线程中。以来 cv2.VideoCapture().read() 是一个阻塞操作,您的程序在轮询新帧时会遇到I / O延迟。目前,主线程轮询帧,然后在a中处理它 顺序 订购。通过专门用于轮询帧的完全不同的线程并让主线程仅关注处理帧,您可以执行任务 平行 。
cv2.VideoCapture().read()
这就是问题...
for x in range(width): for y in range(height): if canny[y,x] == 255:
Numpy.argmax是解决方案......
for x in range(width-1): # Slice the relevant column from the image # The image 'column' is a tall skinny image, only 1px thick column = np.array(canny[:,x:x+1]) # Use numpy to find the first non-zero value railPoint = np.argmax(column)
完整代码:
import cv2, numpy as np, time # Get start time start = time.time() # Read in the image img = cv2.imread('/home/stephen/Desktop/rail.jpg')[40:,10:-10] # Canny filter canny = cv2.Canny(img, 85, 255) # Get height and width height, width = canny.shape # Create list to store rail points railPoints = [] # Iterate though each column in the image for position in range(width-1): # Slice the relevant column from the image # The image 'column' is a tall skinny image, only 1px thick column = np.array(canny[:,position:position+1]) # Use numpy to find the first non-zero value railPoint = np.argmax(column) # Add the railPoint to the list of rail points railPoints.append(railPoint) # Draw a circle on the image cv2.circle(img, (position, railPoint), 1, (123,234,123), 2) cv2.imshow('img', img) k = cv2.waitKey(1) cv2.destroyAllWindows() print(time.time() - start)
我使用Numpy的解决方案需要6毫秒,而你的解决方案需要266毫秒。