Image Classifier Deployment (Flask)
AdvancedProject 3 — Image Classifier Deployment (Flask)
File: project3_flask_deploy.py
Purpose: Flask server that loads a saved model (for example cnn_mnist.h5) and exposes /predict endpoint. This script expects cnn_mnist.h5 to exist (created by Project 1).
# project3_flask_deploy.py
from flask import Flask, request, jsonify
import numpy as np
import tensorflow as tf
app = Flask(__name__)
# Load Keras model (make sure cnn_mnist.h5 exists)
MODEL_PATH = "cnn_mnist.h5"
model = tf.keras.models.load_model(MODEL_PATH)
print("Model loaded from", MODEL_PATH)
@app.route("/")
def index():
return "ML Model Deployment - POST JSON to /predict with {'image': flattened_list}"
@app.route("/predict", methods=["POST"])
def predict():
"""
Expects JSON:
{
"image": [0.0, 0.1, ..., 0.0] # length 28*28 flattened values in range 0..1
}
"""
data = request.get_json(force=True)
if "image" not in data:
return jsonify({"error": "Send JSON with key 'image'"}), 400
flat = data["image"]
try:
arr = np.array(flat, dtype=np.float32)
arr = arr.reshape(1, 28, 28, 1) # adapt if your model uses different shape
except Exception as e:
return jsonify({"error": f"Invalid image data: {e}"}), 400
preds = model.predict(arr)
class_idx = int(np.argmax(preds, axis=1)[0])
conf = float(np.max(preds, axis=1)[0])
return jsonify({"class": class_idx, "confidence": conf})
if __name__ == "__main__":
# Run Flask app
app.run(host="0.0.0.0", port=5000, debug=True)How to test
- Start the server:
python project3_flask_deploy.py - Send a JSON POST (example using curl). You must prepare a flattened 28x28 grayscale image array with values in [0,1]:
curl -X POST http://127.0.0.1:5000/predict -H "Content-Type: application/json" \ -d "{\"image\": [0.0,0.0,...,0.0]}" # replace ... with 784 numbers
Tip:
To test quickly, you can use a sample from MNIST in Python, flatten it and POST it (example below):
# quick test client (run separately)
import json, requests
from tensorflow.keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
image = (X_test[0].astype("float32") / 255.0).reshape(-1).tolist()
resp = requests.post("http://127.0.0.1:5000/predict", json={"image": image})
print(resp.json())Requirements
pip install flask tensorflow requests