Vassa007

face realtime

Feb 14th, 2025
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. import cv2
  2. import torch
  3. from ultralytics import YOLO
  4.  
  5. # Load model yang sudah ditraining
  6. model = YOLO("runs/detect/train_20250214_104914/weights/best.pt")
  7.  
  8. # Buka webcam (0 = kamera utama, 1 jika menggunakan kamera eksternal)
  9. cap = cv2.VideoCapture(0)
  10.  
  11. # Atur resolusi video (opsional, bisa disesuaikan)
  12. cap.set(3, 640)  # Lebar
  13. cap.set(4, 480)  # Tinggi
  14.  
  15. while cap.isOpened():
  16.     ret, frame = cap.read()
  17.     if not ret:
  18.         break
  19.  
  20.     # Konversi warna (YOLO menggunakan format RGB)
  21.     rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  22.  
  23.     # Gunakan model untuk mendeteksi wajah
  24.     results = model(rgb_frame, conf=0.3)  # Turunkan confidence jika perlu
  25.  
  26.     # Gambar hasil deteksi di frame
  27.     for r in results:
  28.         for box in r.boxes:
  29.             x1, y1, x2, y2 = map(int, box.xyxy[0])  # Koordinat kotak deteksi
  30.             confidence = float(box.conf[0])  # Confidence score
  31.  
  32.             # Gambar kotak deteksi di wajah
  33.             cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
  34.             cv2.putText(frame, f"Face {confidence:.2f}", (x1, y1 - 10),
  35.                         cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
  36.  
  37.     # Tampilkan hasil di layar
  38.     cv2.imshow("YOLOv8 Face Detection", frame)
  39.  
  40.     # Tekan 'q' untuk keluar
  41.     if cv2.waitKey(1) & 0xFF == ord('q'):
  42.         break
  43.  
  44. # Tutup semua proses
  45. cap.release()
  46. cv2.destroyAllWindows()
  47.  
Add Comment
Please, Sign In to add comment