1、调用电脑摄像头 cam.py
from fileinput import filename
from pyparsing import Char
from tkinter.simpledialog import askinteger,askfloat,askstring
import cv2
import tkinter as tk
import tkinter.simpledialog
import os
video = cv2.VideoCapture(0)
idx=1
root = tk.Tk()
root.withdraw()
faceName=askstring("提示",'输入保存的人脸名称:')
print("人脸文件名:",faceName)
while True:
check,frame = video.read()
cv2.imshow("Video Camera",frame)
key = cv2.waitKey(1)
if(key == ord('q')):
print("bye!")
break
if(key == ord(' ')):
print("you press btn: space save image ,index=",idx)
path=os.path.join("image_data", faceName)
if( not os.path.exists(path) ):
os.makedirs(path)
print("path",path,"创建成功")
filename=os.path.sep.join([path, "test_{}.jpg".format(idx)])
cv2.imwrite(filename, frame)
idx+=1
video.release()
cv2.destroyAllWindows()
2.训练 train.py 如下,文件:haarcascade_frontalface_default.xml(百度吧)
import cv2
import os
import numpy as np
from PIL import Image
import pickle
cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
recognise = cv2.face.LBPHFaceRecognizer_create()
def getdata():
current_id = 0
label_id = {}
face_train = []
face_label = []
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
my_face_dir = os.path.join(BASE_DIR,'image_data')
for root, dirs, files in os.walk(my_face_dir):
for file in files:
if file.endswith("png") or file.endswith("jpg"):
path = os.path.join(root, file)
label = os.path.basename(root).lower()
if not label in label_id:
label_id[label] = current_id
current_id += 1
ID = label_id[label]
pil_image = Image.open(path).convert("L")
image_array = np.array(pil_image, "uint8")
face = cascade.detectMultiScale(image_array)
for x,y,w,h in face:
img = image_array[y:y+h, x:x+w]
cv2.imshow("Test",img)
cv2.waitKey(1)
face_train.append(img)
face_label.append(ID)
with open("labels.pickle", 'wb') as f:
pickle.dump(label_id, f)
return face_train,face_label
face,ids = getdata()
recognise.train(face, np.array(ids))
recognise.save("trainner.yml")
3、识别标记
import cv2
import pickle
video = cv2.VideoCapture(0)
cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
recognise = cv2.face.LBPHFaceRecognizer_create()
recognise.read("trainner.yml")
labels = {}
with open("labels.pickle", 'rb') as f:
og_label = pickle.load(f)
labels = {v:k for k,v in og_label.items()}
print(labels)
while True:
check,frame = video.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face = cascade.detectMultiScale(gray, scaleFactor = 1.2, minNeighbors = 5)
for x,y,w,h in face:
face_save = gray[y:y+h, x:x+w]
ID, conf = recognise.predict(face_save)
if conf >= 20 and conf <= 115:
print(ID)
print(labels[ID])
cv2.putText(frame,labels[ID],(x-10,y-10),cv2.FONT_HERSHEY_COMPLEX ,1, (18,5,255), 2, cv2.LINE_AA )
frame = cv2.rectangle(frame, (x,y), (x+w,y+h),(0,255,255),4)
cv2.imshow("Video",frame)
key = cv2.waitKey(1)
if(key == ord('q')):
break
video.release()
cv2.destroyAllWindows()
4、学习记录 Face-Recognition
|