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

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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
// 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
// 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')
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
@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))
// 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
From startups to enterprises and everything in between, see for yourself our incredible impact.
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.Â