Hey there, I’m excited to share with you my journey of creating an image classifier web app using Python!
So, as a machine learning enthusiast, I always look for opportunities to explore new concepts and projects. And building an image classifier web app has been on my to-do list for a while now.
If you’re unfamiliar with image classification, it’s a technique used in computer vision to categorize images into predefined classes or categories.
From identifying objects in images to detecting faces in pictures, image classification has numerous applications in today’s world.
So now, you might be wondering, why create an image classifier web app using Python?
Well, Python is one of the most popular programming languages for machine learning and has a wide range of libraries and packages available for image processing and classification tasks.
Moreover, creating a web app allows us to deploy our model and share it with others, making it accessible to a broader audience.
So, are you ready to join me on this exciting journey?
Let’s dive in and explore how to create an image classifier web app using Python step-by-step!
Step 1: Install the Required Libraries
First, make sure you have the following libraries installed in your Python environment:
You can install them using pip
command in the terminal.
pip install tensorflow streamlit numpy pillow
Streamlit is a pretty cool library that makes it super easy to create interactive web apps with Python.
With Streamlit, you can create an intuitive and simple interface for your app, and focus on the content you want to present rather than the technical details of the web framework.
TensorFlow is another amazing library that you can use for building deep learning models, and it provides an easy-to-use API for working with pre-trained models like Inception v3.
And don’t forget about Pillow! This handy library is perfect for handling images in Python.
Step 2: Import the Required Libraries
After installing the necessary libraries, we can import them into our Python code. We will import the following libraries:
import streamlit as st
from PIL import Image
import numpy as np
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions
streamlit
is the main library we’ll use to create our web app.PIL
is a library used for handling images in Python.numpy
is a library used for numerical operations in Python.tensorflow
is a popular library for building deep-learning models.InceptionV3
is the pre-trained image recognition model we’ll use.preprocess_input
anddecode_predictions
are helper functions from the InceptionV3 model.
Step 3: Load the Pre-Trained Inception v3 Model
The next step is to load the pre-trained Inception v3 model. We will use the weights trained on the ImageNet dataset, which has over a million images in 1,000 categories. This is a powerful model that can recognize a wide range of objects.
model = InceptionV3(weights='imagenet')
Step 4: Create the Streamlit Web App
Now, we can create the Streamlit web app. We will use Streamlit’s file_uploader
function to allow the user to upload an image.
Once the image is uploaded, we will display it on the screen and allow the user to click a button to classify it.
st.title("Image Classifier Web App using Inception v3 Model")
st.write("")
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image.', use_column_width=True)
st.write("")
st.write("Classifying...")
st.write("")
# Preprocessing the image
img_array = np.array(image)
img_array = tf.keras.preprocessing.image.smart_resize(img_array, (299, 299))
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
# Make predictions
predictions = model.predict(img_array)
results = decode_predictions(predictions, top=3)[0]
st.write("Result:")
for result in results:
st.write(f"{result[1]}: {result[2]*100:.2f}%")
Let’s closely examine what’s going on in our image classifier web app.
The first line of code sets the title of our web app to “Image Classifier Web App using Inception v3 Model”.
Then, we create a file_uploader
object that makes it super easy for our users to upload their own images, specifically, ones with the extension .jpg
.
Now, this is where things get really exciting.
Our app checks if the user has uploaded an image file, and if they have, we open that image using Pillow’s Image library and display it on the screen using Streamlit’s image
function.
But wait, there’s more.
We then go ahead and preprocess the image by resizing it to a specific shape of (299, 299) and normalizing the pixel values.
This is super important because the Inception v3 model was trained on images of this shape and with this normalization.
We’re making sure that our image fits the criteria that the model was trained on, so we can get the best possible results.
After all that preprocessing, we finally make predictions using the Inception v3 model. To get the top 3 predictions and their associated probabilities, we use the decode_predictions
function.
And last but not least, we display our results using Streamlit’s write
function. It’s amazing how much we can accomplish with just a few lines of code!
The Final Interface of the Web App
Finally, this is what our app will look like.
Once we upload the image the app will look like this.
So, as soon as we upload the image, the “Predict Now” button will appear at the end.
Let’s see what happens if we click this button.
When we click the predict now button, it displays the top three predictions with their probabilities.
The Complete Code
# Import the necessary libraries
import streamlit as st
from PIL import Image
import numpy as np
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions
# Load the pre-trained Inception v3 model
model = InceptionV3(weights='imagenet')
# Create a Streamlit web app
st.title("Inception v3 Image Classifier")
st.write("")
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image.', use_column_width=True)
st.write("")
if st.button("Predict Now"):
st.write("Classifying...")
x = np.array(image.resize((299, 299)))
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
preds_decoded = decode_predictions(preds, top=5)[0]
for pred in preds_decoded:
st.write(f"{pred[1]}: {pred[2]*100:.2f}%")
Conclusion
Yay! You did it! You’ve successfully built your own image classifier web app using Python and the Inception v3 model.
Now, your app allows users to upload images and classify them into predefined categories. Isn’t that amazing?
But, don’t stop here! This tutorial is just the beginning of your image classification journey. There are so many resources available online that can help you dive deeper into this fascinating topic.
You can find courses, books, and tutorials on various deep learning frameworks such as TensorFlow, PyTorch, and Keras, which provide an easy-to-use API for working with pre-trained models and building custom models from scratch.
I hope this tutorial has given you a great starting point for your own image recognition projects.
You should also check out my other blog posts:
- Data Visualization Web App Using Streamlit: Step-by-Step Guide
- 10 Easy Web Apps You Can Build with Python Today
- Best Python Projects for Resume
Keep exploring, keep learning, and keep building amazing things with AI. Good luck with your image classification journey!