笔记(二)face_recognition人脸识别代码分析

一、逻辑分析

 1、逻辑一:

 门禁状态state=0(正常)1(常开)2(常闭)3(仅管理员模式)4(禁止访客开门)

人员身份role=1(Admin管理员)2(User用户)3(Guest访客)

不允许一个人在一分钟内连续开门

2、逻辑二:

门禁状态state=0(正常)1(常开)2(常闭)3(仅管理员模式)4(禁止访客开门)

人员身份role=1(Admin管理员)2(User用户)3(Guest访客)

不允许一个人在五分钟内连续开门

二、代码块分析:

1.加载文件夹中的图片:

def scan_known_people(known_people_folder):
    for file in image_files_in_folder(known_people_folder):
        d = os.path.basename(file)
        basename = os.path.splitext(d)[0]
        if basename in known_face_names:
            break       
        #print(d)#图片名加后缀
        #print(basename)#图片名
        img = face_recognition.load_image_file(file)
        encodings = face_recognition.face_encodings(img)
        known_face_names.append(basename)#任务名称的集合
        known_face_encodings.append(encodings[0])#已知人脸的编码集合
    return known_face_names, known_face_encodings

2. 后续在显示过程中发现人脸识别后不能正确显示汉字,然后就加了下面这个函数,后续显示的时候直接调用就行

def cv2ImgAddText(img,text,left,top,textColor,textSize):
    if(isinstance(img,np.ndarray)):
        img=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
    draw =ImageDraw.Draw(img)
    ttf="/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"     #linux中的中文字体格式一般在/usr/share/fonts/opentype/noto下
    fontStyle=ImageFont.truetype(
    ttf,textSize,encoding="utf-8")
    draw.text((left,top),text,textColor,font=fontStyle)
    return cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)

3.门禁状态state=0正常时,识别出已知人脸则将人脸信息和时间写入文件并开门,否则关门

def rolezero(facename,name):#正常
	start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):
        doorState = "open"
        nameandtime = {"name":namenum,"timestamp":timenow}
        with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
            p.write(json.dumps(nameandtime)+"\n")
        else:
            doorState = "close"
    return doorState

4.门禁状态state=1常开时,识别出已知人脸则将人脸信息和时间存入文档,若识别出未知人脸则将人脸id设为0再与时间一同存入文件,门设为开

def roleone(facename,name):#常开
    start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):namenum = namenum
    else:namenum = 0#识别出未知传送0
    nameandtime = {"name":namenum,"timestamp":timenow}
    with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
        p.write(json.dumps(nameandtime)+"\n")
    return doorState

5.门禁状态state=3仅管理员可开门时,判断识别出的人脸是否是管理员,若是则存入信息同时开门,若不是则关门

def rolethree(facename,name,c,b):#仅管理员可开门
    start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):
        #循环userid的数组确定对应的role
        key = len(c)-1
        while(key>=0):
            if(c[key]==namenum):
                idrole = b[key]
                break
            key =key-1
        if(idrole == 1):
            nameandtime = {"name":namenum,"timestamp":timenow}
            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                p.write(json.dumps(nameandtime)+"\n")
            doorState = "open"
        else:doorState = "close"
    else:doorState = "close"
    return doorState

6.门禁状态state=4禁止访客访问状态时,若识别出的人脸已知且不是访客则存入信息且开门,若是则关门

def rolefour(facename,name,c,b):
	start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):
        #循环userid的数组确定对应的role
        key = len(c)-1
        while(key>=0):
            if(c[key]==namenum):
                idrole = b[key]
                break
            key =key-1
        if(idrole == 1 or 2):
            nameandtime = {"name":namenum,"timestamp":timenow}
            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                p.write(json.dumps(nameandtime)+"\n")
            doorState = "open"
        else:doorState = "close"
    else:doorState = "close"
    return doorState

三、完整代码

逻辑一的代码: 

import face_recognition
import cv2
import numpy as np
import os
import os.path
import itertools
import multiprocessing
from PIL import Image,ImageDraw,ImageFont
from face_recognition.face_recognition_cli import image_files_in_folder
import time 
import datetime
import re
import face_recognition.api as face_recognition
import sys
import json

# 初始化一些变量
face_locations = []
face_encodings = []
face_names = []
known_people_folder = r'/home/simon/mqtt/picture'
known_face_names = []
known_face_encodings = []

