PYTHON:如何每分钟从 RTSP 自动捕获图像直到 24 小时 [英] PYTHON: how to automatically capture image from RTSP every minute up until 24 hours

查看:89
本文介绍了PYTHON:如何每分钟从 RTSP 自动捕获图像直到 24 小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想用 python 编写一个代码,我从 rtsp 相机(实时流媒体)中提取照片作为帧.但我希望这些照片也与时间戳和日期一起存储,我认为我已经完成了.我唯一的挑战是我希望这些照片每分钟自动保存到我的本地计算机,并在 24 小时后结束.

So I want to write a code in python where I extract photos as frames from an rtsp camera (live streaming). But I would want these photos to be stored with timestamp and date as well which I think I have done. My only challenge is that I want these photos to automatically save to my local computer every minute and ends after 24 hours.

我该怎么做?

这是我当前的代码

 imagesFolder = "C:/Users/<user>/documents"
cap = cv2.VideoCapture("rtsp://username:password@cameraIP/axis-media/media.amp")
frameRate = cap.get(5) #frame rate
count = 0

while cap.isOpened():
    frameId = cap.get(1)  # current frame number
    ret, frame = cap.read()

    if (ret != True):
        break
    if (frameId % math.floor(frameRate) == 0):
        filename = imagesFolder + "/image_" + str(datetime.now().strftime("%d-%m-%Y_%I-%M-%S_%p"))  + ".jpg"
        cv2.imwrite(filename, frame)

    cap.release()
    print ("Done!")

cv2.destroyAllWindows()

推荐答案

这比其他解决方案效果更好.这里唯一的挑战是照片在前 3 分钟(前 3 张照片是在几秒钟内拍摄但在每分钟后保存)后停止保存.现在的解决方案是确保它在停止前每分钟节省最多 24 小时.

This works somewhat better than other solutions. The only challenge here is that the photos stop saving after the first 3 minutes (first 3 photos which are taken in seconds but saved later during each minute) have been saved. The solution now is to ensure that it saves every minute up to 24 hours before it stops.

    import cv2
    import time
    import getpass
    import numpy as np
    import subprocess as sp
    from datetime import datetime

imagesFolder = "C:/Users/" + getpass.getuser() + "/documents"

# RTSP Streaming:
in_stream = "rtsp://username:password@cameraIP/axis-media/media.amp"
cap = cv2.VideoCapture(in_stream)

frameRate = cap.get(5) #frame rate

# Get resolution of input video
width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Release VideoCapture - it was used just for getting video resolution
cap.release()

in_stream = "rtsp://username:password@cameraIP/axis-media/media.amp"

FFMPEG_BIN = "ffmpeg.exe" # on Windows

# Suspecting camera supports TCP protocol hence added: '-rtsp_transport', 'tcp'
command = [ FFMPEG_BIN,
            '-rtsp_transport', 'tcp',
            '-i', in_stream,
            '-f', 'image2pipe',
            '-pix_fmt', 'bgr24',
            '-vcodec', 'rawvideo', '-an', '-']

# Open sub-process that gets in_stream as input and uses stdout as an output PIPE.
pipe = sp.Popen(command, stdout=sp.PIPE, bufsize=10**8)


cur_time = time.time()  # Get current time

# start_time_24h measures 24 hours
start_time_24h = cur_time

# start_time_1min measures 1 minute
start_time_1min = cur_time - 30  # Subtract 30 seconds for start grabbing first frame after 30 seconds (instead of waiting a minute for the first frame).



while True:
    # read width*height*3 bytes from stdout (= 1 frame)
    raw_frame = pipe.stdout.read(width*height*3)

    if len(raw_frame) != (width*height*3):
        print('Error reading frame!!!')  # Break the loop in case of an error (too few bytes were read).
        break

    cur_time = time.time()  # Get current time
    elapsed_time_1min = cur_time - start_time_1min  # Time elapsed from previous image saving.

    # If 60 seconds were passed, reset timer, and store image.
    if elapsed_time_1min >= 60:
        # Reset the timer that is used for measuring 60 seconds
        start_time_1min = cur_time

        # Transform the byte read into a numpy array, and reshape it to video frame dimensions
        frame = np.fromstring(raw_frame, np.uint8)
        frame = frame.reshape((height, width, 3))

        filename = imagesFolder + "/image_" + str(datetime.now().strftime("%d-%m-%Y_%I-%M-%S_%p"))  + ".jpg"
        #filename = "image_" + str(datetime.now().strftime("%d-%m-%Y_%I-%M-%S_%p"))  + ".jpg"
        cv2.imwrite(filename, frame)

        # Show frame for testing
        cv2.imshow('frame', frame)
        cv2.waitKey(1)

    elapsed_time_24h = time.time() - start_time_24h

    #Break loop after 24*60*60 seconds
    if elapsed_time_24h > 24*60*60:
        break

    #time.sleep(60 - elapsed_time) # Sleeping is a bad idea - we need to grab all the frames.


print ("Done!")

pipe.kill()  # Kill the sub-process after 24 hours
cv2.destroyAllWindows()

这篇关于PYTHON:如何每分钟从 RTSP 自动捕获图像直到 24 小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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