| import cv2 | |
| import time | |
| import os | |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
| cap = cv2.VideoCapture(0) | |
| folder_name = input("Nhập tên thư mục để lưu ảnh: ") | |
| parent_dir = "train_img" | |
| folder_path = os.path.join(parent_dir, folder_name) | |
| if not os.path.exists(parent_dir): | |
| os.makedirs(parent_dir) | |
| if not os.path.exists(folder_path): | |
| os.makedirs(folder_path) | |
| image_count = 0 | |
| last_capture_time = 0 | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| frame = cv2.flip(frame, 1) | |
| original_frame = frame.copy() | |
| gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
| faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) | |
| for (x, y, w, h) in faces: | |
| cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) | |
| current_time = time.time() | |
| if len(faces) > 0 and (current_time - last_capture_time) >= 1: | |
| image_path = os.path.join(folder_path, f"{folder_name}_{int(image_count)}.png") | |
| cv2.imwrite(image_path, original_frame) | |
| print(f"Ảnh đã lưu với tên {image_path}") | |
| last_capture_time = current_time | |
| image_count += 1 | |
| if image_count >= 30: | |
| print(f"Đã chụp đủ 30 ảnh, dừng chương trình. Ảnh đã được lưu tại: {folder_path}") | |
| break | |
| cv2.imshow('Webcam', frame) | |
| if cv2.waitKey(1) & 0xFF == ord('q'): | |
| break | |
| cap.release() | |
| cv2.destroyAllWindows() | |