b = []#role:1(Admin管理员)2(User用户)3(Guest访客)
c = []#userid
doorState = "close"#门的状态
idrole = 0#初始化由userid查找出的对应role
with open("/home/simon/mqtt/"+"shadow.ini","r") as mj: 
    mess = mj.read()
    mess_parsed = json.loads(mess)
    state_f = mess_parsed['payload']['state']['reported']['state']
    state = int(state_f)  #门禁状态state=0(正常)1(常开)2(常闭)3(仅管理员模式)4(禁止访客开门)
    facelist = mess_parsed['payload']['state']['reported']['faceList']
    for i in facelist:
        role = i['role']
        userid = i['userId']
        b.append(int(role))
        c.append(int(userid))#将role和userid对应存起来

#加载文件夹中的图片
def scan_known_people(known_people_folder):
    for file in image_files_in_folder(known_people_folder):
        d = os.path.basename(file)
        basename = os.path.splitext(d)[0]
        if basename in known_face_names:
            break       
        #print(d)#图片名加后缀
        #print(basename)#图片名
        img = face_recognition.load_image_file(file)
        encodings = face_recognition.face_encodings(img)
        known_face_names.append(basename)#任务名称的集合
        known_face_encodings.append(encodings[0])#已知人脸的编码集合
    return known_face_names, known_face_encodings

def cv2ImgAddText(img,text,left,top,textColor,textSize):
    if(isinstance(img,np.ndarray)):
        img=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
    draw =ImageDraw.Draw(img)
    ttf="/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"     #linux中的中文字体格式一般在/usr/share/fonts/opentype/noto下
    fontStyle=ImageFont.truetype(
    ttf,textSize,encoding="utf-8")
    draw.text((left,top),text,textColor,font=fontStyle)
    return cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)

def rolezero(facename,name):#正常
	start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):
        doorState = "open"
        nameandtime = {"name":namenum,"timestamp":timenow}
        with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
            p.write(json.dumps(nameandtime)+"\n")
        else:
            doorState = "close"
    return doorState

def roleone(facename,name):#常开
    start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):namenum = namenum
    else:namenum = 0#识别出未知传送0
    nameandtime = {"name":namenum,"timestamp":timenow}
    with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
        p.write(json.dumps(nameandtime)+"\n")
    return doorState

def rolethree(facename,name,c,b):#仅管理员可开门
    start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):
        #循环userid的数组确定对应的role
        key = len(c)-1
        while(key>=0):
            if(c[key]==namenum):
                idrole = b[key]
                break
            key =key-1
        if(idrole == 1):
            nameandtime = {"name":namenum,"timestamp":timenow}
            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                p.write(json.dumps(nameandtime)+"\n")
            doorState = "open"
        else:doorState = "close"
    else:doorState = "close"
    return doorState

def rolefour(facename,name,c,b):
	start = time.time()
    namestart = facename
    timenow = int(round(start*1000))
    namenum = re.sub("\D","",name)#只传id
    #识别出的人脸已知时保存数据
    if(namenum):
        #循环userid的数组确定对应的role
        key = len(c)-1
        while(key>=0):
            if(c[key]==namenum):
                idrole = b[key]
                break
            key =key-1
        if(idrole == 1 or 2):
            nameandtime = {"name":namenum,"timestamp":timenow}
            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                p.write(json.dumps(nameandtime)+"\n")
            doorState = "open"
        else:doorState = "close"
    else:doorState = "close"
    return doorState

