from skimage import io,color
import dlib
from skimage.feature import hog
import matplotlib.pyplot as plt
image=io.imread(r"C:\Users\hp\Desktop\FaceDetection\eg.png")
image=color.rgb2gray(image)
array,hog_image=hog(image,visualise=True)
fig,(ax1,ax2)=plt.subplots(1,2,figsize=(8,4))
ax1.imshow(image,cmap=plt.cm.gray)
ax2.imshow(hog_image,cmap=plt.cm.gray)
plt.show()
图中人脸加框
from skimage import io
import dlib
file_name="li_00.jpg"
image=io.imread(file_name)
detector=dlib.get_frontal_face_detector()
detector_faces=detector(image,1)
print("发现{}张人脸,在{}图片中".format(len(detector_faces),file_name))
model="shape_predictor_68_face_landmarks.dat"
predictor=dlib.shape_predictor(model)
win=dlib.image_window()
win.set_image(image)
for i,box in enumerate(detector_faces):
win.add_overlay(box)
print("第{}张人脸的左边位置:{},右边位置:{}".format(i,box.left(),box.right()))
landmarks=predictor(image,box)
win.add_overlay(landmarks)
dlib.hit_enter_to_continue()
KNN
import os
from sklearn import neighbors
import os.path
import pickle
from PIL import Image,ImageDraw
import face_recognition as fr
from face_recognition.face_recognition_cli import image_files_in_folder
def train(train_dir,model_save_path='face_recog_model.clf',n_neighbors=3,knn_algo='ball tree'):
X=[]
Y=[]
for class_dir in os.listdir(train_dir):
if not os.path.isdir(os.path.join(train_dir,class_dir)):
continue
for img_path in image_files_in_folder(os.path.join(train_dir,class_dir)):
image= fr.load_image_file(img_path)
boxes=fr.face_locations(image)
X.append(fr.face_encodings(image,known_face_locations=boxes)[0])
Y.append(class_dir)
if n_neighbors is None:
n_neighbors=3
knn_clf=neighbors.KNeighborsClassifier(n_neighbors=n_neighbors)
knn_clf.fit(X,Y)
if model_save_path is not None:
with open(model_save_path,'wb') as f:
pickle.dump(knn_clf,f)
return knn_clf
def predict(img_path,knn_clf=None,model_path=None,distance_threshold=0.5):
if knn_clf is None and model_path is None:
raise Exception("必须提供KNN分类器,可选方式为knn_clf或model_path")
if knn_clf is None:
with open(model_path,"rb") as f:
knn_clf=pickle.load(f)
X_img=fr.load_image_file(img_path)
X_face_locations=fr.face_locations(X_img)
encondings=fr.face_encodings(X_img,known_face_locations=X_face_locations)[0]
closest_distances=knn_clf.kneighbors(encondings,n_neighbors=1)
are_matches=[closest_distances[0][i][0]<=distance_threshold
for i in range(len(X_face_locations)) ]
return [(pred,loc) if rec else("unknown",loc)
for pred,loc ,rec in zip(knn_clf.predict(encondings),X_face_locations,are_matches)]
def show_names_on_image(img_path,predictions):
pil_image=Image.open(img_path).convert("RGB")
draw=ImageDraw.Draw(pil_image)
for name,(top,right,bottom,left) in predictions:
draw.rectangle(((left,top),(right,bottom)),outline=(255,0,255))
name=name.encode("UTF-8")
name=name.decode("ascii")
text_width,text_height=draw.textsize(name)
draw.rectangle(((left,bottom-text_height-10),(right,bottom)),
fill=(255,0,255),outline=(255,0,255))
draw.text((left+6,bottom-text_height-5),name,fill=(255,255,255))
del draw
pil_image.show()
if __name__=="__main__":
print("正在训练KNN分类器~~~~")
train("examples/train",model_save_path="face_recog_model.clf",n_neighbors=2)
print("训练完成")
for image_file in os.listdir("examples/test"):
full_file_path=os.path.join("examples/test",image_file)
print("在{}中寻找人脸……".format(image_file))
predictions=predict(full_file_path,model_path="face_recog_model.clf")
for name,(top,right,bottom,left) in predictions:
print("发现{},位置:({},{},{},{})".format(name,top,right,bottom,left))
show_names_on_image(os.path.join("examples/test",image_file),predictions)