-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict_image.py
More file actions
91 lines (74 loc) · 3.24 KB
/
Copy pathpredict_image.py
File metadata and controls
91 lines (74 loc) · 3.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import numpy as np
import pandas as pd
import os
from flask import Flask, request, render_template, jsonify
from werkzeug.utils import secure_filename
from neural_network import NeuralNetwork
app = Flask(__name__, static_folder='src/static', template_folder='src/templates')
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
def load_model():
nn = NeuralNetwork()
weights = np.load('model_weights.npz')
nn.weights_input_hidden = weights['w1']
nn.bias_input_hidden = weights['b1']
nn.weights_hidden_middle = weights['w2']
nn.bias_hidden_middle = weights['b2']
nn.weights_middle_output = weights['w3']
nn.bias_middle_output = weights['b3']
return nn
def preprocess_image(features):
if len(features) != 42:
raise ValueError("L'image doit avoir 42 coordonnées")
return np.array([features])
def predict(features):
nn = load_model()
X = preprocess_image(features)
output = nn.predict(X)
# Récupérer la classe prédite, en supposant que la sortie soit une probabilité softmax
predicted_class = np.argmax(output)
letters = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'} # La classe commence à 0 pour un tableau d'indices
return letters[predicted_class]
def extract_features_from_image(image_path):
if not os.path.exists(image_path):
raise FileNotFoundError(f"L'image {image_path} n'existe pas")
data = pd.read_csv('src/datas/data_formatted.csv', header=None)
filename = os.path.basename(image_path)
try:
image_num = int(''.join(filter(str.isdigit, filename))) - 1
except ValueError:
raise ValueError(f"Impossible d'extraire le numéro de l'image depuis {filename}")
if image_num < 0 or image_num >= len(data):
raise ValueError(f"Numéro d'image {image_num} hors plage (0 à {len(data) - 1})")
features = data.iloc[image_num, :42].values
true_label_onehot = data.iloc[image_num, 42:].values
true_label = np.argmax(true_label_onehot) # Utilisation de l'indice de la classe sans ajout de 1
return features, true_label
@app.route('/')
def upload_form():
return render_template("upload.html")
@app.route('/predict', methods=['POST'])
def predict_image():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file:
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
try:
features, true_label = extract_features_from_image(file_path)
predicted_letter = predict(features)
letters = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'} # Correspondance entre index et lettres
os.remove(file_path)
return render_template('upload.html',
prediction=predicted_letter,
true_label=letters[true_label]) # Affichage du label réel
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5001)