def face():
    #获取对网络摄像头 #0 的引用(默认)
    video_capture = cv2.VideoCapture(0)
    global idrole
    namestart = "未知"
    start = time.time()
    process_this_frame = True
    print("state:")
    print(state)
    while True:
        ret, frame = video_capture.read()# 抓取一帧视频
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)# 将视频帧调整为 1/4 大小以加快人脸识别处理
        rgb_small_frame = small_frame[:, :, ::-1] # 将图像从 BGR 颜色(OpenCV 使用的)转换为 RGB 颜色(face_recognition 使用的)
        # 只处理每隔一帧的视频以节省时间
        known_face_names, known_face_encodings = scan_known_people(known_people_folder)#加载文件夹中的图片   
        if process_this_frame:
            # 查找当前视频帧中的所有人脸和人脸编码/根据encoding来判断是不是同一个人,是就输出true,不是为false
            face_locations = face_recognition.face_locations(rgb_small_frame)#获得所有人脸位置
            if face_locations:
                face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)#获得人脸特征值
                face_names = []#存储出现在画面中人脸的名字
                for face_encoding in face_encodings:
                    # 查看人脸是否与已知人脸匹配/默认为unknown
                    matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                    facename = "未知"
                    name = facename.encode("utf-8").decode("utf-8") #转为汉字 
                    end = time.time()
                    # 如果在 known_face_encodings 中找到匹配,则使用与新人脸距离最小的已知人脸
                    face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                    best_match_index = np.argmin(face_distances)
                    if matches[best_match_index]:
                        facename = known_face_names[best_match_index]
                        name = facename.encode("utf-8").decode("utf-8") #转为汉字 
                        end = time.time()
                    face_names.append(facename)
                    now_time=datetime.datetime.now()
                    nowtime = datetime.datetime.strftime(now_time,'%Y-%m-%d %H:%M:%S') 
                    #根据state来判断门禁模式
                    if(state==0):#正常
                        #识别出的人脸有变化
                        if (facename != namestart):
                        	doorState = rolezero(facename,name)
                        #识别出的人脸没有变化时,不会连续发送,至少要过60秒
                        elif((end-start)>=60):
                        	doorState = rolezero(facename,name)
                        else:doorState = "close"
                    if(state==1):#常开
                        doorState = "open"
                        if (facename != namestart):
                        	doorState = roleone(facename,name)
                        #识别出的人脸没有变化时,不会连续发送,至少要过60秒
                        elif((end-start)>=60):
                        	doorState = roleone(facename,name)
                    if(state==2):#常闭
                        doorState = "close"
                    if(state==3):#仅管理员可开门
                        #识别出的人脸有变化
                        if (facename != namestart):
                        	doorState = rolethree(facename,name,c,b)                          
                        #识别出的人脸没有变化时,不会连续发送,至少要过60秒
                        elif((end-start)>=60):
                            doorState = rolethree(facename,name,c,b) 
                        else:doorState = "close"
                    if(state==4):#禁止访客开门
                        #识别出的人脸有变化
                        if (facename != namestart):
                        	doorState = rolefour(facename,name,c,b)
                        #识别出的人脸没有变化时,不会连续发送,至少要过60秒
                        elif((end-start)>=60):
                            doorState = rolefour(facename,name,c,b)
                        else:doorState = "close"

                # 显示结果
                for (top, right, bottom, left), facename in zip(face_locations, face_names):
                    # 缩放人脸位置,因为我们检测到的帧被缩放到 1/4 大小
                    top *= 4
                    right *= 4
                    bottom *= 4
                    left *= 4
                    cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)# 在脸部周围画一个框
                    # 在人脸下方画一个带有名字的标签
                    cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)          
                    if(doorState=="open"):
                        nameAndtime = name + '   ' + nowtime + '   ' + "door:" + doorState
                    else:
                        nameAndtime = name + '   ' + nowtime + '   ' 
                    #print(name)            
                    img = cv2ImgAddText(frame, nameAndtime, (left + 6), (bottom - 30), (255, 255, 255), 20)#调用的函数
                    cv2.imshow('Video', img)# 显示结果图像
            else:
                cv2.imshow("Video",frame)
        process_this_frame = not process_this_frame#不知道什么作用,感觉有点防抖动的意思
        if cv2.waitKey(1) & 0xFF == ord('q'):# 按键盘上的“q”退出!
            break      

    # 释放网络摄像头的句柄
    video_capture.release()
    cv2.destroyAllWindows()

if __name__=="__main__":
    face()

 逻辑二的代码:

import face_recognition
import cv2
import numpy as np
import os
import os.path
import itertools
import multiprocessing
from PIL import Image,ImageDraw,ImageFont
from face_recognition.face_recognition_cli import image_files_in_folder
import time 
import datetime
import re
import face_recognition.api as face_recognition
import sys
import json

# 初始化一些变量
face_locations = []
face_encodings = []
face_names = []
known_people_folder = r'/home/simon/mqtt/picture'
known_face_names = []
known_face_encodings = []

