import cv2 import torch import torch.nn as nn import numpy as np from torchvision import models, transforms from insightface.app import FaceAnalysis # ========================================== # 1. KHỞI TẠO VÀ TẢI CÁC MÔ HÌNH AI # ========================================== print("[INFO] Đang khởi tạo hệ thống AI...") # 1.1 Tải mô hình Anti-Spoofing (PyTorch) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") liveness_model = models.mobilenet_v2() num_ftrs = liveness_model.classifier[1].in_features liveness_model.classifier[1] = nn.Linear(num_ftrs, 2) # 2 lớp: 0 (Fake), 1 (Real) liveness_model.load_state_dict(torch.load('models/anti_spoofing_model.pth', map_location=device)) liveness_model = liveness_model.to(device) liveness_model.eval() # Đặt ở chế độ suy luận (không train nữa) # Bộ tiền xử lý ảnh cho Anti-Spoofing preprocess = transforms.Compose([ transforms.ToPILImage(), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # 1.2 Tải mô hình Nhận diện khuôn mặt (InsightFace) # Dùng bộ 'buffalo_l' siêu chuẩn app = FaceAnalysis(name='buffalo_l', root='./models', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) app.prepare(ctx_id=0, det_size=(640, 640)) # ========================================== # 2. ĐĂNG KÝ KHUÔN MẶT GỐC (DATABASE) # ========================================== print("[INFO] Đang đọc khuôn mặt gốc...") base_img = cv2.imread('my_face.jpg') if base_img is None: print("[LỖI] Không tìm thấy file 'my_face.jpg'. Vui lòng thêm ảnh vào thư mục!") exit() faces_base = app.get(base_img) if len(faces_base) == 0: print("[LỖI] Không tìm thấy khuôn mặt nào trong ảnh gốc!") exit() base_embedding = faces_base[0].embedding # Vector 512 chiều của khuôn mặt gốc # Hàm so sánh 2 khuôn mặt def compare_faces(emb1, emb2, threshold=0.45): sim = np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2)) return sim >= threshold, sim # ========================================== # 3. CHẠY WEBCAM VÀ XỬ LÝ THEO THỜI GIAN THỰC # ========================================== print("[INFO] Bắt đầu quét điểm danh. Nhấn 'q' để thoát.") cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break # Bước 1: Phát hiện khuôn mặt faces = app.get(frame) for face in faces: # Lấy tọa độ khung khuôn mặt (Bounding Box) bbox = face.bbox.astype(int) x1, y1, x2, y2 = bbox # Đảm bảo tọa độ không vượt quá kích thước ảnh x1, y1 = max(0, x1), max(0, y1) x2, y2 = min(frame.shape[1], x2), min(frame.shape[0], y2) # Cắt khuôn mặt ra để kiểm tra face_crop = frame[y1:y2, x1:x2] if face_crop.shape[0] == 0 or face_crop.shape[1] == 0: continue # Bước 2: Kiểm tra Thực thể (Anti-Spoofing) input_tensor = preprocess(face_crop).unsqueeze(0).to(device) with torch.no_grad(): output = liveness_model(input_tensor) _, pred = torch.max(output, 1) is_real = (pred.item() == 1) if not is_real: # Nếu là FAKE: Cảnh báo đỏ, không nhận diện cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2) cv2.putText(frame, "FAKE - Canh Bao!", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2) else: # Bước 3: Nếu là REAL, tiến hành Nhận diện current_embedding = face.embedding match, score = compare_faces(base_embedding, current_embedding) if match: # Trùng khớp: Xanh lá cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(frame, f"Sy (Real) - {score:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2) else: # Người lạ nhưng là thật: Vàng cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 255), 2) cv2.putText(frame, f"Unknown (Real)", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2) # Hiển thị kết quả lên màn hình cv2.imshow("He Thong Diem Danh AI", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()