20230601_python练习_调用摄像头做人脸检测后通过邮件发送图片

'''
1调取摄像头,优先外接,其后自身摄像头
2按照时间保存图片,名称yyyymmddhh24miss
3邮件发送,邮箱固定,密码存在d盘txt文件
'''
import time,os,cv2
from PIL import Image, ImageEnhance
import numpy as np
import smtplib                                  #发送邮件模块
from email.mime.text import MIMEText            #定义邮件内容
from email.mime.multipart import MIMEMultipart  #用于传送附件
from email.header import Header
from email.utils import formataddr

#第一步获取正常登陆的邮箱名称等信息
def get_email_user(text_list):
    if len(text_list) != 4:
        user = '[email protected]'
        password = 'xxxx'
        smtpserver = 'smtp.163.com'
        receives = '[email protected]'
    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 替换成 
,头尾 content_head = '尊敬的领导,您好:

        ' content_tail = '

        此致
敬礼

支撑中心
' content_new = content_head + content.replace('\\n','
').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'] ='[email protected]' #可以设置接收者看到的发送人邮箱 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.1) #看数量 for (x, y, w, h) in faces: #print('xywh', (x, y, w, h)) if w >= 10: # 图像宽超过10才保存,因为太小的误判可能性更大 cropped = gray[y:y + w, x:x + h] # 加入眼睛识别,如果存在眼睛在保存 eye = faceCascade_eye.detectMultiScale(cropped, 1.1) 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): #print('title',title) capture_1 = cv2.VideoCapture(1, cv2.CAP_DSHOW) capture_0 = cv2.VideoCapture(0, cv2.CAP_DSHOW) if capture_1.isOpened(): capture = cv2.VideoCapture(1, cv2.CAP_DSHOW) elif capture_0.isOpened(): capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) while (capture.isOpened()): retval, image = capture.read() #人脸图片锐化函数调用 image = get_image_enhance(image) #调用人脸识别 faces_list,eye_list = Face_comparison(image) # 根据获取数量进行绘制外框 if len(faces_list) >= 1: for (x, y, w, h) in faces_list: cv2.rectangle(image, (x -1, y -1), (x + w +1, y + h +1), (0, 0, 255), 1) # 字体样式 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)) break else: continue time.sleep(0.3) return image #文本获取,用于邮箱信息读取 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 get_image_enhance(img_cv): # opencv转换PIL img_pil = Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)) # 增强锐度 sharpness = ImageEnhance.Sharpness(img_pil) img_pil = sharpness.enhance(1.5) # 设置增强因子 enhancer = ImageEnhance.Sharpness(img_pil) factor = 2.0 # 增强图片 img_pil = enhancer.enhance(factor) # PIL转换opencv img_cv = cv2.cvtColor(np.asarray(img_pil), cv2.COLOR_RGB2BGR) #返回opencv图片 return img_cv 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") # 循环执行 while True: text_list = email_user() print('text:',text_list) day = get_today_time() #print('day:',day) 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'] #邮件名称与附件名 title = 'Face_comparison_'+day send_file='D:/get_capture_file/image/'+ title+'.jpg' #调用 # 加载摄像头,判断是外摄像还是自备 image = get_capture(title) #将图片存入文件内 print('send_file',send_file) cv2.imwrite(send_file, image) # 获取图像尺寸 height, width, channels = image.shape print(height, width) #邮件发送 email_st = '默认状态' try:email_st = email_out(user,password,smtpserver,user,receives,title,title,send_file) except:email_st = '发送异常' print('email_st',email_st) #失败反馈 try:time.sleep(30) except:pass

你可能感兴趣的:(python,开发语言)