繁体   English   中英

python opencv在网络摄像头视频中使用putText显示时间倒计时

[英]python opencv display time countdown using putText in webcam video

目标:

我想在网络摄像头获得的每一帧上放置文本,以便可以分别显示文本“ 3”,“ 2”,“ 1”。 因此描绘了一个倒数计时器。 倒数之后,应将一帧写入文件,即保存到磁盘。 只要视频流尚未关闭,这应该是可重复的。

每个帧都是在while循环内获得的,并且由于硬件配置,照相机可能具有未知的帧速率或更差的帧速率,在运行照相机的过程中,照相机每秒检索的帧数可能会有所不同。

无法使用time.sleep()因为它会冻结while循环并中断窗口中显示的视频流。

主while循环内的另一个while循环是不可接受的,因为它极大地减慢了处理器的速度,并且每秒处理的帧数更少,从而使视频流非常不连贯。

我尝试过的

import cv2
import sys
import time

# Initialize variables
camSource = -1
running = True
saveCount = 0
nSecond = 1
totalSec = 3.0
keyPressTime = 0.0
startTime = 0.0
timeElapsed = 0.0
startCounter = False
endCounter = False

# Start the camera
camObj = cv2.VideoCapture(camSource)
if not camObj.isOpened():
    sys.exit('Camera did not provide frame.')

frameWidth = int(camObj.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
frameHeight = int(camObj.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))

# Start video stream
while running:
    readOK, frame = camObj.read()

    # Display counter on screen before saving a frame
    if startCounter:
        if nSecond <= totalSec: 
            # draw the Nth second on each frame 
            # till one second passes  
            cv2.putText(img = frame, 
                        text = str(nSecond),
                        org = (int(frameWidth/2 - 20),int(frameHeight/2)), 
                        fontFace = cv2.FONT_HERSHEY_DUPLEX, 
                        fontScale = 3, 
                        color = (255,0,0),
                        thickness = 2, 
                        lineType = cv2.CV_AA)

            timeElapsed += (time.time() - startTime)
            print 'timeElapsed:{}'.format(timeElapsed)

            if timeElapsed >= 1:
                nSecond += 1
                print 'nthSec:{}'.format(nSecond)
                timeElapsed = 0
                startTime = time.time()

        else:
            # Save the frame
            cv2.imwrite('img' + str(saveCount) + '.jpg', frame)  
            print 'saveTime: {}'.format(time.time() - keyPressTime)

            saveCount += 1
            startCounter = False
            nSecond = 1

    # Get user input
    keyPressed = cv2.waitKey(3)
    if keyPressed == ord('s'):
        startCounter = True
        startTime = time.time()
        keyPressTime = time.time()
        print 'startTime: {}'.format(startTime)
        print 'keyPressTime: {}'.format(keyPressTime)

    elif keyPressed == ord('q'):
        # Quit the while loop
        running = False
        cv2.destroyAllWindows()

    # Show video stream in a window    
    cv2.imshow('video', frame)

camObj.release()

问题:

我可以看到我的方法几乎可以正常工作,但是time.time()返回的CPU滴答数与实际秒数不同。 每个数字的文本不会显示整整一秒钟,并且文件保存太快(在1.5秒而不是3秒内)。

我会回答:

如果您可以显示如何正确设置时间以及如何显示“ 3”,“ 2”,“ 1”,而不是我当前的显示“ 1”,“ 2”,“ 3”的方法

挣扎了两天并阅读了datetime模块后,我有了所需的东西。 但是我可以接受除我以外的其他答案,如果它是更pythonic的。

import cv2
import sys
from datetime import datetime

# Initialize variables
camSource = -1
running = True
saveCount = 0
nSecond = 0
totalSec = 3
strSec = '321'
keyPressTime = 0.0
startTime = 0.0
timeElapsed = 0.0
startCounter = False
endCounter = False

# Start the camera
camObj = cv2.VideoCapture(camSource)
if not camObj.isOpened():
    sys.exit('Camera did not provide frame.')

frameWidth = int(camObj.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
frameHeight = int(camObj.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))

# Start video stream
while running:
    readOK, frame = camObj.read()

    # Display counter on screen before saving a frame
    if startCounter:
        if nSecond < totalSec: 
            # draw the Nth second on each frame 
            # till one second passes  
            cv2.putText(img = frame, 
                        text = strSec[nSecond],
                        org = (int(frameWidth/2 - 20),int(frameHeight/2)), 
                        fontFace = cv2.FONT_HERSHEY_DUPLEX, 
                        fontScale = 6, 
                        color = (255,255,255),
                        thickness = 5, 
                        lineType = cv2.CV_AA)

            timeElapsed = (datetime.now() - startTime).total_seconds()
#            print 'timeElapsed: {}'.format(timeElapsed)

            if timeElapsed >= 1:
                nSecond += 1
#                print 'nthSec:{}'.format(nSecond)
                timeElapsed = 0
                startTime = datetime.now()

        else:
            cv2.imwrite('img' + str(saveCount) + '.jpg', frame)  
#            print 'saveTime: {}'.format(datetime.now() - keyPressTime)

            saveCount += 1
            startCounter = False
            nSecond = 1

    # Get user input
    keyPressed = cv2.waitKey(3)
    if keyPressed == ord('s'):
        startCounter = True
        startTime = datetime.now()
        keyPressTime = datetime.now()
#        print 'startTime: {}'.format(startTime)
#        print 'keyPressTime: {}'.format(keyPressTime)

    elif keyPressed == ord('q'):
        # Quit the while loop
        running = False
        cv2.destroyAllWindows()

    # Show video stream in a window    
    cv2.imshow('video', frame)

camObj.release()

这是我自己的实现的一个版本,该版本实现了5秒倒计时定时器的无用支付,而无论输出10秒视频,它都是如此! 请让我知道评论中的任何问题!

    def draw_text(frame, text, x, y, color=(255,0,255), thickness=4, size=3):
            if x is not None and y is not None:
                cv2.putText(
                    frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)

    import numpy as np
    import cv2
    import time
    #timeout = time.time() + 11   # 10 seconds from now
    cap = cv2.VideoCapture(0)
    init_time = time.time()
    test_timeout = init_time+6
    final_timeout = init_time+17
    counter_timeout_text = init_time+1
    counter_timeout = init_time+1
    counter = 5
    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            center_x = int(frame.shape[0]/2)
            center_y = int(frame.shape[0]/2)
            if (time.time() > counter_timeout_text and time.time() < test_timeout):
                draw_text(frame, str(counter), center_x, center_y)
                counter_timeout_text+=0.03333
            if (time.time() > counter_timeout and time.time() < test_timeout):
                counter-=1
                counter_timeout+=1
            cv2.imshow('frame', frame)
            if (cv2.waitKey(1) & 0xFF == ord('q')) or (time.time() > final_timeout):
                break
        else:
            break
    # Release everything if job is finished
    cap.release()
    cv2.destroyAllWindows()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM