60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
from flask import Flask, request, jsonify, make_response
|
|
import numpy as np
|
|
import cv2
|
|
from skimage.feature import local_binary_pattern
|
|
import os
|
|
from joblib import load
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
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)
|
|
|
|
|
|
@app.route('/classify', methods=['POST'])
|
|
def classify_face():
|
|
# Mendapatkan gambar dari request
|
|
file = request.files['image']
|
|
|
|
# Membaca gambar
|
|
image_bytes = file.read()
|
|
original_image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
|
|
|
|
gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
|
|
gray_image = cv2.equalizeHist(gray_image)
|
|
|
|
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
|
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.2, minNeighbors=10, minSize=(50, 50))
|
|
|
|
predictions = []
|
|
lbp_features = []
|
|
|
|
for i, (x, y, w, h) in enumerate(faces, 1):
|
|
cropped_face = original_image[y:y + h, x:x + w]
|
|
resized_face = cv2.resize(cropped_face, (100, 100))
|
|
gray_resized_face = cv2.cvtColor(resized_face, cv2.COLOR_BGR2GRAY)
|
|
normalized_face = cv2.normalize(gray_resized_face, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
|
|
test_lbp_features = extract_lbp_features(normalized_face, radius=1, n_points=8, method='uniform')
|
|
lbp_features.append(test_lbp_features.tolist())
|
|
predicted_class = knn_model.predict([test_lbp_features])[0]
|
|
predictions.append(predicted_class) # Hanya menambahkan kelas prediksi
|
|
|
|
response = make_response(jsonify(predictions))
|
|
response.headers['X-LBP-Features'] = str(lbp_features)
|
|
return response
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True) |