import numpy as np import cv2 from skimage.feature import local_binary_pattern import joblib # Load the trained model from file knn_model = joblib.load('facemodel.joblib') def extract_lbp_features(image, radius=1, n_points=8, method='uniform'): lbp = local_binary_pattern(image, n_points, radius, method) (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, n_points + 3), range=(0, n_points + 2)) # Normalize the histogram hist = hist.astype("float") hist /= (hist.sum() + 1e-7) return hist # Fungsi untuk deteksi wajah dan cropping def detect_and_crop_faces(image_path): # Baca gambar original_image = cv2.imread(image_path) gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) # Peningkatan kontras gray_image = cv2.equalizeHist(gray_image) # Muat pre-trained Haar Cascade untuk deteksi wajah face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Deteksi wajah pada gambar dengan parameter yang disesuaikan faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.4, minNeighbors=6, minSize=(50, 50)) # Cek jumlah wajah yang terdeteksi print(f'{image_path}: {len(faces)} face(s) detected') # Loop melalui setiap wajah yang terdeteksi, potong, dan tampilkan for i, (x, y, w, h) in enumerate(faces, 1): # Pemotongan (Cropping) wajah cropped_face = original_image[y:y + h, x:x + w] # # Tampilkan gambar wajah yang terpotong # cv2.imshow(f'Cropped Face {i}', cropped_face) # # # Tunggu 1 detik sebelum menampilkan gambar berikutnya # cv2.waitKey(1000) return faces # Path ke gambar wajah uji test_image_path = 'images/testface/Alia Bhatt/Alia Bhatt_77.jpg' # Deteksi wajah dan cropping pada gambar uji test_faces = detect_and_crop_faces(test_image_path) # Loop melalui setiap wajah yang terdeteksi di gambar uji for i, (x, y, w, h) in enumerate(test_faces, 1): # Pemotongan (Cropping) wajah cropped_test_face = cv2.imread(test_image_path)[y:y + h, x:x + w] # Resize gambar menjadi 100x100 piksel resized_test_face = cv2.resize(cropped_test_face, (100, 100)) # Konversi gambar resized ke grayscale gray_resized_test_face = cv2.cvtColor(resized_test_face, cv2.COLOR_BGR2GRAY) # Normalisasi intensitas normalized_test_face = cv2.normalize(gray_resized_test_face, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) # Ekstraksi fitur LBP untuk gambar uji test_lbp_features = extract_lbp_features(normalized_test_face, radius=1, n_points=8, method='uniform') # Tampilkan nilai ekstraksi LBP ke konsol print(f'LBP Features for face: {test_lbp_features}') # Prediksi kelas menggunakan model K-NN predicted_class = knn_model.predict([test_lbp_features])[0] # Tampilkan hasil prediksi print(f'Predicted class for face {i}: {predicted_class}') # Tunggu sampai tombol ditekan dan tutup jendela cv2.waitKey(0) cv2.destroyAllWindows()