python+opencv+face_recognition實現門禁系統
def face_c():
import cv2
capture =cv2.VideoCapture(0)
cv2.namedWindow("camera",1)
print("採集圖片 識別成功後按空格鍵保存圖片")
font = cv2.FONT_HERSHEY_PLAIN
max_ = 0
face=[]
while True:
ret, img = capture.read()
face_cascade = cv2.CascadeClassifier("./face.xml")
if img.ndim == 3:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
gray = img
faces = face_cascade.detectMultiScale(gray)
for (x,y,width,height) in faces:
if (width*height)>max_:
max_ = width*height
face = [x,y,x+width,y+height]
if max_ != 0:
img_ = cv2.rectangle(img, (face[0],face[1]), (face[2],face[3]), (255,0,0), 4)
max_ = 0
cv2.imshow('camera',img_)
key = cv2.waitKey(3)
if key == 27:
print("esc break...")
cv2.destroyAllWindows()
capture.release()
break
if key == ord(' '):
cv2.destroyAllWindows()
capture.release()
gray = gray[face[1]-100:face[3]+100, face[0]-100:face[2]+100]
path = input("請輸入姓名")
cv2.imwrite('./img/'+path+'.jpg',gray)
break
def face_s():
import face_recognition
import os
import cv2
IP = input("請輸入IP地址,輸入0用電腦攝像頭")
if IP == '0':
capture =cv2.VideoCapture(0)
else:
capture =cv2.VideoCapture(IP)
cv2.namedWindow("camera",1)
font = cv2.FONT_HERSHEY_PLAIN
max_ = 0
face=[]
face_img = {}
flag=0
text = ""
g = os.walk(r"./img")
for path,dir_list,file_list in g:
for file_name in file_list:
print('讀取到'+ os.path.join(path, file_name) )
picture = face_recognition.load_image_file(os.path.join(path, file_name))
face_img[file_name[:-4]] = face_recognition.face_encodings(picture)[0]
while True:
ret, img = capture.read()
face_cascade = cv2.CascadeClassifier("./face.xml")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
for (x,y,width,height) in faces:
if (width*height)>max_:
max_ = width*height
face = [x,y,x+width,y+height]
if max_ != 0:
img = cv2.rectangle(img, (face[0],face[1]), (face[2],face[3]), (255,0,0), 4)
cv2.putText(img, text, (face[0], face[1]), font, 2, (0,0,255), 1)
flag =(flag+1)%10
if flag == 0:
try:
face_gray = face_recognition.face_encodings(img)[0]
for i in face_img:
results = face_recognition.compare_faces([face_img[i]], face_gray,tolerance=0.4)
if results[0] == True:
text = i
break
else:
text = ''
except BaseException:
pass
max_ = 0
cv2.imshow('camera',img)
key = cv2.waitKey(3)
if key == 27:
cv2.destroyAllWindows()
capture.release()
break
while(True):
print("請選擇模式")
print("1 信息採集")
print("2 實時識別")
print("q 退出")
a = input()
if a=='1':
face_c()
elif a=='2':
face_s()
elif a=='q':
break
else:
print("輸入信息不對請重新輸入")