import cv2
import os
import shutil
import numpy as np
from PIL import Image
def red(date):
faces = cv2.CascadeClassifier(r"C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect\haarcascades\haarcascade_frontalface_default.xml")
cap=cv2.VideoCapture(0)
face_id=input("\n enter user id: ")
count=0
while True:
ret, img = cap.read()
if ret:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = faces.detectMultiScale(gray,1.05, 10,minSize=(32,32))
for (x,y,w,h) in face:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
if h+w>=300:
new_img = cv2.resize(img[y:y + h, x:x + w], (92, 112)) # 调整图像大小
count+=1
cv2.imwrite("ALLFace/User."+str(face_id)+"."+str(count)+".jpg",new_img)
cv2.imshow('image',img)
k=cv2.waitKey(1)
if k==27:
break
if count==500:
break
cap.release()
cv2.destroyAllWindows()
def getImageAndLabels(path):
detector = cv2.CascadeClassifier(
r"C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect\haarcascades\haarcascade_frontalface_default.xml")
imagePaths = [os.path.join(path, f) for f in os.listdir(path)] # join函数的作用
faceSamples = []
ids = []
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
img_numpy = np.array(PIL_img, 'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_numpy)
for (x, y, w, h) in faces:
faceSamples.append(img_numpy[y:y + h, x: x + w])
ids.append(id)
return faceSamples, ids
def train(path):
recohnizer=cv2.face.LBPHFaceRecognizer_create()
faces,ids=getImageAndLabels(path)
recohnizer.train(faces,np.array(ids))
recohnizer.write(r'E:\01STUDY\20190701\work\deathopencv\train\trainer.yml')
print("{0} faces trained.exiting program".format(len(np.unique(ids))))
def realize():
recohnizer = cv2.face.LBPHFaceRecognizer_create()
recohnizer.read(r'E:\01STUDY\20190701\work\deathopencv\train\trainer.yml')
cascadePath=(r"C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect\haarcascades\haarcascade_frontalface_default.xml")
facaeCascade=cv2.CascadeClassifier(cascadePath)
font=cv2.FONT_HERSHEY_SIMPLEX
idnum=0
name={1:"ymz"}
cap=cv2.VideoCapture(0)
minW=0.1*cap.get(3)
minH=0.1*cap.get(4)
while True:
ret, img = cap.read()
if ret:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = facaeCascade.detectMultiScale(gray,1.05, 10,minSize=(32,32))
for (x,y,w,h) in face:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
idnum,confidence=recohnizer.predict(gray[y:y+h,x:x+w])
print(idnum)
if confidence<100 :#置信度大于50%
idnum=name[idnum]
confidence="{0}%".format(round(100-confidence))
else:
idnum="unknown"
confidence="{0}%".format(round(100-confidence))
cv2.putText(img,idnum,(x+5,y-5),font,1,(255,0,0),1)
cv2.putText(img,str(confidence),(x+5,y+h-5),font,1,(0,0,0),1)
cv2.imshow('camera',img)
k=cv2.waitKey(10)
if k==27:
break
cap.release()
cv2.destroyAllWindows()
if __name__=='__main__':
date2=r'E:\01STUDY\20190701\work\deathopencv\ALLface'
#red(date2)
#train(date2)
realize()