#python #opencv #face-detection #face-recognition #haar-classifier
#python #opencv #распознавание лиц #haar-классификатор
Вопрос:
Я написал два скрипта main_program.py
и detector.py
для выполнения обнаружения и распознавания лиц. Я сначала обучаю классификатор, а затем использую его для распознавания лиц. Но обучение не происходит, потому что программа завершается с ошибкой.
вот код для обоих сценариев: Для main_program.py
:-
import cv2
import os
import numpy as np
import detector as dec
test_img = cv2.imread(r'C:UsersJasonPCDesktopFaceDetectionTest Imagesj1.jpg')
faces_detected, gray_img = dec.faceDetect(test_img)
print('Faces Detected: ', faces_detected)
faces, faceID = dec.labels_for_training_data(r'C:UsersJasonPCDesktopFaceDetectionResources')
face_recognizer = dec.train_classifier(faces, faceID)
name = {0:'Obama', 1:'Trump'}
for faces in faces_detected:
(x, y, w, h) = face
roi_gray = gray_img[y : y h, x : x h]
label, confidence = face_recognizer.predict(roi_gray)
confidence('confidence: ', confidence)
print('label: ', label)
dec.draw_rect(test_img, face)
predicted_name = name[label]
dec.put_text(test_img, predicted_name, x, y)
result_img = cv2.resize(test_img, (200, 200))
cv2.imshow('Face Detection', result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
И вот код для detector.py
import cv2
import os
import numpy as np
def faceDetect(img):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
classifier = cv2.CascadeClassifier(r'C:UsersJasonPCDocumentsCodeVaultPythonFaceDetectionClassifiershaarcascade_frontalface_alt.xml')
# classifier = cv2.CascadeClassifier(r'C:UsersJasonPCDocumentsCodeVaultPythonFaceRecognitionClassifier.xml')
# val = classifier.load(r'C:UsersJasonPCDocumentsCodeVaultPythonFaceRecognitionClassifier.xml')
faces = classifier.detectMultiScale(gray_img, scaleFactor = 1.5, minNeighbors = 5 )
return faces, gray_img
def labels_for_training_data(directory):
faces = []
faceID = []
for path, subdirnames, filenames in os.walk(directory):
for filename in filenames:
if filename.startswith("."):
print('Skipping system file...')
continue
id = os.path.basename(path)
img_path = os.path.join(path, filename)
print('img_path: ', img_path)
print('id: ', id)
test_img = cv2.imread(img_path)
if test_img is None:
print('Image is not loaded properly')
continue
faces_rect, gray_img = faceDetect(test_img)
if len(faces_rect) != 1:
continue # since multiple faces has been detected in an single image
(x, y , w, h) = faces_rect[0]
roi_gray = gray_img[y : y 1, x : x h]
faces.append(roi_gray)
faceID.append(int(id))
return faces, faceID
def train_classifier(faces, faceID):
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.train(faces, np.array(faceID))
return face_recognizer
def draw_rect(test_img, face):
(x, y , w, h) = face
cv2.rectangle(test_img, (x, y), (x w, y h), (255, 0, 0), thickness = 5)
def put_text(test_img, text, x, y):
cv2.putText(test_img, text, (x, y), cv2.FONT_HERSHEY_DUPLEX, 5, (255,0, 0), 6)
Но я застрял с ошибкой!
Traceback (most recent call last):
File "c:/Users/JasonPC/Desktop/FaceDetection/main_program.py", line
29, in <module>
face_recognizer = dec.train_classifier(faces, faceID)
File "c:UsersJasonPCDesktopFaceDetectiondetector.py", line 44,
in train_classifier
face_recognizer.train(faces, np.array(faceID))
cv2.error: OpenCV(4.3.0) C:projectsopencv-pythonopencvmodulescoresrcmatrix.cpp:235: error: (-215:Assertion failed) s >= 0 in function 'cv::setSize'
Пожалуйста, помогите мне отладить эту ошибку!
большое, большое спасибо!
Комментарии:
1. Каков результат вашей
faces
переменной?2. ошибка -215 обычно представляет собой ошибку с пустым мат