b = []#role:1(Admin管理员)2(User用户)3(Guest访客)
c = []#userid
t = []#存进门的时间戳
doorState = "close"#门的状态
idrole = 0#初始化由userid查找出的对应role
with open("/home/simon/mqtt/"+"shadow.ini","r") as mj: 
    mess = mj.read()
    mess_parsed = json.loads(mess)
    state_f = mess_parsed['payload']['state']['reported']['state']
    state = int(state_f)  #门禁状态state=0(正常)1(常开)2(常闭)3(仅管理员模式)4(禁止访客开门)
    facelist = mess_parsed['payload']['state']['reported']['faceList']
    start = time.time()
    for i in facelist:
        role = i['role']
        userid = i['userId']
        b.append(int(role))
        c.append(int(userid))#将role和userid对应存起来
        t.append(int(0))#将进门的时间戳和userid对应存起来,初始时间戳都设为int(0)

#加载文件夹中的图片
def scan_known_people(known_people_folder):
    for file in image_files_in_folder(known_people_folder):
        d = os.path.basename(file)#图片名加后缀
        basename = os.path.splitext(d)[0]#图片名
        if basename in known_face_names:
            break       
        img = face_recognition.load_image_file(file)
        encodings = face_recognition.face_encodings(img)
        known_face_names.append(basename)#任务名称的集合
        known_face_encodings.append(encodings[0])#已知人脸的编码集合
    return known_face_names, known_face_encodings

def cv2ImgAddText(img,text,left,top,textColor,textSize):
    if(isinstance(img,np.ndarray)):
        img=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
    draw =ImageDraw.Draw(img)
    ttf="/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" #linux中的中文字体格式一般在/usr/share/fonts/opentype/noto下
    fontStyle=ImageFont.truetype(ttf,textSize,encoding="utf-8")
    draw.text((left,top),text,textColor,font=fontStyle)
    return cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)

