Skip to content

Instantly share code, notes, and snippets.

@juliendkim
Last active March 14, 2020 13:57
Show Gist options
  • Save juliendkim/2bfe513d9140f2e5bbd94a15b061c420 to your computer and use it in GitHub Desktop.
Save juliendkim/2bfe513d9140f2e5bbd94a15b061c420 to your computer and use it in GitHub Desktop.
train face then recognize
import cv2
import os
from face_recog import save_detected, detect_face, train_face
def check(trained_filename):
model = cv2.face.LBPHFaceRecognizer_create()
model.read(trained_filename)
capture = cv2.VideoCapture(0)
while True:
captured, frame = capture.read()
if not captured:
break
detected, marked_image = detect_face.detect_faces(frame)
for gray_face, (x, y, _, _) in detected:
train_id, confidence = model.predict(gray_face)
if confidence < 50:
cv2.putText(marked_image, f'{train_id} {confidence:.2f}', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 0))
cv2.imshow('Face', marked_image)
if cv2.waitKey(10) > 0:
break
capture.release()
cv2.destroyAllWindows()
def ready(path):
save_detected.save_detected(path)
def train(face_image_folder, trained_save_filename):
train_face.train(face_image_folder, trained_save_filename)
if __name__ == '__main__':
check(f'{os.path.dirname(os.path.abspath(__file__))}/trained.xml')
import os
import cv2
def detect_faces(image):
if image is None:
return None, None
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
classifier = cv2.CascadeClassifier(f'{os.path.dirname(os.path.abspath(__file__))}/haarcascade_frontalface_default.xml')
coords = classifier.detectMultiScale(gray_image, 1.3, 5)
detected = []
for coord in coords:
x, y, w, h = coord
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
face = gray_image[y:y+h, x:x+w]
resized = cv2.resize(face, (200, 200))
detected.append((resized, coord))
return detected, image
if __name__ == '__main__':
detect_faces(None)
download from https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
opencv-contrib-python==4.1.2.30
import os
import cv2
from face_recog import detect_face
def save_detected(path):
os.makedirs(path, exist_ok=True)
capture = cv2.VideoCapture(0)
face_count = 0
while True:
captured, frame = capture.read()
if not captured:
break
detected, marked_image = detect_face.detect_faces(frame)
if not detected:
continue
for gray_face, (x, y, _, _) in detected:
face_count += 1
cv2.imwrite(f'{path}/{face_count:03d}.jpg', gray_face)
cv2.putText(marked_image, str(face_count), (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('Ready Training Faces', marked_image)
if cv2.waitKey(10) > 0 or face_count == 100:
break
capture.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
save_detected(f'{os.path.dirname(os.path.abspath(__file__))}/faces')
import cv2
import numpy as np
import os
def train(path, trained_file):
train_data, labels = [], []
for idx, file in enumerate(os.listdir(path)):
image = cv2.imread(f'{path}/{file}', cv2.IMREAD_GRAYSCALE)
train_data.append(np.asarray(image, dtype=np.uint8))
labels.append(idx)
if len(labels) == 0:
return None, None
labels = np.asarray(labels, dtype=np.int32)
model = cv2.face.LBPHFaceRecognizer_create()
model.train(np.asarray(train_data), np.asarray(labels))
model.write(trained_file)
return model
if __name__ == '__main__':
train(
f'{os.path.dirname(os.path.abspath(__file__))}/faces',
f'{os.path.dirname(os.path.abspath(__file__))}/trained.xml'
)
@mazen-tagadeen
Copy link

how to install opencv-contrib-python==4.1.2.30

@mazen-tagadeen
Copy link

i'm using opencv 4.1 but ther Error cv2.face.LBPHFaceRecognizer_create()

@juliendkim
Copy link
Author

juliendkim commented Mar 14, 2020

@mazen-tagadeen
pip install opencv-contrib-python or use requirements.txt pip install -r requirements.txt

@mazen-tagadeen
Copy link

mazen-tagadeen commented Mar 14, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment