跟着大佬学人脸识别 :基于Opencv快速实现人脸识别
附上代码
import cv2
import os
import numpy as np
def detect_face(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(
'/home/xiaoshiguang/PycharmProjects/untitled/venv/renlianjiance/haarcascades/haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
if (len(faces) == 0):
return None, None
(x, y, w, h) = faces[0]
return gray[y:y + w, x:x + h], faces[0]
def prepare_training_data(data_folder_path):
dirs = os.listdir(data_folder_path)
faces = []
labels = []
for dir_name in dirs:
label = int(dir_name)
subject_dir_path = data_folder_path + "/" + dir_name
subject_images_names = os.listdir(subject_dir_path)
for image_name in subject_images_names:
image_path = subject_dir_path + "/" + image_name
image = cv2.imread(image_path)
cv2.imshow("Training on image...", image)
cv2.waitKey(10)
face, rect = detect_face(image)
if face is not None:
faces.append(face)
labels.append(label)
cv2.waitKey(1)
cv2.destroyAllWindows()
return faces, labels
faces, labels = prepare_training_data("/home/xiaoshiguang/PycharmProjects/untitled/venv/renlianjiance/train_data")
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.train(faces, np.array(labels))
def draw_rectangle(img, rect):
(x, y, w, h) = rect
cv2.rectangle(img, (x, y), (x + w, y + h), (128, 128, 0), 2)
def draw_text(img, text, x, y):
cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
subjects = ["37252419820910539X", "130828198212137224", "411224196611058161", "511525199106131460", "370406198206100163"]
def predict(test_img):
img = test_img.copy()
face, rect = detect_face(img)
label = face_recognizer.predict(face)
label_text = subjects[label[0]]
draw_rectangle(img, rect)
draw_text(img, label_text, rect[0], rect[1] - 5)
return img,label_text
test_img1 = cv2.imread("/home/xiaoshiguang/PycharmProjects/untitled/venv/renlianjiance/test_data/1.jpg")
test_img2 = cv2.imread("/home/xiaoshiguang/PycharmProjects/untitled/venv/renlianjiance/test_data/5.jpg")
test_img3 = cv2.imread("/home/xiaoshiguang/PycharmProjects/untitled/venv/renlianjiance/test_data/4.jpg")
predicted_img1, pre_label_text1 = predict(test_img1)
predicted_img2, pre_label_text2 = predict(test_img2)
predicted_img3, pre_label_text3 = predict(test_img3)
cv2.imshow(pre_label_text1, predicted_img1)
cv2.imshow(pre_label_text2, predicted_img2)
cv2.imshow(pre_label_text3, predicted_img3)
cv2.waitKey(0)
cv2.destroyAllWindows()


