import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk

import os
import pickle
import face_recognition



def add_new_user(known_faces, known_names):
video = cv2.VideoCapture(0) # Веб-камера

while True:
ret, frame = video.read()

# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)

for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = “Unknown”

# Проверка, что лицо на видео есть в базе данных
if True in matches:
continue

name = tk.simpledialog.askstring(“Новый пользователь”, “Введите имя пользователя:”)
if name is None:
return

# Создание директории для нового пользователя
person_folder = os.path.join(“database”, name)
os.makedirs(person_folder, exist_ok=True)

# Сохранение скриншота с лицом
screenshot_name = datetime.now().strftime(“%Y%m%d%H%M%S”) + “.png”
screenshot_path = os.path.join(person_folder, screenshot_name)
cv2.imwrite(screenshot_path, frame)

# Обновление базы данных
known_faces.append(face_encoding)
known_names.append(name)

messagebox.showinfo(“Новый пользователь”, “Пользователь успешно добавлен в базу данных.”)
return

cv2.imshow(““Face Recognition””, frame)

if cv2.waitKey(1) & 0xFF == ord(‘q’):
break

video.release()
cv2.destroyAllWindows()


def load_known_faces(folder_path):
known_faces = []
known_names = []

for name in os.listdir(folder_path):
person_folder = os.path.join(folder_path, name)
if not os.path.isdir(person_folder):
continue

for image_name in os.listdir(person_folder):
image_path = os.path.join(person_folder, image_name)
image = face_recognition.load_image_file(image_path)
image_encoding = face_recognition.face_encodings(image)
if len(image_encoding) > 0:
known_faces.append(image_encoding[0])
known_names.append(name)

return known_faces, known_names


def recognize_faces(camera_id, known_faces, known_names):
video = cv2.VideoCapture(camera_id)

while True:
ret, frame = video.read()

# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)

for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = “Unknown”

# Поиск соответствия лица с известными лицами
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]

# Рисуем прямоугольник вокруг лица и название
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

# Сохранение скриншота при нахождении лица на видео
if name != “Unknown”:
now = datetime.now()
timestamp = now.strftime(“%Y%m%d%H%M%S”)
screenshot_path = os.path.join(“database”, name, f"{name}_{timestamp}.png")
cv2.imwrite(screenshot_path, frame)

# Отображение кадра с распознанными лицами
cv2.imshow(“Face Recognition”, frame)

if cv2.waitKey(1) & 0xFF == ord(‘q’):
break
def add_new_user():
name = messagebox.askstring(“New User”, “Enter the name of the new user:”)
if name:
folder_path = os.path.join(“database”, name)
os.makedirs(folder_path, exist_ok=True)
messagebox.showinfo(“New User”, “New user added successfully!”)


# Создание окна для отображения
window = tk.Tk()
window.title(““Face Recognition””)
window.geometry(“800x600”)

# Загрузка известных лиц
known_faces, known_names = load_known_faces(“database”)

# Кнопка для добавления нового пользователя
add_user_button = tk.Button(window, text=“Добавить пользователя”, command=lambda: add_new_user(known_faces, known_names))
add_user_button.pack()

# Запуск распознавания на веб-камере
recognize_faces(0, known_faces, known_names)

# Запуск главного цикла окна
window.mainloop()

как уменьшить размер видео внутри окна tkinter чтобы было видно кнопки и остальное окно с помощью canvas