Я пытаюсь отправить файл изображения в запросе из бэкэнда Express JS в модуль распознавания лиц Python, который не работает. Все коды и ошибки приведены ниже. Но при отправке запроса от почтальона (я использую классики вместо почтальона) в модуль Python он работает нормально. Все скриншоты также представлены ниже.
[img]https://i .sstatic.net/4a553FTL.png[/img]
[img]https: //i.sstatic.net/M6WAvW4p.png[/img]
Часть контроллера для конечной точки->
//Sending req to ml module
export const getFaceDetails= async( req , res )=>{
const photo = req.file;
try {
const formData = new FormData();
formData.append('image', photo.buffer);
console.log(formData);
// Make the POST request to the face recognition module
const response = await axios.post('http://127.0.0.1:5000/detect', formData, {
headers: {
"content-type":"multipart/form-data" // Set appropriate headers for multipart/form-data
}
});
// Handle response from the face recognition module
res.status(200).json(response.data);
} catch (error) {
console.error('Error sending image to face recognition module:', error.message);
res.status(500).send('Error processing the image');
}
}
Часть маршрута
import { getFaceDetails } from '../controllers/Hackathon.js';
const upload = multer({
storage: multer.memoryStorage(),
});
HackathonRoutes.post("/face",upload.single("image"),getFaceDetails)
flask_main.py
from flask import Flask, request, jsonify
import cv2
import numpy as np
from retinaface import RetinaFace
from deepface import DeepFace
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
app = Flask(__name__)
# Initialize known face embeddings (from the database)
known_faces = []
known_profiles = ['ritika.jpg', 'shubham.jpg', 'kuldeep.jpg', 'anurag.jpg', 'chaudhary.jpg']
# Pre-compute embeddings for known profiles
for profile_image in known_profiles:
img = cv2.imread(profile_image)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
face_embedding = DeepFace.represent(img_rgb, model_name="ArcFace", enforce_detection=False)
if len(face_embedding) > 0:
known_faces.append(face_embedding[0]['embedding'])
@app.route('/detect', methods=['POST'])
def detect_faces():
# Check if an image is provided
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
# Load the uploaded image
file = request.files['image']
print(file)
# image=file.read()
# KP change1
# file_bytes = np.frombuffer(file.read(), np.uint8)
# image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
# if image is None:
# return jsonify({"error": "Failed to decode image"}), 400
#KP change 2
image = np.frombuffer(file.read(), np.uint8)
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
#Original Code
# image = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_COLOR)
# Use RetinaFace to detect faces
faces = RetinaFace.detect_faces(image)
if len(faces) == 0:
return jsonify({"message": "No faces detected"}), 200
matches = []
# Process each detected face in the group image
for i, (key, face_data) in enumerate(faces.items()):
# Get face bounding box
bbox = face_data['facial_area']
face_crop = image[bbox[1]:bbox[3], bbox[0]:bbox[2]] # Crop the detected face
# Convert to RGB for DeepFace
face_crop_rgb = cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB)
# Get face embedding using DeepFace (ArcFace model)
face_in_group = DeepFace.represent(face_crop_rgb, model_name="ArcFace", enforce_detection=False)
if len(face_in_group) > 0:
unknown_embedding = face_in_group[0]['embedding'] # Extract embedding
# Compare detected face with known faces
for j, known_embedding in enumerate(known_faces):
# Calculate cosine similarity
similarity = np.dot(known_embedding, unknown_embedding) / (np.linalg.norm(known_embedding) * np.linalg.norm(unknown_embedding))
# Set a threshold for matching
if similarity > 0.4:
matches.append({
"detected_face": f"Face {i}",
"matched_profile": known_profiles[j],
"similarity": round(similarity, 2)
})
# Return the matched profiles
if len(matches) > 0:
return jsonify({"matches": matches}), 200
else:
return jsonify({"message": "No matching faces found"}), 200
if __name__ == '__main__':
app.run(debug=True)
Ошибка серверной части
Error sending image to face recognition module: Request failed with status code 400
Журнал Python
127.0.0.1 - - [07/Oct/2024 11:54:10] "POST /detect HTTP/1.1" 400 -
127.0.0.1 - - [07/Oct/2024 11:55:50] "POST /detect HTTP/1.1" 400 -
Подробнее здесь: https://stackoverflow.com/questions/790 ... -backend-r