def detectface(frame): Загрузка каскадного классификатора для обнаружения лиц…
- User
def detect_face(frame): # Загрузка каскадного классификатора для обнаружения лиц face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Преобразование кадра в оттенки серого gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Обнаружение лиц на кадре faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4, minSize=(30, 30)) if len(faces) > 0: return True else: return FalseСоздание главного окна приложения
root = tk.Tk()
def new_user(): # Создание нового окна new_user_window = tk.Toplevel(root)
# Создание canvas (холста) для отображения видео с веб-камеры canvas = tk.Canvas(new_user_window, width=640, height=480) canvas.pack() # Создание формы регистрации login_label = tk.Label(new_user_window, text="Логин:") login_entry = tk.Entry(new_user_window) password_label = tk.Label(new_user_window, text="Пароль:") password_entry = tk.Entry(new_user_window, show='*') register_button = tk.Button(new_user_window, text="Зарегистрироваться", command=lambda: register(login_entry.get(), password_entry.get())) # Расположение элементов формы регистрации на окне login_label.pack() login_entry.pack() password_label.pack() password_entry.pack() register_button.pack()def register(login, password): # Проверка, существует ли уже пользователь с таким логином
if os.path.exists(f"dataset/{login}"): print("Пользователь уже существует!") return # Захват видео с веб-камеры cap = cv2.VideoCapture(2) ret, frame = cap.read() if not detect_face(frame): print("Лицо не обнаружено!") cap.release() cv2.destroyAllWindows() return # Создание папки для нового пользователя os.mkdir(f"dataset/{login}") # Сохранение кадра с лицом пользователя cv2.imwrite(f"dataset/{login}/face.jpg", frame) # Сохранение логина и пароля в файле with open(f"dataset/{login}/info.txt", "w") as file: file.write(f"Логин: {login}\n") file.write(f"Пароль: {password}") # Закрытие окна и освобождение ресурсов cap.release() cv2.destroyAllWindows()Создание кнопок “Новый пользователь” и “Войти”
new_user_button = tk.Button(root, text="Новый пользователь", command=new_user) login_button = tk.Button(root, text="Войти")
Расположение кнопок на холсте
new_user_button.pack() login_button.pack()
video_label = tk.Label(root) video_label.pack()
video_capture = cv2.VideoCapture(2)
def update_video(): # Получение текущего кадра видео ret, frame = video_capture.read() if ret: # Конвертация цветового пространства BGR в RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Создание изображения Tkinter из массива numpy img = Image.fromarray(frame_rgb) imgtk = ImageTk.PhotoImage(image=img) # Обновление изображения в виджете Label video_label.imgtk = imgtk video_label.configure(image=imgtk) video_label.after(10, update_video)
Вызов функции update_video() для начала обновления видео
update_video()
- Assistant
This code snippet creates a GUI application that allows users to register and login. The
detect_facefunction is used to detect faces in the video frames captured by the webcam.When the "New User" button is clicked, a new window is created where the user can enter their login and password. After clicking the "Register" button, the program captures a frame from the webcam and saves it as an image in a folder named after the user's login. The login and password are also saved in a text file.
The main window contains two buttons: "New User" and "Login". The "New User" button opens the new user window, and the "Login" button currently does not have any functionality.
The video from the webcam is displayed in the main window using a
Labelwidget. Theupdate_videofunction is called periodically to update the video frames in theLabel.Overall, this code snippet provides the basic functionality for registering new users and capturing their face images for later use in a facial recognition system.