Untitled

 avatar
unknown
plain_text
2 months ago
2.1 kB
6
Indexable
import cv2
import os
import numpy as np

def preprocess_face(face):
    """Preprocessing untuk memperbaiki kualitas wajah."""
    # Konversi ke grayscale
    gray_face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
    # Histogram Equalization untuk normalisasi pencahayaan
    equalized_face = cv2.equalizeHist(gray_face)
    # Kembali ke format RGB agar cocok dengan input model
    return cv2.cvtColor(equalized_face, cv2.COLOR_GRAY2BGR)

# Input nama pengguna
user_name = input("Masukkan Nama Pengguna: ")

# Buat folder untuk menyimpan dataset berdasarkan nama pengguna
OUTPUT_DIR = f"dataset_latest/{user_name.replace(' ', '_')}"  # Mengganti spasi dengan underscore
os.makedirs(OUTPUT_DIR, exist_ok=True)

# Menggunakan kamera untuk menangkap wajah
cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

count = 0  # Counter untuk menyimpan jumlah gambar
while count < 200:  # Ambil 200 gambar
    ret, frame = cap.read()
    if not ret:
        break

    # Deteksi wajah
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50))

    for (x, y, w, h) in faces:
        face = frame[y:y+h, x:x+w]
        
        # Preprocessing wajah
        preprocessed_face = preprocess_face(face)
        face_resized = cv2.resize(preprocessed_face, (128, 128))
        file_path = os.path.join(OUTPUT_DIR, f"face_{count}.jpg")
        
        # Simpan wajah yang telah diproses
        cv2.imwrite(file_path, face_resized)
        count += 1

        # Gambar kotak di wajah
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.putText(frame, f"Capturing {count}/200", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

    cv2.imshow(f"Collecting Faces for {user_name}", frame)
    if cv2.waitKey(1) & 0xFF == ord('q') or count >= 200:
        break

cap.release()
cv2.destroyAllWindows()
print(f"{count} images saved for user {user_name} in {OUTPUT_DIR}")
Editor is loading...
Leave a Comment