aiinnovators4/MobileNetV2
1
1from flask import Flask, request, render_template2from PIL import Image3import numpy as np4import tensorflow as tf5from tensorflow.keras.models import load_model6from tensorflow.keras.preprocessing import image as img_prep7import os8import tempfile9app = Flask(__name__)10 11# Load your trained model12model = load_model('animal_recognition_model.h5')13 14# Define class labels15classes = [16 'ArmaDillo', 'Bear', 'Birds', 'Cow', 'Crocodile', 'Deer', 'Elephant',17 'Goat', 'Horse', 'Jaguar', 'Monkey', 'Rabbit', 'Skunk', 'Tiger', 'Wild Boar'18]19 20# Image preprocessing function21def preprocess_image(image_path):22 try:23 img = Image.open(image_path)24 if img.mode != 'RGB':25 img = img.convert('RGB')26 img = img.resize((224, 224)) # Adjust to model input size27 img = img_prep.img_to_array(img)28 img = np.expand_dims(img, axis=0)29 img = img / 255.030 return img31 except Exception as e:32 print("Error processing image:", e)33 return None34 35# Prediction function36def predict(image_path):37 img = preprocess_image(image_path)38 if img is None:39 return "Image processing failed", "null"40 41 prediction = model.predict(img)42 confidence = np.max(prediction)43 if confidence > 0.85:44 predicted_class = classes[np.argmax(prediction)]45 return predicted_class, int(confidence * 100)46 else:47 return "No animal predicted", "null"48 49@app.route('/')50def home():51 return render_template('index.html') # Ensure this HTML file exists52 53@app.route('/predict', methods=['POST'])54def predict_route():55 if 'file' not in request.files:56 return "No file part in the request"57 58 file = request.files['file']59 if file.filename == '':60 return "No selected file"61 62 with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:63 image_path = tmp.name64 file.save(image_path)65 66 67 predicted_class, confidence = predict(image_path)68 69 # Clean up temporary file70 if os.path.exists(image_path):71 os.remove(image_path)72 73 return f"""74 Predicted Class: {predicted_class}75 Confidence: {confidence}%76 """77 78if __name__ == '__main__':79 app.run(host="0.0.0.0", port=7860, debug=True)80 