I am trying to use openCV to record videos from my IP Cameras for security use. I'd like to set the videos to record within a given time span (Eg from 10am to 10 pm) then sleep until the next day at the next time. The code below tries to emulate this process over a shorter time period to allow for easy testing.
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")
I expected that after after the first video is done recording and is released, the videos after that would have content in them. However, only the first video file after running the code has frames in it. the rest are just empty files.
In the while loop you call cap.release()
which destroys the reference to the camera, so there are no new frames to save. Either (re)open the videoCapture
at the start of the while loop, or don't close it. It is also good practice to check if the cap.read()
was successful.