/
ParaD
/
Steward
Обзор
Документация
Войти
/
ParaD
/
Steward
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
work_camera.py
90 строк
4 KB
Rayfaga
first_commit
01 мар 2025, 20:13
01 мар 2025, 20:13
3e85144
Код
Авторство
О чём код?
import cv2 import face_recognition import math def calculate_face_alignment(left_eye, right_eye): # Вычисляем угол наклона линии, соединяющей левый и правый глаз left_eye_center = (sum([point[0] for point in left_eye]) / len(left_eye), sum([point[1] for point in left_eye]) / len(left_eye)) right_eye_center = (sum([point[0] for point in right_eye]) / len(right_eye), sum([point[1] for point in right_eye]) / len(right_eye)) delta_x = right_eye_center[0] - left_eye_center[0] delta_y = right_eye_center[1] - left_eye_center[1] angle = math.atan2(delta_y, delta_x) * 180 / math.pi # Преобразование в градусы # Чем ближе угол к 0, тем ровнее лицо (положение головы прямо) return 1 / (abs(angle) + 1) # Возвращаем оценку: чем выше, тем лучше # 1. Извлечение лица с документа def extract_face_from_document(input_path, output_path): image = face_recognition.load_image_file(input_path) face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model="hog") if face_locations: top, right, bottom, left = face_locations[0] face_image = image[top:bottom, left:right] cv2.imwrite(output_path, face_image) print(f"Лицо из документа сохранено в {output_path}") else: print("Лицо на изображении документа не обнаружено.") # 2. Детектирование лица с камеры и сохранение самого удачного кадра def capture_best_face_from_camera(output_path): cap = cv2.VideoCapture(0) best_frame = None max_score = 0 print("Нажмите 'q' для выхода") while True: ret, frame = cap.read() if not ret: break face_landmarks = face_recognition.face_landmarks(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) face_locations = face_recognition.face_locations(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) if face_locations and face_landmarks: for landmarks in face_landmarks: if 'left_eye' in landmarks and 'right_eye' in landmarks: left_eye = landmarks['left_eye'] right_eye = landmarks['right_eye'] score = calculate_face_alignment(left_eye, right_eye) if score > max_score: max_score = score best_frame = frame.copy() cv2.imshow('Frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break if best_frame is not None: cv2.imwrite(output_path, best_frame) print(f"Лучший кадр сохранен в {output_path}") else: print("Не удалось захватить лицо.") cap.release() cv2.destroyAllWindows() # 3. Сравнение двух изображений лиц с выводом результата def compare_faces(doc_face_path, camera_face_path): doc_image = face_recognition.load_image_file(doc_face_path) camera_image = face_recognition.load_image_file(camera_face_path) doc_encoding = face_recognition.face_encodings(doc_image) camera_encoding = face_recognition.face_encodings(camera_image) if doc_encoding and camera_encoding: result = face_recognition.compare_faces([doc_encoding[0]], camera_encoding[0], tolerance=0.08) if result[0]: print("ПРОХОДИТЕ") else: print("Доступ запрещен.") else: print("Не удалось получить кодировки лиц.") # Пример вызова функций extract_face_from_document('./photo/password.jpg', './photo/doc_face.jpg') #capture_best_face_from_camera('camera_face.jpg') #compare_faces('doc_face.jpg', 'camera_face.jpg')