Opencv Python 录像
程序员文章站
2022-05-16 14:55:46
...
import numpy as np
import cv2
import datetime
from general_utils import ImgUtil
cap = cv2.VideoCapture(0)
## some videowriter props
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = 10
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
#fourcc意为四字符代码(Four-Character Codes),顾名思义,该编码由四个字符组成,下面是VideoWriter_fourcc对象一些常用的参数,注意:字符顺序不能弄混
#cv2.VideoWriter_fourcc('I', '4', '2', '0'),该参数是YUV编码类型,文件名后缀为.avi
#cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),该参数是MPEG-1编码类型,文件名后缀为.avi
#cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),该参数是MPEG-4编码类型,文件名后缀为.avi
#cv2.VideoWriter_fourcc('T', 'H', 'E', 'O'),该参数是Ogg Vorbis,文件名后缀为.ogv
#cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),该参数是Flash视频,文件名后缀为.flv
fourcc = cv2.VideoWriter_fourcc(*'MP42')
## open and set props
videoWriter = cv2.VideoWriter()
#录像时间:
recordTime=[]
dtstart=datetime.datetime(2020,7,22,7,0,0)
dtend=datetime.datetime(2020,7,22,8,10,0)
class typeRecord(object):
def __init__(self,hour_start,min_start,hour_end,min_end):
yy=datetime.datetime.now().year
mm=datetime.datetime.now().month
dd=datetime.datetime.now().day
self.dtstart=datetime.datetime(yy,mm,dd,hour_start,min_start,0)
self.dtend=datetime.datetime(yy,mm,dd,hour_end,min_end,0)
nr=yy
nr=nr*100+mm
nr=nr*100+dd
nr=nr*100+hour_start
nr=nr*100+min_start
self.fn=str(nr)+ r".avi"
self.fileOpend=False
def isInRange(self):
nowtime=datetime.datetime.now()
if (nowtime>self.dtstart and nowtime<self.dtend):
return True
else:
return False
recordTime.append(typeRecord(7,0,8,10))
recordTime.append(typeRecord(10,0,11,0))
recordTime.append(typeRecord(11,0,12,0))
recordTime.append(typeRecord(12,0,13,15))
recordTime.append(typeRecord(15,30,16,30))
recordTime.append(typeRecord(16,30,18,00))
recordTime.append(typeRecord(21,59,23,0))
while(True):
ret,frame=cap.read()
nowString=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
ImgUtil.imgAddText(frame,nowString,1,sz[1]-10,0.5,0,255,255,2,withShadow=False)
ImgUtil.imgAddText(frame,nowString,1,sz[1]-10,0.5,0,0,0,0,withShadow=False)
if ret: cv2.imshow('frame',frame)
if cv2.waitKey(1)&0xff == ord('q'):
break
record=False
for tm in recordTime:
#print(tm.dtstart)
#print(tm.dtend)
record|=tm.isInRange()
if(tm.isInRange()):
if videoWriter.isOpened():
videoWriter.write(frame)
else:
videoWriter.open(tm.fn,fourcc,fps,sz,True)
if not record: # 如果不录象
if videoWriter.isOpened(): #如果正在开,就关掉
videoWriter.release()
if videoWriter.isOpened():videoWriter.release()
cap.release()
cv2.destroyAllWindows()