如何使用openCV在Python中提高视频播放速度

Gen*_*tem 5 python performance opencv video-capture

我正在编写一个程序,在遇到栏杆的第一个像素的视频上画一条线,我的问题是视频播放缓慢。

在此处输入图片说明 屏幕截图,供您参考视频的外观。在录像过程中,摄像机移近了,但由于速度慢,我不得不等待几分钟才能看到变化,但是在拍摄时,摄像机每隔几秒钟就移动一次。

我认为问题是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()
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ste*_*hke 2

这就是问题...

for x in range(width):
    for y in range(height):
         if canny[y,x] == 255:
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

完整代码:

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)
Run Code Online (Sandbox Code Playgroud)

我使用 Numpy 的解决方案花了 6 毫秒,而你的解决方案花了 266 毫秒。 轨输出


归档时间:

查看次数:

579 次

最近记录:

6 年,10 月 前