【问题标题】:Processing frame every second in opencv python在opencv python中每秒处理帧
【发布时间】:2018-07-09 14:34:20
【问题描述】:

这是使用 opencv 网站从网络摄像头读取视频文件的代码。我只想每秒处理一次帧。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

我应该如何修改代码:

【问题讨论】:

    标签: python python-3.x python-2.7 opencv


    【解决方案1】:

    你应该让你的进程在每次读取前等待一秒钟:

    import numpy as np
    import cv2
    import time
    
    cap = cv2.VideoCapture(0)
    
    while(True):
        # Capture frame-by-frame
        start_time = time.time()
        ret, frame = cap.read()
    
        # Our operations on the frame come here
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # Display the resulting frame
        cv2.imshow('frame',gray)
    
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
        time.sleep(1.0 - time.time() + start_time) # Sleep for 1 second minus elapsed time
    
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()
    

    【讨论】:

    • 考虑处理时间会很好
    • @DmitriiZ。可以一次又一次地执行cap.read() 并跳过帧,但效率非常低。与一秒相比,这里的处理时间非常短。另一种可能性是每秒运行一个进程以获得一个帧。然而,这需要对代码进行更大的转换。
    • 为什么不添加start = time.time()end = time.time() 并为 (1 - (end - start)) 而不是 1 休眠? (还要考虑到处理时间可能大于 1s)
    • 好主意,我会把它添加到我的解决方案中。
    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    相关资源
    最近更新 更多