本文总共用到了笔记本自带摄像头和一个外接摄像头,在人脸识别用到的人脸识别的xml文件会在后文中给出链接,代码还有很大的优化空间,等后面有时间了就慢慢优化,目前运行尚未出现异常现象,语言播报目前识别人脸播报会引起卡顿,仍是一个待优化的点
import cv2
import time
import win32com.client as win
startup=time.time()
speak = win.Dispatch("SAPI.SpVoice")
speak.Speak('视频录制与人脸识别正在启动,正在载入人脸识别所需项目')
faces_list=[]
number_list=['60','120','180']
face_cascade = cv2.CascadeClassifier('RecognitionModel.xml')
today=time.time()
cap = cv2.VideoCapture(0)
cap_usb=cv2.VideoCapture(1)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
size_usb=(int(cap_usb.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap_usb.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter('视频保存{}.avi'.format(time.strftime('%Y-%m-%d_%H_%I_%M_%S')), fourcc,5.0, size)
out_usb=cv2.VideoWriter('人像识别保存{}.avi'.format(time.strftime('%Y-%m-%d_%H_%I_%M_%S')),fourcc,5.0,size)
start=time.time()
speak.Speak('摄像机0号与摄像机USB正在启动中')
def read():
while True:
ret, frame = cap.read()
ret_usb,frame_usb=cap_usb.read()
grey_usb=cv2.cvtColor(frame_usb,cv2.COLOR_BGR2GRAY)
faces_usb=face_cascade.detectMultiScale(grey_usb,scaleFactor=1.5,minNeighbors=5)
for(x,y,w,h) in faces_usb:
width = x+w
height = y+h
strok=2
color=(255,0,0)
cv2.rectangle(frame_usb,(x,y),(width,height),color,strok)
faces_list.append(len(faces_usb))
frame = cv2.flip(frame, 1)
frame_usb = cv2.flip(frame_usb, 1)
out.write(frame)
out_usb.write(frame_usb)
if faces_list!=[]:
cv2.putText(frame_usb,"Find {} faces".format(faces_list[-1]),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(0, 255, 0), 2)
cv2.putText(frame,"Press Q to save and quit",(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(0, 255, 0), 2)
cv2.imshow('frame', frame)
cv2.imshow("frame_usb find face", frame_usb)
endgo=time.time()
# conumber_list.append(round(endgo-start,1))
#conumber_list=list(set(conumber_list))
if str(int(endgo-start)) in number_list:
speak.Speak("监控视频导出成功")
speak.Speak('人脸识别视频导出成功')
out.write(frame)
out_usb.write(frame_usb)
elif int(endgo-start)>=36000:
speak.Speak('设定时间已到')
out.write(frame)
out_usb.write(frame_usb)
break
else:
print(str(int(endgo-start)))
time.sleep(0.5)
if cv2.waitKey(1) & 0xFF == ord('q'):
speak.Speak("监控视频导出成功")
speak.Speak('人脸识别视频导出成功')
break
cap.release()
cap_usb.release()
out.release()
out_usb.release()
read()
cv2.destroyAllWindows()
end=time.time()
speak.Speak('虚拟空间系统已经关闭,系统运行总共时间为{}秒'.format(int(end-startup)))
|