Как получить видеофайлы после первого видеофайла, чтобы правильно сохранить - PullRequest
0 голосов
/ 18 июня 2019

Я пытаюсь использовать openCV для записи видео с моих IP-камер в целях безопасности. Я хотел бы установить видео для записи в течение определенного промежутка времени (например, с 10 утра до 10 вечера), а затем спать до следующего дня в следующий раз. Приведенный ниже код пытается эмулировать этот процесс в течение более короткого периода времени, чтобы упростить тестирование.

import cv2
# import numpy as np
from datetime import datetime, timedelta
import time

# capture IP camera's live feed
cap = cv2.VideoCapture('rtsp://admin:@10.187.1.146:554/user=admin_password=tlJwpbo6_channel=1_stream=0')
ret, initialFrame = cap.read()

# Settings for the video recording.
fourcc = cv2.VideoWriter_fourcc(*'XVID')
fps = 22

# Get the frame's size
fshape = initialFrame.shape
fheight = fshape[0] # int(fshape[0] * (75 / 100))
fwidth = fshape[1] # int(fshape[1] * (75 / 100))

frameSize = (fwidth,fheight)

if cap.isOpened:
    print ("The IP Camera's feed is now streaming\n")
    today = datetime.today().strftime('%Y-%b-%d')

    try:
        #Loop to view the camera's live feed
        while datetime.today().strftime('%Y-%b-%d') == today:

            vidOut = cv2.VideoWriter('Cam01_'+str(today)+ " " + str(datetime.today().strftime('%H:%M')) +'.avi',fourcc,fps,frameSize)
            print ("Recording for " + today)

            recStart = datetime.now()
            recStop = recStart + timedelta(seconds= 60*3)

            print ("Recording for duration of 10 mins \n\n Press Ctrl+C on the keyboard to quit \n\n")

            while recStart <= datetime.now() and datetime.now() <= recStop:

                # read frame
                ret, frame = cap.read()

                # Write frame to video file
                vidOut.write(frame)

            print ("Recording ended at " + datetime.now().strftime("%Y-%B-%d, %A %H:%M"))
            print ("Next Recording at " + (datetime.now() + timedelta(seconds= 60*3)).strftime("%Y-%B-%d, %A %H:%M"))

            vidOut.release() # End video write
            cap.release() # Release IP Camera
            # cv2.destroyAllWindows() # Close all Windows that were launched by cv2.

            print ('Waiting 3 mins before next recording')
            time.sleep(60*3)
            continue

    except KeyboardInterrupt:
        print ("\n Process Interrupted by User \n")
        print ("\n Recording ended at " + datetime.now().strftime("%Y-%B-%d, %A %H:%M"))
        print ("Next Recording at " + (recStart + timedelta(seconds= 600)).strftime("%Y-%B-%d, %A %H:%M"))

        vidOut.release() # End video write
        cap.release() # Release IP Camera
else:
    print("The video stream couldn't be reached")

Я ожидал, что после того, как будет закончено запись и выпуск первого видео, в видео после этого будет содержаться контент. Однако только первый видеофайл после выполнения кода содержит кадры. остальные просто пустые файлы.

1 Ответ

0 голосов
/ 18 июня 2019

В цикле while вы вызываете cap.release(), который уничтожает ссылку на камеру, поэтому новые кадры для сохранения отсутствуют. Либо (пере) откройте videoCapture в начале цикла while, либо не закрывайте его. Также рекомендуется проверять, был ли cap.read() успешным.

...