python opencv在网络摄像头视频中使用putText显示时间倒计时 [英] python opencv display time countdown using putText in webcam video

查看:246
本文介绍了python opencv在网络摄像头视频中使用putText显示时间倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:

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

I'd like to put text on each frame obtained by the webcam so that the text "3", "2", "1" can be displayed for a second each. Thus portraying a countdown timer. Following the countdown, a frame should be written to file i.e. saved to disk. This should be repeatable as long as the video stream has not been closed.

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

Each frame is obtained within a while loop and due to hardware configuration the camera may have an unknown frame rate or worse, the number of frames retrieved by the camera per second can vary during the course of running the camera.

time.sleep()不能使用,因为它会冻结while循环并中断在窗口中显示的视频流.

time.sleep() cannot be used because it freezes the while loop and disrupts the video stream being displayed in the window.

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

another while loop inside the main while loop is unacceptable because it slows down the processor greatly and fewer frames are processed per second making the video stream very choppy.

我尝试过的事情:

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秒内).

I can see that my method almost works but the cpu ticks returned by time.time() is not the same as real world seconds. The text for each numeral isn't displayed for a whole second and the file is saved too quickly (within 1.5 seconds instead of 3).

我会接受以下答案:

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

If you can show how to get the timing correct and how to display "3", "2", "1" instead of my current method which displays "1", "2", "3"

推荐答案

苦苦挣扎了两天并阅读了datetime模块后,我有了所需的东西.但是,如果我的回答更pythonic,我可以接受我的回答.

After struggling for two days and reading up on datetime module I have what I need. I can however accept an answer other than mine if it is more 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()

这篇关于python opencv在网络摄像头视频中使用putText显示时间倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