/web-to-ai-ml-integrations

Upload Image to Web App and Run ML Model

Step-by-step guide: Upload images to your web app and run an ML model for fast, effective AI insights.

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

Upload Image to Web App and Run ML Model

Building the Upload Form (Front End)

 
  • Objective: Create a simple HTML form that allows users to select an image file from their computer and upload it to the web application.
  • Key Elements Explained:
    • Form Tag: Defines the portion of the page which takes user input.
    • Input Type "file": Lets users browse and select an image file.
    • Submit Button: Initiates the file upload to the backend server.

// HTML form for image upload


  
    
// Multipart encoding is essential for file uploads // 'accept' attribute to filter image file types // Button to submit the form
 

Handling File Upload in the Back End

 
  • Objective: Create a backend endpoint that receives the uploaded image file from the form.
  • Explanation: The backend framework (e.g., Flask in Python) will define a route for "/upload" that processes the POST request.
  • Technical Note: When configuring your route, ensure you handle the file stream properly and perform error checks to confirm a file is indeed being uploaded.

import os
from flask import Flask, request, redirect, url_for, render_template // Importing necessary modules
from werkzeug.utils import secure\_filename // Utility to secure the file name before saving

app = Flask(name)
app.config["UPLOAD_FOLDER"] = "uploads" // Define a folder to save the uploaded files
app.config["ALLOWED_EXTENSIONS"] = {"png", "jpg", "jpeg", "gif"} // Acceptable image formats

def allowed_file(filename):
// Check if the file extension is allowed
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"]

@app.route("/upload", methods=["POST"])
def upload_image():
if "image" not in request.files:
return "No file part in the request", 400 // Bad request if file key is missing
file = request.files["image"]
if file.filename == "":
return "No selected file", 400 // Bad request for empty file name
if file and allowed_file(file.filename):
filename = secure_filename(file.filename) // Prevent directory traversal
file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(file_path) // Save file to server
// Once saved, proceed to process the image with the ML model
result = run_ml_model(file_path) // Passing file path to ML model function
return render_template("result.html", result=result) // Render result on a new page
else:
return "File type not permitted", 400 // Return error for disallowed file types

// For local testing set
if name == "main":
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True) // Ensure the uploads folder exists
app.run(debug=True)


 

Processing and Preprocessing the Image

 
  • Objective: Read the saved image file and apply any preprocessing needed before feeding it into the ML model.
  • Explanation: Preprocessing might include resizing, normalizing pixel values, converting to grayscale, etc.
  • Technical Note: Use libraries like Pillow (PIL) or OpenCV for preprocessing. The choice depends on your model's requirements.

from PIL import Image
import numpy as np

def preprocess_image(image_path):
// Open the image using PIL
img = Image.open(image_path)
// Resize the image to 224x224 pixels if required by the ML model
img = img.resize((224, 224))
// Convert image to a numpy array for further processing
img_array = np.array(img)
// Optional: Normalize the pixel values to the range [0, 1]
img_array = img_array / 255.0
// Expand dimensions if the model expects a batch (e.g., shape becomes (1, 224, 224, 3))
img_array = np.expand_dims(img_array, axis=0)
return img_array


 

Integrating the ML Model

 
  • Objective: Load your trained ML model and run inference using the preprocessed image.
  • Explanation: The ML model can be built using frameworks such as TensorFlow, PyTorch, or scikit-learn, and this guide demonstrates integration with a model that accepts image data.
  • Important Considerations: Ensure that the model is loaded once (outside the request function if possible) to optimize performance. Also, match the input shape of the preprocessed image to that expected by the model.

import tensorflow as tf

// Pre-load the model when the server starts to avoid reloading on each request
model = tf.keras.models.load_model("my_trained_model.h5") // Assuming your model is saved in Keras format

def run_ml_model(image_path):
// Preprocess the image
processed_img = preprocess_image(image_path)
// Run model inference to predict the content of the image
predictions = model.predict(processed_img)
// Process predictions, e.g., convert probabilities to class labels
// This example assumes a classification task
predicted_class = tf.argmax(predictions, axis=1).numpy()[0]
return predicted_class


 

Returning the Prediction in the Web App

 
  • Objective: Send the inference result back to the user through the web interface.
  • Explanation: After processing the image and running the ML model, display the result in a user-friendly format. Use templating engines (like Jinja2 with Flask) to dynamically insert the model's output into an HTML page.
  • Technical Tip: Ensure proper error handling and user feedback if something goes wrong during upload or processing.

// Example Flask route rendering the result using a template

@app.route("/result")
def show_result():
// The 'result.html' template should be designed to display the prediction outcome
return render_template("result.html", result="Insert your prediction here")


 


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