我正在尝试使用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")
我希望在完成第一个视频的录制并发布后,之后的视频中将包含内容。但是,只有在运行代码后的第一个视频文件中才包含帧。其余的只是空文件。
答案 0 :(得分:0)
在while循环中,调用cap.release()
会破坏对摄像机的引用,因此没有要保存的新帧。在while循环开始时重新打开videoCapture
,或者不关闭它。最好检查cap.read()
是否成功。