from flask import Flask, render_template, request, redirect, url_for from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image import numpy as np import os from PIL import Image # Initialize the Flask app app = Flask(__name__) # Load trained model MODEL_PATH = 'my_model.h5' model = load_model(MODEL_PATH) # List of class names (from LabelEncoder's `classes_`) class_names = ['Acacia', 'Acer', 'Alnus', 'Anadenanthera', 'Betula', 'Celtis', 'Chamaerops', 'Corylus', 'Eucalyptus', 'Fagus', 'Fraxinus', 'Juglans', 'Laurus', 'Morus', 'Pinus', 'Platanus', 'Populus', 'Quercus', 'Salix', 'Tamarix', 'Tilia', 'Ulmus', 'Zea'] # Home route @app.route('/') def index(): return render_template('index.html') # Predict route @app.route('/predict', methods=['POST']) def predict(): if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if file.filename == '': return redirect(request.url) if file: # Save the uploaded file filepath = os.path.join('static', file.filename) file.save(filepath) # Load image img = Image.open(filepath).convert("RGB") img = img.resize((128, 128)) img_array = np.array(img) / 255.0 img_array = np.expand_dims(img_array, axis=0) # Predict predictions = model.predict(img_array) class_index = np.argmax(predictions) predicted_label = class_names[class_index] confidence = round(100 * np.max(predictions), 2) return render_template('result.html', label=predicted_label, confidence=confidence, image_path=filepath) return redirect(url_for('index')) # Run the app if __name__ == '__main__': app.run(debug=True)