/web-to-ai-ml-integrations

How to Process Image in Flask ML App

Step-by-step guide to process images in your Flask ML app. Boost your ML workflow and image processing skills today.

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

How to Process Image in Flask ML App

Receiving and Validating the Uploaded Image

 
  • Description: In this step, the Flask application accepts an image uploaded from the client (e.g., via an HTML form or API request) and validates it to ensure it is a valid image file format.
  • Key Concepts: We use the Flask request object to access file data. Validating the file prevents malicious or incompatible data from being processed.

// Import required modules
from flask import Flask, request, jsonify
from werkzeug.utils import secure\_filename
import os

app = Flask(name)

// Define allowed image extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
// Check if the uploaded file has one of the allowed extensions
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

// Define endpoint for image upload
@app.route('/upload', methods=['POST'])
def upload_image():
// Check if the POST request has the file part
if 'file' not in request.files:
return jsonify({'error': 'No file part provided'}), 400

file = request.files['file']

if file.filename == '':
    return jsonify({'error': 'No file selected for uploading'}), 400

if file and allowed\_file(file.filename):
    // Secure the file name to prevent directory traversal attacks
    filename = secure\_filename(file.filename)
    filepath = os.path.join('uploads', filename)
    file.save(filepath)  // Save file locally
    // Proceed to process this image
    return process\_image(filepath)
else:
    return jsonify({'error': 'Allowed file types are png, jpg, jpeg, gif'}), 400


 

Preprocessing the Image

 
  • Description: Before feeding the image into an ML model, it typically needs resizing, normalization, and conversion into an array format suitable for the ML framework.
  • Key Concepts: Use the Pillow library (commonly known as PIL) for image handling and optionally NumPy for array manipulations.

// Import necessary libraries for image handling
from PIL import Image
import numpy as np

def preprocess_image(image_path, target_size=(224, 224)):
// Open the image file using Pillow
image = Image.open(image_path)

// Convert to RGB if necessary
if image.mode != 'RGB':
    image = image.convert('RGB')

// Resize the image to the target dimensions expected by the ML model
image = image.resize(target\_size)

// Convert image to array
image\_array = np.array(image)

// Normalize pixel values to the range [0, 1] if needed
image_array = image_array.astype('float32') / 255.0

// Expand dimensions to simulate a batch of one image (if model expects batch dimension)
image_array = np.expand_dims(image\_array, axis=0)
return image\_array


 

Loading the Machine Learning Model

 
  • Description: The application needs to load a pre-trained ML model. This could be a deep learning model saved in a format like TensorFlow’s SavedModel, Keras .h5, or PyTorch model.
  • Key Concepts: Use the respective ML library's API to load the model so that it is ready to generate predictions for the preprocessed image.

// Example using TensorFlow/Keras to load a model
from tensorflow.keras.models import load\_model

// Load your pre-trained model (update the path as needed)
model = load_model('models/my_model.h5')


 

Generating Predictions Using the Model

 
  • Description: With the preprocessed image available as a properly shaped tensor, the model can now provide predictions. This step involves running the model's inference method.
  • Key Concepts: The ML model’s prediction output might require post-processing to map numerical predictions to human-understandable labels.

def predict(image\_path):
    // Preprocess the image to the required format
    processed_image = preprocess_image(image\_path)

// Generate predictions with the loaded model
predictions = model.predict(processed\_image)

// Post-process predictions if needed 
// For example, if predictions represent probabilities for classes, select the class with the highest score
predicted\_class = np.argmax(predictions, axis=1)[0]
return predicted\_class

// Integrate with the /upload route for processing after saving
def process_image(image_path):
// Get prediction from model for the processed image
result = predict(image_path)

// Return result as JSON response
return jsonify({'predicted\_class': int(result)}), 200


 

Handling Errors and Edge Cases

 
  • Description: Robust applications should address potential errors during image processing such as corrupted files, unsupported formats, or issues while loading the ML model.
  • Key Concepts: Implement appropriate exception handling using try/except constructs to capture and return meaningful error messages.

@app.errorhandler(Exception)
def handle\_exception(e):
    // If an error occurs that wasn't explicitly handled return an error message
    return jsonify({'error': str(e)}), 500

// For example, modifying the preprocess_image function with error handling can be done as follows:
def safe_preprocess_image(image_path, target_size=(224, 224)):
try:
return preprocess_image(image_path, target_size)
except Exception as e:
raise ValueError("Error during image preprocessing: " + str(e))


 

Wrapping Up the Flask Machine Learning App

 
  • Description: Ensure that your Flask application is ready to handle incoming requests and that all components (uploading, preprocessing, model prediction) work in harmony. This involves testing the endpoints and verifying that the predictions are accurate.
  • Key Concepts: Carefully design the endpoint(s) to integrate all steps, so the application continuously provides valuable feedback on image processing.

// Add main block to run the Flask app
if **name** == '**main**':
    // Ensure directories such as 'uploads' exist
    if not os.path.exists('uploads'):
        os.makedirs('uploads')
    app.run(debug=True)  // Run Flask application in debug mode for troubleshooting
 


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.Â