/web-to-ai-ml-integrations

Build Image Classifier Web App with Flask

Build an image classifier web app with Flask using our step-by-step guide. Boost your coding and machine learning skills now!

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Build Image Classifier Web App with Flask

 

Creating the Flask Application and File Structure

 
  • Overview: Build a Flask web app that serves an HTML page for image upload, processes the uploaded image through a trained classifier model, and returns the prediction result.
  • File Structure: Organize your app into an app.py file for the Flask server logic, a folder called templates for the HTML files, and a folder called static for any CSS, JavaScript, or image assets.

 

Integrating the Pre-Trained Image Classifier Model

 
  • Model Choice: Use a framework like TensorFlow/Keras, PyTorch, or any image-classification library. For this guide, we assume a Keras model saved as model.h5 that has been pre-trained on your data.
  • Loading the Model: Load the model once when the Flask app starts to avoid reloading on every request.

// Import necessary modules for AI/ML functionality
from tensorflow.keras.models import load\_model
import numpy as np
import cv2    // OpenCV for image processing

// Load the pre-trained model once
model = load\_model('model.h5')
  • This model expects images of a predetermined shape (for example, 224x224 pixels). Make sure to adjust the image dimensions during pre-processing.

 

Building the Flask App Routes

 
  • Route Setup: Create two main routes: one for rendering the image upload page and one for handling the image upload (via form POST).
  • Image Upload Handling: After receiving a file, process it using OpenCV (or PIL) to make it compatible with the model’s input requirements.

// Import necessary modules from Flask
from flask import Flask, render_template, request, redirect, url_for

app = Flask(**name**)

// Home route to render upload page
@app.route('/')
def index():
    return render\_template('index.html')

// POST route to process the uploaded image
@app.route('/predict', methods=['POST'])
def predict():
    if 'file' not in request.files:
        return redirect(url\_for('index'))
    
    file = request.files['file']
    if file.filename == '':
        return redirect(url\_for('index'))
    
    // Read the image file in memory and convert to array
    file\_bytes = np.asarray(bytearray(file.read()), dtype=np.uint8)
    img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
    
    // Pre-process the image: Resize and normalize
    img\_resized = cv2.resize(img, (224, 224)) // Assuming model requires 224x224 input
    img_array = np.expand_dims(img\_resized, axis=0) / 255.0  // Normalize pixel values
    
    // Get the prediction from the model
    prediction = model.predict(img\_array)
    
    // Convert the prediction to a readable class label.
    // For example, if your model is a classifier with multiple classes:
    class\_index = np.argmax(prediction)
    confidence = prediction\[0]\[class\_index]
    
    return render_template('result.html', prediction=class_index, confidence=confidence)
    
if **name** == '**main**':
    app.run(debug=True)
  • Note: In a production environment, avoid using debug mode and consider proper error handling for robustness.

 

Creating the HTML Templates

 
  • Index Template: This template should contain an HTML form that lets users upload an image.
  • Result Template: This template displays the prediction results obtained from the model.

/_ File: templates/index.html _/

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Classifier</title>
</head>
<body>
    <h2>Upload an Image to Classify</h2>
    <form action="/predict" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" accept="image/\*" required>
        <input type="submit" value="Classify">
    </form>
</body>
</html>

/_ File: templates/result.html _/

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Prediction Results</title>
</head>
<body>
    <h2>Prediction Results</h2>
    <p>Predicted Class: <b>{{ prediction }}</b></p>
    <p>Confidence: <b>{{ confidence \* 100 | round(2) }}%</b></p>
    <a href="{{ url\_for('index') }}">Try Another Image</a>
</body>
</html>
  • Explanation: The index.html template includes form attributes such as enctype="multipart/form-data" which is required for file uploads.
  • The result.html uses Jinja templating to display variables passed from the Flask route.

 

Handling Image Pre-Processing and Model Integration

 
  • Image Decoding: The uploaded file is converted into a Numpy array and decoded to an image format using OpenCV's imdecode function.
  • Resizing: The image is resized to the dimensions expected by your model. Adjust this as per the trained model's requirement.
  • Normalization: Scale the pixel values to a 0-1 range. This step is often crucial as many models were trained on normalized data.
  • Prediction: The prediction process involves getting the highest probability class using np.argmax from the model's output array.

 

Testing and Debugging the Application

 
  • Local Testing: Run the Flask app locally and test image uploads to verify file reading, image processing, and model predictions.
  • Troubleshooting: If predictions fail, inspect the shape of the processed image (img\_array.shape) and ensure it matches the input dimensions expected by the model.
  • Verbose Logging: For debugging purposes, log intermediate outputs to console, such as image shape, pre-processed array values, and prediction outputs.

// Example of logging intermediate output
print("Image shape:", img\_array.shape)
print("Prediction output:", prediction)
  • Security Considerations: Validate the file type and limit file sizes to prevent potential attacks. Flask provides methods to check content types and set maximum file sizes.

 

Deployment Considerations

 
  • Production Server: For production, consider using a WSGI server like Gunicorn or uWSGI instead of the Flask built-in server.
  • Scaling: To handle more requests, deploy the app behind a reverse proxy (e.g., Nginx) which can also manage static file caching and SSL termination.
  • Model Optimization: For faster inference times, consider optimizing your model or using model serving frameworks like TensorFlow Serving.

 

Conclusion and Further Enhancements

 
  • Summary: This guide presented a step-by-step technical approach to integrate a pre-trained image classifier into a Flask web app. We covered file structure, model integration, image pre-processing, and return of inference results.
  • Enhancements:
    • Implement additional error handling for file reading and model prediction errors.
    • Add a feature to display the uploaded image alongside the prediction.
    • Integrate user authentication and session management for a more robust application.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â