CoolFace
Apppublic

vanv123/aidd

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
collect_data.py63 linesDownload Raw Back to root
1import cv2
2import os
3import time
4
5# 1. Định nghĩa đường dẫn lưu ảnh
6REAL_PATH = 'dataset/train/real'
7FAKE_PATH = 'dataset/train/fake'
8
9# 2. Khởi tạo webcam (0 là camera mặc định của laptop)
10cap = cv2.VideoCapture(0)
11
12def capture_images(label_path, num_images=100):
13    print(f"\n[INFO] Đang chuẩn bị chụp {num_images} ảnh...")
14    time.sleep(2) # Dừng 2 giây để em chuẩn bị tư thế
15    
16    count = 0
17    while count < num_images:
18        ret, frame = cap.read()
19        if not ret:
20            break
21        
22        # Lưu ảnh với tên chứa timestamp để không bị trùng
23        img_name = os.path.join(label_path, f"img_{int(time.time() * 1000)}_{count}.jpg")
24        cv2.imwrite(img_name, frame)
25        count += 1
26        
27        # Hiển thị thông báo lên màn hình
28        cv2.putText(frame, f"Dang chup: {count}/{num_images}", (50, 50), 
29                    cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
30        cv2.imshow('Thu thap Dataset', frame)
31        cv2.waitKey(50) # Tốc độ chụp: 0.05 giây / ảnh
32        
33    print("[INFO] Đã chụp xong!")
34
35# 3. Vòng lặp chính điều khiển bằng bàn phím
36print("=== HƯỚNG DẪN SỬ DỤNG ===")
37print("- Nhấn phím 'r' để chụp mặt THẬT (Real).")
38print("- Nhấn phím 'f' để chụp mặt GIẢ (Fake).")
39print("- Nhấn phím 'q' để THOÁT.")
40
41while True:
42    ret, frame = cap.read()
43    if not ret:
44        print("[LỖI] Không thể kết nối với webcam.")
45        break
46
47    cv2.putText(frame, "Nhan: 'r' (That), 'f' (Gia), 'q' (Thoat)", (10, 30), 
48                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
49    cv2.imshow('Thu thap Dataset', frame)
50
51    key = cv2.waitKey(1) & 0xFF
52    
53    if key == ord('r'):
54        # Chụp mặt thật: Em cứ ngồi bình thường, hơi xoay đầu nhẹ
55        capture_images(REAL_PATH, 100)
56    elif key == ord('f'):
57        # Chụp mặt giả: Lấy điện thoại mở ảnh 1 khuôn mặt, giơ lên trước camera
58        capture_images(FAKE_PATH, 100)
59    elif key == ord('q'):
60        break
61
62cap.release()
63cv2.destroyAllWindows()