63 lines
2.2 KiB
Python
63 lines
2.2 KiB
Python
import numpy as np
|
|
import cv2
|
|
from skimage.feature import local_binary_pattern
|
|
import os
|
|
from joblib import load
|
|
import sys
|
|
|
|
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
|
|
|
|
# Mendapatkan path lengkap ke file facemodel.joblib
|
|
model_path = os.path.join(os.path.dirname(__file__), 'facemodel.joblib')
|
|
|
|
# Memuat model dari file
|
|
knn_model = load(model_path)
|
|
|
|
# Path ke gambar wajah uji (diteruskan sebagai argumen command line)
|
|
test_image_path = sys.argv[1]
|
|
|
|
# Baca gambar
|
|
original_image = cv2.imread(test_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.3, minNeighbors=8, minSize=(30, 30))
|
|
|
|
# Cek jumlah wajah yang terdeteksi
|
|
print(f'{test_image_path}: {len(faces)} face(s) detected')
|
|
|
|
# Loop melalui setiap wajah yang terdeteksi, potong, dan ekstraksi LBP
|
|
for i, (x, y, w, h) in enumerate(faces, 1):
|
|
# Pemotongan (Cropping) wajah
|
|
cropped_face = original_image[y:y + h, x:x + w]
|
|
|
|
# Resize gambar menjadi 100x100 piksel
|
|
resized_face = cv2.resize(cropped_face, (100, 100))
|
|
|
|
# Konversi gambar resized ke grayscale
|
|
gray_resized_face = cv2.cvtColor(resized_face, cv2.COLOR_BGR2GRAY)
|
|
|
|
# Normalisasi intensitas
|
|
normalized_face = cv2.normalize(gray_resized_face, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
|
|
|
|
# Ekstraksi fitur LBP untuk gambar uji
|
|
test_lbp_features = extract_lbp_features(normalized_face, radius=1, n_points=8, method='uniform')
|
|
|
|
# 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}')
|