之前在做一个离开后人脸识别邮件提醒工具,经过多次构思增加了部分环节功能。目前流程如下:
1:使用 opencv摄像头人脸保存 提取使用者面部信息作为比对基础,可以存储多人数据,素材少时需要多采集几次
2:使用 摄像头人脸识别邮件发送 进行摄像头监控,如果前期已经做好面部素材采集,就可以长期挂着,未发现对电脑增加过多负担
下面代码为 opencv摄像头人脸保存。
需要注意文件路径 D:/get_capture_file/image/face_catalogue/5330000_wumingshi/
文件必须放在 D:/get_capture_file/下,image 是存放录像视频的,face_catalogue 存放人脸面部素材,
5330000_wumingshi 单个素材文件夹,前面 5330000是编码,wumingshi 是暂定名称,可以改为姓名拼音
dll 文件夹是放 pythoncom38.dll pywintypes38.dll
moxing 文件夹是放 haarcascade_eye.xml haarcascade_frontalface_default.xml
email_user.txt 文件内存放 发件人邮箱;密码;邮箱服务器;接收人邮箱
# opencv练习面部识别,通过截屏保存图像的方式保存使用。
# 屏幕像素大小,需要通过别的模块,练手就直接使用自己屏幕的了,如果想根据屏幕像素不同变动的,可以再添加。 pip install Pillow
# 另外既然截屏,就可以直接在图像读取后直接面部识别,节省一步保存转换的步骤。
# pyinstaller --onefile -F -w C:/Users/HONOR/PycharmProjects/pytorch/网络爬虫练习/文件夹目录/屏幕截取人脸增加人脸库/opencv摄像头人脸保存.py
# C:\Users\HONOR\PycharmProjects\pytorch\dist\opencv摄像头人脸保存.exe
import uuid,socket,time,os
import cv2
import numpy as np
#获取电脑设备号
def get_mac():
#mac
mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
# 获取主机名
hostname = socket.gethostname()
# 获取IP
ip = socket.gethostbyname(hostname)
# 屏幕分辨率为
# screen = ImageGrab.grab()
# width, height = screen.size
width, height = 640,480
# 结果数据字典
pc_mac = {'mac':mac,'hostname':hostname,'ip':ip,'width':width,'height':height}
# 结果数据导出
return pc_mac
# 时间计算
def get_current_time():
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
data_secs = abs(ct - round(ct)) * 1000
time_stamp = "%s%03d" % (data_head, data_secs)
return time_stamp
#调用摄像头
def get_capture(title,faceCascade,faceCascade_eye):
capture_1 = cv2.VideoCapture(1, cv2.CAP_DSHOW)
capture_0 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if capture_1.isOpened():
print('外设摄像头')
capture = cv2.VideoCapture(1, cv2.CAP_DSHOW)
elif capture_0.isOpened():
print('本机摄像头')
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
image_st = 0
while (capture.isOpened()):
retval, image = capture.read()
#调用人脸识别
faces_list,eye_list = Face_comparison(image,faceCascade,faceCascade_eye)
#print('faces_list',faces_list)
# 根据获取数量进行绘制外框
if len(faces_list) >= 1:
for (x, y, w, h) in faces_list:
#print('调用人脸识别',y,y + w, x,x + h)
# 根据获取数量进行绘制外框
# cv2.rectangle(image, (x -1, y -1), (x + w +1, y + h +1), (0, 0, 255), 1)
# 将图像区域转换为灰色
face_image = image[y:y + w, x:x + h]
#图像彩色转灰色化
face_gray = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)
# 图像灰色转彩色化
face_rgb = cv2.cvtColor(face_gray, cv2.COLOR_GRAY2RGB)
#图像替换
image[y:y + w, x:x + h] = face_rgb
# 字体样式
font = cv2.FONT_HERSHEY_TRIPLEX
# 字体系数
font_xs = round(image.shape[0] / 768, 2)
#图片左上角标记
cv2.putText(image,title,(5, 15), font, round(0.6 * font_xs, 1), (0, 0, 255))
#改变图片状态
image_st = 1
break
else:
break
return image
#人脸模型加载
def get_face_eye():
# 人脸
faceCascade = cv2.CascadeClassifier("D:\\get_capture_file\\moxing\\haarcascade_frontalface_default.xml")
# 眼睛
faceCascade_eye = cv2.CascadeClassifier("D:\\get_capture_file\\moxing\\haarcascade_eye.xml")
return faceCascade,faceCascade_eye
#人脸识别与眼睛识别
def Face_comparison(img,faceCascade,faceCascade_eye):
faces_list = []
eye_list = []
#转黑白图片
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#人脸识别
faces = faceCascade.detectMultiScale(gray,1.08)
#看数量
#print('faces',len(faces))
for (x, y, w, h) in faces:
#print('xywh', (x, y, w, h))
if w >= 30: # 图像宽超过50才保存,因为太小的误判可能性更大
cropped = gray[y:y + w, x:x + h]
# 加入眼睛识别,如果存在眼睛在保存
eye = faceCascade_eye.detectMultiScale(cropped, 1.08)
if len(eye) >= 1:
for (eye_x, eye_y, eye_w, eye_h) in eye:
if eye_w >= 1:
eye_list.append([eye_x + x, eye_y + y, eye_w, eye_h])
# print('eye_list', len(eye_list))
# print(eye_list)
faces_list.append([x, y, w, h])
return faces_list,eye_list
#人脸素材库加载,这个不动
def face_catalogue(catalogue):
#面部目录加载,每次读取图片加载一次太浪费效率
#cv2.face.LBPHFaceRecognizer_create() 需要 pip install opencv-contrib-python
photos = list()
lables = list()
file_name = {}
# 遍历上层目录
for root, dirs, files in os.walk(catalogue):
# 查看存在多少个子目录
if files == []:
#print('root', root, 'dirs', dirs, 'files', files)
for dir in dirs:
#print('dir',dir)
for root_son, dirs_son, files_son in os.walk(catalogue + "/%s" % dir):
#print('dir', dir, 'files', files_son)
dir_id = dir[0:7]
dir_name = dir[8:]
#print('dir_id', dir_id, 'dir_name', dir_name)
#增加字典
file_name[dir_id]=dir_name
#附件计数
file_num = 0
for file_son in files_son:
#print('file', catalogue + "/%s/%s" % (dir, file_son))
# img = cv2.imread(catalogue + "/%s/%s" % (dir, file_son), 0)
img = cv2.imdecode(np.fromfile(catalogue + "/%s/%s" % (dir, file_son), dtype=np.uint8), 0)
imga = cv2.resize(img, (200, 200))
photos.append(imga)
lables.append(int(dir_id))
file_num += 1
#print('序列号',dir,'素材数量:',file_num)
#print('文件数',set(lables),file_name)
model = cv2.face.LBPHFaceRecognizer_create()
model.train(photos, np.array(lables))
return model,file_name
#根据图片比对素材库相似度
def model_confidence(image,image_name):
image_st = image_name + ' 文件处理完成'
# 人脸模型加载
model, file_name = face_catalogue('D:/get_capture_file/image/face_catalogue')
print('file_name',file_name)
#取文件前七位最大数值化+1
nex_label = str(int(max(file_name.keys()))+1)
# 图片像素扩充与素材一致
cropped = cv2.resize(image, (200, 200))
# 相似度比对
label, confidence = model.predict(cropped)
print('相似度比对', label,file_name[str(label)], str(round(confidence,2)).replace('.','_'))
if confidence <= 50:
# 在相似文件夹内存放图片
image_st = image_st +' 相似度比对较高'
path_new = 'D:/get_capture_file/image/face_catalogue/'+str(label)+'_'+file_name[str(label)]+'/'+image_name+'.jpg'
cv2.imwrite(path_new,image)
else:
# 新创建一个文件夹存放该图片
image_st = image_st + ' 相似度比对较低'
path_new = 'D:/get_capture_file/image/face_catalogue/' + nex_label+'_wumingshi/' +image_name+'.jpg'
if os.path.exists('D:/get_capture_file/image/face_catalogue/'+nex_label+'_wumingshi/'):
cv2.imwrite(path_new, image)
else:
os.mkdir('D:/get_capture_file/image/face_catalogue/'+nex_label+'_wumingshi/')
cv2.imwrite(path_new, image)
return image_st
#图片人脸标准化存档,大小改为200*200,灰色,时间+第几个
def Face_image_save(image,faces,in_time):
image_dict = {}
i = 0
for (x, y, w, h) in faces:
i += 1
cropped_gray = cv2.resize(cv2.cvtColor(image[y:y + w, x:x + h], cv2.COLOR_BGR2GRAY),(200,200))
#图片名
image_name = in_time + '_' + str(i)
#print('image_name',image_name)
#cv2.imwrite(image_name,cropped_gray)
image_dict[image_name]=cropped_gray
return image_dict
#确认路径是否存在,不存在就创建
#D:\get_capture_file\image\face_catalogue\5330000_wumingshi
def path_exists():
path_new = 'D:/get_capture_file/image/face_catalogue/5330000_wumingshi/'
if os.path.exists(path_new) is False:
os.mkdir(path_new)
img_zero = np.zeros((200,200),np.uint8)
cv2.imwrite(path_new + '000.jpg', img_zero)
print('5330000_wumingshi:创建完成')
else:print('5330000_wumingshi:之前已存在')
dll_1 = 'D:/get_capture_file/dll/pythoncom38.dll'
dll_2 = 'D:/get_capture_file/dll/pywintypes38.dll'
dll_a = 'C:/Windows/System32/pythoncom38.dll'
dll_b = 'C:/Windows/System32/pywintypes38.dll'
if os.path.exists(dll_a) is False and os.path.exists(dll_1):
shutil.copyfile(dll_1, dll_a)
print(dll_a,'创建完成')
else:print(dll_a,'之前已存在')
if os.path.exists(dll_b) is False and os.path.exists(dll_2):
shutil.copyfile(dll_2, dll_b)
print(dll_b,'创建完成')
else:print(dll_b,'之前已存在')
if __name__ == '__main__':
# 获取系统数据
mac_id= get_mac()
# 展现数据
print('计算机参数展示', mac_id)
# 获取内容
mac, hostname, ip = mac_id['mac'],mac_id['hostname'],mac_id['ip']
width,height = mac_id['width'],mac_id['height']
#人脸模型与眼睛模型
faceCascade,faceCascade_eye = get_face_eye()
#录屏准备
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
in_time = get_current_time()
fps = 1
# 视频存档
# file_name = './image/avi'+in_time+'.avi'
# output = cv2.VideoWriter( file_name ,fourcc,fps,(width,height))
#创建转移文件
path_exists()
#循环次数
for i in range(100*fps):
#图片时间同步
in_time = get_current_time()
#获取屏幕截图
#image = get_hwnd_title()
#获取摄像头
image = get_capture(in_time,faceCascade,faceCascade_eye)
#人脸位置与眼睛位置获取
faces_list,eye_list = Face_comparison(image,faceCascade,faceCascade_eye)
print('人脸列表',faces_list)
# 视频存档:视频增加帧数
# output.write(image)
#图片加工存档,把保存环节去掉
image_dict = Face_image_save(image,faces_list,in_time)
#导出图片内容
print('image_dict',len(image_dict),image_dict.keys())
for image_name in image_dict.keys():
cropped = image_dict[image_name]
image_st = model_confidence(cropped,image_name)
print('相似度比对',image_st)
js_time = get_current_time()
print('js_time1',in_time, js_time)
time.sleep(0.1)
下面代码为 摄像头人脸识别邮件发送 部分
# 1调取摄像头,优先外接,其后自身摄像头
# 2按照时间保存图片,名称yyyymmddhh24miss
# 3邮件发送,邮箱固定,密码存在d盘txt文件
# #打包成exe文件
# pyinstaller --onefile -F -w C:/Users/HONOR/PycharmProjects/pytorch/网络爬虫练习/文件夹目录/摄像头人脸识别邮件发送v2.py
# C:\Users\HONOR\PycharmProjects\pytorch\dist\摄像头人脸识别邮件发送v2.exe
#
#
# pip install time
# pip install os
# pip install cv2 # pip install opencv-python
# pip install Pillow=6.2.1
# pip install numpy
# pip install smtplib
# pip install email
# pip install win32gui
# pip uninstall Pillow
# pip uninstall shutil
# 20230612
# 1、效率问题,用户名密码可以只在程序加载过程生成一次,每次读取文件,会浪费时间,不过影响不大。
# --------改成过程开始执行时读取,或为了更新用户名密码信息,可以设置轮询,比如100次循环读取一次。
# 2、时间问题,摄像头会存在长期无法探索到人脸而循环执行,过程一开始的时间会很不准确,可能半小时一小时都没有。
# --------改成摄像头探测到人脸再获取当前时间,影响不大。
# 3、资源问题,摄像头会存在长期无法探索到人脸而循环执行,占用cpu过大。
# --------设置未找到人脸自动停止30秒再启动,
# 4、视频时带上电脑屏幕截图、监控鼠标键盘操作、建立使用者面部库,当使用者不是本人时才会监控
# 20230615 后续增加功能:
# 摄像头人脸识别邮件发送v2.exe
# 1、判断 pythoncom38.dll pywintypes38.dll 是否存在,不存在 将 D:\get_capture_file\dll 文件夹下:pythoncom38.dll pywintypes38.dll 复制到 C:\Windows\System32\ 路径下。
# 2、在过程里增加对 D:\get_capture_file\image\face_catalogue 人脸素材的相似度比对,大于50以上的进行视频留存发送。
# 3、判断 D:\get_capture_file\image\face_catalogue\5330000_wumingshi 是否存在,不存在进行创建,并保留一张素材图片。
import time,os,cv2
import smtplib #发送邮件模块
from email.mime.text import MIMEText #定义邮件内容
from email.mime.multipart import MIMEMultipart #用于传送附件
from email.header import Header
from email.utils import formataddr
#增加屏幕截屏功能
import win32gui
from PyQt5.QtWidgets import QApplication
import numpy as np
import sys
import shutil
#第一步获取正常登陆的邮箱名称等信息
def get_email_user(text_list):
if len(text_list) != 4:
user = 'xxx@163.com'
password = 'xxx'
smtpserver = 'smtp.163.com'
receives = 'xxx@139.com'
else:
user,password,smtpserver,receives = text_list
user_dict ={'user':user,'password':password,'smtpserver':smtpserver,'receives':receives}
return user_dict
#邮件推送
def email_out(user,password,smtpserver,sender,receives,title,content,send_file):
'''
:param user: 发送邮箱用户名
:param password:发送邮箱密码
:param smtpserver:发送服务器
:param sender:发送方邮箱
:param receives:接收方邮箱
:param title:邮件标题
:param content:邮件正文
:param send_file:邮件附件
:return:
'''
#提取当前日期
in_time = get_today_time()
#获取文件后缀
tuple_text = os.path.splitext(send_file)
#print('tuple_text',tuple_text[1])
# 发送邮件主题和内容
subject = title
#文字描述中 \n 替换成 <br/>,头尾
content_head = '<html><strong>尊敬的领导,您好:</strong><br/><br/> '
content_tail = '<br/><h4> 此致<br/>敬礼<br/></h4> <div align=right> <strong> xxx经营部业务支撑中心 </strong> </div>'
content_new = content_head + content.replace('\\n','<br/>').replace('^', ' ') + content_tail
send_file_path = open(send_file, 'rb').read() # 'rb'表示r读取,b表示二进制方式读取
att = MIMEText(send_file_path, 'base64', 'utf-8') # 调用传送附件模块,传送附件
att["Content-Type"] = 'application/octet-stream'
# file_name 主题名加原来文件名后缀
file_name = title + '_' + in_time[0:8] + tuple_text[1]
att["Content-Disposition"] = 'attachment;filename=%s' % Header(file_name,'utf-8').encode() # 附件描述外层要用单引号
# 构建发送与接收信息
msgRoot = MIMEMultipart() # 发送附件的方法定义为一个变量
msgRoot.attach(MIMEText(content_new, 'html', 'utf-8')) # 发送附件的方法中嵌套发送正文的方法
msgRoot['subject'] = subject
#接收人显示内容
msgRoot['From'] = formataddr((Header("淄博业支中心", 'utf-8').encode(), sender))
#msgRoot['From'] = sender #显示发送人邮箱
#msgRoot['From'] ='xxx@sd.xxx.com' #可以设置接收者看到的发送人邮箱
msgRoot['Bcc'] = receives
msgRoot.attach(att) # 添加附件到正文中
# SSL协议端口号要使用465
smtp = smtplib.SMTP_SSL(smtpserver, 465)
# HELO 向服务器标识用户身份
smtp.helo(smtpserver)
# 服务器返回结果确认
smtp.ehlo(smtpserver)
# 登录邮箱服务器用户名和密码
smtp.login(user, password)
smtp.sendmail(sender, receives, msgRoot.as_string())
smtp.quit()
return "发送成功"
#今天时间计算
def get_today_time():
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
data_secs = abs(ct - round(ct)) * 1000
time_stamp = "%s%03d" % (data_head, data_secs)
return time_stamp
#图像人脸识别
def Face_comparison(img):
faces_list = []
eye_list = []
#转黑白图片
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#人脸识别
faces = faceCascade.detectMultiScale(gray,1.08)
#看数量
for (x, y, w, h) in faces:
#print('xywh', (x, y, w, h))
if w >= 30: # 图像宽超过30才保存,因为太小的误判可能性更大
cropped = gray[y:y + w, x:x + h]
# 加入眼睛识别,如果存在眼睛在保存
eye = faceCascade_eye.detectMultiScale(cropped, 1.08)
#print('eye', eye)
if len(eye) > 0:
for (eye_x, eye_y, eye_w, eye_h) in eye:
if eye_w >= 1:
eye_list.append([eye_x + x, eye_y + y, eye_w, eye_h])
#print('eye_list', len(eye_list))
faces_list.append([x, y, w, h])
return faces_list,eye_list
#调用摄像头
def get_capture(title):
capture_1 = cv2.VideoCapture(1, cv2.CAP_DSHOW)
capture_0 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if capture_1.isOpened():
print('外设摄像头')
capture = cv2.VideoCapture(1, cv2.CAP_DSHOW)
elif capture_0.isOpened():
print('本机摄像头')
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
image_st = 0
while (capture.isOpened()):
retval, image = capture.read()
#调用人脸识别
faces_list,eye_list = Face_comparison(image)
#print('faces_list',faces_list)
# 根据获取数量进行绘制外框
if len(faces_list) >= 1:
for (x, y, w, h) in faces_list:
#print('调用人脸识别',y,y + w, x,x + h)
# 根据获取数量进行绘制外框
# cv2.rectangle(image, (x -1, y -1), (x + w +1, y + h +1), (0, 0, 255), 1)
# 将图像区域转换为灰色
face_image = image[y:y + w, x:x + h]
#图像彩色转灰色化
face_gray = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)
#*********人脸素材库比对,小于50不发送提醒************
# 人脸模型加载
model, file_name = face_catalogue('D:/get_capture_file/image/face_catalogue')
# 图片像素扩充与素材一致
cropped = cv2.resize(face_gray, (200, 200))
# 相似度比对
label, confidence = model.predict(cropped)
print('相似度比对', label, file_name[str(label)], str(round(confidence, 2)).replace('.', '_'))
#相似度比对
if confidence <= 50: # 小于50可以认定同一人,本人在场就不提醒了
image_st -= 10
break
else: #大于50发送邮件
pass
# 图像灰色转彩色化
face_rgb = cv2.cvtColor(face_gray, cv2.COLOR_GRAY2RGB)
#图像替换
image[y:y + w, x:x + h] = face_rgb
# 字体样式
font = cv2.FONT_HERSHEY_TRIPLEX
# 字体系数
font_xs = round(image.shape[0] / 768, 2)
#图片左上角标记
cv2.putText(image,title,(5, 15), font, round(0.6 * font_xs, 1), (0, 0, 255))
#改变图片状态
image_st += 1
break
else:
break
return image,image_st,capture
#录制视频
def get_video(title,height,width,image_old):
capture_1 = cv2.VideoCapture(1, cv2.CAP_DSHOW)
capture_0 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if capture_1.isOpened():
print('外设摄像头')
capture = cv2.VideoCapture(1, cv2.CAP_DSHOW)
elif capture_0.isOpened():
print('本机摄像头')
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
#title文件名前缀,h高度,w宽度
send_file = 'D:/get_capture_file/image/' + title + '.mp4'
video = cv2.VideoWriter(send_file, cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), 10, (width*2, height))
#封面图片 image_old 写入视频内
for i in range(1, 5):
# 屏幕截图
img_cv = cv2.resize(get_hwnd_title(),(width, height))
image_old = np.hstack((image_old, img_cv))
video.write(image_old)
while (capture.isOpened()):
print('get_video', str(round(0 / (10 * 20) * 100, 2)) + '%')
for i in range(1, 10 * 20):
retval, image = capture.read()
if (i+1) % 50 == 0:print('get_video',str(round((i+1)/(10 * 20)*100,2))+'%')
# 屏幕截图
img_cv = cv2.resize(get_hwnd_title(), (width, height))
image = cv2.resize(image, (width, height))
image = np.hstack((image, img_cv))
video.write(image)
time.sleep(0.02)
break
return send_file
#文本获取,用于邮箱信息读取
def email_user():
with open('D:\\get_capture_file\\email_user.txt','r') as file:
text = file.readlines()[0]
text_list = text.split(';')
return text_list
def convertQImageToMat(incomingImage):
incomingImage = incomingImage.convertToFormat(4)
width = incomingImage.width()
height = incomingImage.height()
ptr = incomingImage.bits()
ptr.setsize(incomingImage.byteCount())
arr = np.array(ptr).reshape(height, width, 4)
return arr
#屏幕截图
def get_hwnd_title():
hwnd_title = dict()
def get_all_hwnd(hwnd,mouse):
if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})
win32gui.EnumWindows(get_all_hwnd,0)
# 程序会打印窗口的hwnd和title,有了title就可以进行截图了。
hwnd = win32gui.FindWindow(None, 'C:\Windows\system32\cmd.exe')
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img_qt = screen.grabWindow(hwnd).toImage()
#pyqt5转PIL
new_image=convertQImageToMat(img_qt)#将获取的图像从QImage转换为RBG格式
# PIL转换opencv
img_cv = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
return img_cv
#人脸素材库加载,这个不动
def face_catalogue(catalogue):
#面部目录加载,每次读取图片加载一次太浪费效率
#cv2.face.LBPHFaceRecognizer_create() 需要 pip install opencv-contrib-python
photos = list()
lables = list()
file_name = {}
# 遍历上层目录
for root, dirs, files in os.walk(catalogue):
# 查看存在多少个子目录
if files == []:
#print('root', root, 'dirs', dirs, 'files', files)
for dir in dirs:
#print('dir',dir)
for root_son, dirs_son, files_son in os.walk(catalogue + "/%s" % dir):
#print('dir', dir, 'files', files_son)
dir_id = dir[0:7]
dir_name = dir[8:]
#print('dir_id', dir_id, 'dir_name', dir_name)
#增加字典
file_name[dir_id]=dir_name
#附件计数
file_num = 0
for file_son in files_son:
#print('file', catalogue + "/%s/%s" % (dir, file_son))
# img = cv2.imread(catalogue + "/%s/%s" % (dir, file_son), 0)
img = cv2.imdecode(np.fromfile(catalogue + "/%s/%s" % (dir, file_son), dtype=np.uint8), 0)
imga = cv2.resize(img, (200, 200))
photos.append(imga)
lables.append(int(dir_id))
file_num += 1
#print('序列号',dir,'素材数量:',file_num)
#print('文件数',set(lables),file_name)
model = cv2.face.LBPHFaceRecognizer_create()
model.train(photos, np.array(lables))
return model,file_name
#确认路径是否存在,不存在就创建
#D:\get_capture_file\image\face_catalogue\5330000_wumingshi
def path_exists():
path_new = 'D:/get_capture_file/image/face_catalogue/5330000_wumingshi/'
if os.path.exists(path_new) is False:
os.mkdir(path_new)
img_zero = np.zeros((200,200),np.uint8)
cv2.imwrite(path_new + '000.jpg', img_zero)
print('5330000_wumingshi:创建完成')
else:print('5330000_wumingshi:之前已存在')
dll_1 = 'D:/get_capture_file/dll/pythoncom38.dll'
dll_2 = 'D:/get_capture_file/dll/pywintypes38.dll'
dll_a = 'C:/Windows/System32/pythoncom38.dll'
dll_b = 'C:/Windows/System32/pywintypes38.dll'
if os.path.exists(dll_a) is False and os.path.exists(dll_1):
shutil.copyfile(dll_1, dll_a)
print(dll_a,'创建完成')
else:print(dll_a,'之前已存在')
if os.path.exists(dll_b) is False and os.path.exists(dll_2):
shutil.copyfile(dll_2, dll_b)
print(dll_b,'创建完成')
else:print(dll_b,'之前已存在')
if __name__ == '__main__':
#加载人脸模型
faceCascade = cv2.CascadeClassifier("D:\\get_capture_file\\moxing\\haarcascade_frontalface_default.xml")
faceCascade_eye = cv2.CascadeClassifier("D:\\get_capture_file\\moxing\\haarcascade_eye.xml")
#获取用户名密码
text_list = email_user()
print('用户信息:', text_list)
user_dict = get_email_user(text_list)
# print('user_dict:', user_dict)
user, password, smtpserver, receives = user_dict['user'], user_dict['password'], user_dict['smtpserver'], user_dict['receives']
#创建转移文件
path_exists()
# 循环执行
while True:
#定义休息时间
sleeps = 2
day = get_today_time()
#print('day:',day)
#邮件名称与附件名
title = 'Face_comparison_'+day
send_file='D:/get_capture_file/image/'+ title+'.jpg'
# 加载摄像头,判断是外摄像还是自备
image,image_st,capture = get_capture(title)
print('get_capture_image_st', image_st)
#图片状态1为有效
if image_st >= 1:
#录制之后30秒不记录
sleeps = 120
# 获取图像尺寸
height, width, channels = image.shape
send_file = get_video(title,height,width,image)
print('video_file',send_file)
#邮件发送
email_st = '默认状态'
try:email_st = email_out(user,password,smtpserver,user,receives,title,title,send_file)
except:email_st = '发送异常'
print('email_st',email_st)
else:print('图片状态为无效')
#等待时间,失败反馈
try:time.sleep(sleeps)
except:pass