aidd / collect_data.py
vanv123's picture
Upload 11 files
e727cd2 verified
Raw History Blame Contribute Delete
2.22 kB
import cv2
import os
import time
# 1. Định nghĩa đường dẫn lưu ảnh
REAL_PATH = 'dataset/train/real'
FAKE_PATH = 'dataset/train/fake'
# 2. Khởi tạo webcam (0 là camera mặc định của laptop)
cap = cv2.VideoCapture(0)
def capture_images(label_path, num_images=100):
print(f"\n[INFO] Đang chuẩn bị chụp {num_images} ảnh...")
time.sleep(2) # Dừng 2 giây để em chuẩn bị tư thế
count = 0
while count < num_images:
ret, frame = cap.read()
if not ret:
break
# Lưu ảnh với tên chứa timestamp để không bị trùng
img_name = os.path.join(label_path, f"img_{int(time.time() * 1000)}_{count}.jpg")
cv2.imwrite(img_name, frame)
count += 1
# Hiển thị thông báo lên màn hình
cv2.putText(frame, f"Dang chup: {count}/{num_images}", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('Thu thap Dataset', frame)
cv2.waitKey(50) # Tốc độ chụp: 0.05 giây / ảnh
print("[INFO] Đã chụp xong!")
# 3. Vòng lặp chính điều khiển bằng bàn phím
print("=== HƯỚNG DẪN SỬ DỤNG ===")
print("- Nhấn phím 'r' để chụp mặt THẬT (Real).")
print("- Nhấn phím 'f' để chụp mặt GIẢ (Fake).")
print("- Nhấn phím 'q' để THOÁT.")
while True:
ret, frame = cap.read()
if not ret:
print("[LỖI] Không thể kết nối với webcam.")
break
cv2.putText(frame, "Nhan: 'r' (That), 'f' (Gia), 'q' (Thoat)", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
cv2.imshow('Thu thap Dataset', frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('r'):
# Chụp mặt thật: Em cứ ngồi bình thường, hơi xoay đầu nhẹ
capture_images(REAL_PATH, 100)
elif key == ord('f'):
# Chụp mặt giả: Lấy điện thoại mở ảnh 1 khuôn mặt, giơ lên trước camera
capture_images(FAKE_PATH, 100)
elif key == ord('q'):
break
cap.release()
cv2.destroyAllWindows()