def face():
    #获取对网络摄像头 #0 的引用(默认)
    video_capture = cv2.VideoCapture(0)
    #global idrole
    namestart = "未知"
    start = time.time()
    process_this_frame = True
    shibie_frame = False#用来在屏幕上显示开门
    print("state:")
    print(state)
    while True:
        ret, frame = video_capture.read()# 抓取一帧视频
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)# 将视频帧调整为 1/4 大小以加快人脸识别处理
        rgb_small_frame = small_frame[:, :, ::-1] # 将图像从 BGR 颜色(OpenCV 使用的)转换为 RGB 颜色(face_recognition 使用的)
        # 只处理每隔一帧的视频以节省时间
        known_face_names, known_face_encodings = scan_known_people(known_people_folder)#加载文件夹中的图片   
        if process_this_frame:
            # 查找当前视频帧中的所有人脸和人脸编码/根据encoding来判断是不是同一个人,是就输出true,不是为false
            face_locations = face_recognition.face_locations(rgb_small_frame)#获得所有人脸位置
            if face_locations:
                face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)#获得人脸特征值
                face_names = []#存储出现在画面中人脸的名字
                for face_encoding in face_encodings:
                    # 查看人脸是否与已知人脸匹配/默认为unknown
                    matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                    facename = "未知"
                    name = facename.encode("utf-8").decode("utf-8") #转为汉字 
                    #end = time.time()
                    # 如果在 known_face_encodings 中找到匹配,则使用与新人脸距离最小的已知人脸
                    face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                    best_match_index = np.argmin(face_distances)
                    if matches[best_match_index]:
                        facename = known_face_names[best_match_index]
                        name = facename.encode("utf-8").decode("utf-8") #转为汉字 
                        #end = time.time()
                    face_names.append(facename)
                    now_time=datetime.datetime.now()
                    nowtime = datetime.datetime.strftime(now_time,'%Y-%m-%d %H:%M:%S') 
                    if(state==0):#正常
                        now = time.time()
                        namestart = facename
                        timenow = int(round(now*1000))#ms级时间戳
                        namenum = re.sub("\D","",name)#只传id
                        #识别出的人脸已知时保存数据
                        if(namenum):
                            #循环userid的数组确定对应的时间戳
                            key1 = len(c)-1
                            while(key1>=0):
                                if(c[key1]==int(namenum)):
                                    if(t[key1]==int(0)):#第一次进门
                                        nameandtime = {"name":namenum,"timestamp":timenow}
                                        with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                            p.write(json.dumps(nameandtime)+"\n")
                                        doorState = "open"
                                        shibie_frame = True
                                        t[key1] = timenow#更新时间戳
                                    else:#不是第一次进门
                                        itime = t[key1]
                                        #判断当前人员与前一次进门是否相差规定时间
                                        if((timenow-itime)>=360000):#5分钟内不能重复识别#1秒相差1200
                                            nameandtime = {"name":namenum,"timestamp":timenow}
                                            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                                p.write(json.dumps(nameandtime)+"\n")
                                            doorState = "open"
                                            shibie_frame = True
                                            t[key1] = timenow#更新时间戳
                                        else:
                                            doorState = "close"
                                            shibie_frame = False
                                    break
                                key1 =key1-1
                        else:
                            doorState = "close"
                            shibie_frame = False
                    if(state==1):#常开
                        doorState = "open"
                        start = time.time()
                        namestart = facename
                        timenow = int(round(start*1000))
                        namenum = re.sub("\D","",name)#只传id
                        #识别出的人脸已知时保存数据
                        if(namenum):namenum = namenum
                        else:namenum = 0#识别出未知传送0
                        #循环userid的数组确定对应的时间戳
                        key1 = len(c)-1
                        while(key1>=0):
                            if(c[key1]==int(namenum)):
                                if(t[key1]==int(0)):#第一次进门
                                    nameandtime = {"name":namenum,"timestamp":timenow}
                                    with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                        p.write(json.dumps(nameandtime)+"\n")
                                    doorState = "open"
                                    shibie_frame = True
                                    t[key1] = timenow#更新时间戳
                                else:#不是第一次进门
                                    itime = t[key1]
                                    #判断当前人员与前一次进门是否相差规定时间
                                    if((timenow-itime)>=360000):
                                        nameandtime = {"name":namenum,"timestamp":timenow}
                                        with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                            p.write(json.dumps(nameandtime)+"\n")
                                        doorState = "open"
                                        shibie_frame = True
                                        t[key1] = timenow#更新时间戳
                                    else:shibie_frame = False
                                break
                            key1 =key1-1
                    if(state==2):#常闭
                        doorState = "close"
                        shibie_frame = False
                    if(state==3):#仅管理员可开门
                        start = time.time()
                        namestart = facename
                        timenow = int(round(start*1000))
                        namenum = re.sub("\D","",name)#只传id
                        #识别出的人脸已知时保存数据
                        if(namenum):
                            #循环userid的数组确定对应的role和时间戳
                            key1 = len(c)-1
                            while(key1>=0):
                                if(c[key1]==int(namenum)):
                                    idrole = b[key1]
                                    itime = t[key1]
                                    if(idrole==int(1)):
                                        if(itime==int(0)):#第一次进门
                                            nameandtime = {"name":namenum,"timestamp":timenow}
                                            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                                p.write(json.dumps(nameandtime)+"\n")
                                            doorState = "open"
                                            shibie_frame = True
                                            t[key1] = timenow#更新时间戳
                                        else:#不是第一次进门
                                            #判断当前人员与前一次进门是否相差规定时间
                                            if((timenow-itime)>=360000):
                                                nameandtime = {"name":namenum,"timestamp":timenow}
                                                with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                                    p.write(json.dumps(nameandtime)+"\n")
                                                doorState = "open"
                                                shibie_frame = True
                                                t[key1] = timenow#更新时间戳
                                            else:
                                                doorState = "close"
                                                shibie_frame = False
                                    else:
                                        doorState = "close"
                                        shibie_frame = False
                                    break
                                key1 =key1-1
                        else:
                            doorState = "close"
                            shibie_frame = False
                    if(state==4):#禁止访客开门
                        start = time.time()
                        namestart = facename
                        timenow = int(round(start*1000))
                        namenum = re.sub("\D","",name)#只传id
                        #识别出的人脸已知时保存数据
                        if(namenum):
                            #循环userid的数组确定对应的role
                            key1 = len(c)-1
                            while(key1>=0):
                                if(c[key1]==int(namenum)):
                                    idrole = b[key1]
                                    itime = t[key1]
                                    if(idrole==int(1) or int(2)):
                                        if(itime==int(0)):#第一次进门
                                            nameandtime = {"name":namenum,"timestamp":timenow}
                                            with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                                p.write(json.dumps(nameandtime)+"\n")
                                            doorState = "open"
                                            shibie_frame = True
                                            t[key1] = timenow#更新时间戳
                                        else:#不是第一次进门
                                            #判断当前人员与前一次进门是否相差规定时间
                                            if((timenow-itime)>=360000):
                                                nameandtime = {"name":namenum,"timestamp":timenow}
                                                with open("/home/simon/mqtt/"+"FaceAndTime.json","a+") as p:
                                                    p.write(json.dumps(nameandtime)+"\n")
                                                doorState = "open"
                                                shibie_frame = True
                                                t[key1] = timenow#更新时间戳
                                            else:
                                                doorState = "close"
                                                shibie_frame = False
                                    else:
                                        doorState = "close"
                                        shibie_frame = False
                                    break
                                key1 =key1-1
                            else:
                                doorState = "close"
                                shibie_frame = False
                        else:
                            doorState = "close"
                            shibie_frame = False
                
                        # 显示结果
                    for (top, right, bottom, left), facename in zip(face_locations, face_names):
                        # 缩放人脸位置,因为我们检测到的帧被缩放到 1/4 大小
                        top *= 4
                        right *= 4
                        bottom *= 4
                        left *= 4
                        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)# 在脸部周围画一个框
                        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) # 在人脸下方画一个带有名字的标签   
                        namec = ''.join(re.findall('[\u4e00-\u9fa5]',name))#只显示名字不显示id
                        nameAndtime = namec + '   ' + nowtime + '   '            
                        img = cv2ImgAddText(frame, nameAndtime, (left + 6), (bottom - 30), (255, 255, 255), 20)#调用的函数
                        if(shibie_frame):
                            (H,W) = frame.shape[:2]
                            rec = (H,W)
                            width = 1000#框的大小
                            height = 150
                            (w,h) = (width,height)
                            (x,y) = (int((rec[1]-width)/2),int((rec[0]-height)/2))
                            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), cv2.FILLED)
                            image1=cv2ImgAddText(frame,("欢迎"+namec+"!已开门!"),(int((rec[1]-width)/2)+100),int((rec[0]-height)/2),(0,0,255),100)
                            cv2.imshow('Video',image1)
                        else:
                            cv2.imshow('Video', img)# 显示结果图像
            else:
                cv2.imshow("Video",frame)
        process_this_frame = not process_this_frame#不知道什么作用,感觉有点防抖动的意思
        if cv2.waitKey(1) & 0xFF == ord('q'):# 按键盘上的“q”退出!
            break      

    # 释放网络摄像头的句柄
    video_capture.release()
    cv2.destroyAllWindows()

