我正在编写一个程序,在遇到栏杆的第一个像素的视频上画一条线,我的问题是视频播放缓慢。
屏幕截图,供您参考视频的外观。在录像过程中,摄像机移近了,但是由于速度慢,我不得不等待几分钟才能看到变化,但是在拍摄时,摄像机每隔几秒钟就移动一次。
我认为问题是for循环正在视频的每一帧上运行,但我不确定。
我可以采用什么解决方案来加快程序运行速度?
import cv2
cap = cv2.VideoCapture('video.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
canny = cv2.Canny(frame, 85, 255)
height, width = canny.shape
first_black_array = []
for x in range(width):
first_black_pixel_found = 0
for y in range(height):
if first_black_pixel_found == 0:
if canny[y,x] == 255:
first_black_array.append(height - y)
first_black_pixel_found = 1
cv2.line(frame,(x,y),(x,y),(0,255,0),1)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
谢谢!
答案 0 :(得分:1)
这是问题所在...
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)
答案 1 :(得分:0)
潜在的进一步改进可能是将帧捕获操作放在单独的线程中。由于cv2.VideoCapture().read()
是一项阻止操作,因此您的程序在轮询新帧时会遇到I / O延迟。当前,主线程轮询一个帧,然后以顺序顺序对其进行处理。通过为轮询帧指定一个完全不同的线程并使主线程仅专注于处理帧,您可以在 parallel 中执行任务。