if __name__=="__main__":
    face()

四、遇到的问题及知识点总结

1.编码:encode,把你认识的转为机器人认识的

解码:decode,把一堆机器人认识的解释为人能读懂的

2.在python中,通过import可以简化代码

例:import numpy---->data=numpy.ndarry

import numpy as np---->data=np.ndarray

3.os.path.splitext("文件路径")   可以分离文件名与拓展名

4.

with open("a.txt","w") as p:
    p.write()

with open("a.txt","a") as p:
    p.write()

w:覆盖内容

a:新增内容

5.Question:TypeError: a bytes-like object is required,not 'str'

Solution:

#原代码

with open("/home/simon/mqtt/"+"shadow.ini","wb") as sd:

        sd.write(msg.payload.decode('utf-8'))

#更改后的代码

with open("/home/simon/mqtt/"+"shadow.ini","w") as sd:

        sd.write(msg.payload.decode('utf-8'))

将“wb”改为“w”即可解决这个问题,主要是with open存的格式问题

6.数组(list)转字符串(str)

#list内容:

meslist = [{'userId':2.0,'deadline':164096,'role':2.0},{'userId':3.0,'role':1.0}]

list内有数字,不能简单地用   ','.join(meslist)     会报错

正确方法:

strm = ",".join('%s'%id for id in meslist)

print(strm)

输出的strm内容:

{'userId':2.0,'deadline':164096,'role':2.0},{'userId':3.0,'role':1.0}

7.目标:将数组中所存的字符串的对应数据拿出来重新组成数组

原数组:meslist = [{'userId':2.0,'deadline':164096,'role':2.0},{'userId':3.0,'role':1.0}]

目标数组:a = [2,3]

#实现代码
a = [0]
for i in meslist:
    userid = i['userId']
    a.append(int(userid))

8.成员操作符in<用来判断一个字符串中是否有某个量>

str = "string test string test"
find1 = "str"
find2 = "test"
print(find1 in str)   #True
print(find2 not in str)   #False

此篇博客仅做为我此次任务的一个记录,后续还会继续努力。

注:人脸识别设备和mqtt服务器的连接以及传输的代码在下一篇博客中

以上仅是课设个人笔记,如有错误欢迎指正~ 

  • 28
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值