Creating a Fruit Detection Web App Using Streamlit and Python
Written on
Chapter 1: Introduction to Streamlit
In this guide, we will explore how to leverage the Streamlit web framework to create a web application for detecting and counting fruits from images. Streamlit is a highly effective tool for machine learning and data analytics, renowned for its user-friendliness and ease of deployment, particularly on platforms like Heroku.
We will develop a fruit detection application, making use of various Streamlit features such as:
- Title
- Sidebar
- Subheader
- Selectbox
For additional Streamlit features, please refer to the relevant articles.
Let's get started with our web application in Python!
Section 1.1: Setting Up Your Environment
First, we need to import all the essential libraries:
import streamlit as st
import random
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import imutils
import cv2
import warnings
warnings.filterwarnings('ignore')
To create a wider layout for our Streamlit app, we will adjust the page configuration:
st.set_page_config(layout="wide")
Next, we will add a title to the sidebar:
st.sidebar.header("This App Localizes Fruits and Counts Them in Images")
We will now set a title for the main page and utilize a subheader and selectbox to allow users to choose the type of fruit image:
st.title("Fruit Detection and Counting")
menu = ['Blue Grape Image', 'Orange', 'Apple', 'Pineapple']
st.subheader('Select a Fruit Image')
fruit_choice = st.selectbox('Choose the type of Fruit Image', menu)
To display images in three separate columns, Streamlit provides a straightforward method:
col1, col2, col3 = st.columns(3)
Now, let's proceed with the image processing and showcase the input and output images in these columns.
Subsection 1.1.1: Image Processing
with col1:
if fruit_choice == "Apple":
st.subheader("Input Image")
image1 = Image.open("apple.jpg")
st.image(image1)
image = cv2.imread('apple.jpg')
dst = cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 15)
cv2.imwrite('dst.jpg', dst)
rgb_image = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
new_image = cv2.medianBlur(rgb_image, 5)
ycbcr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2YCrCb)
Y, Cr, Cb = cv2.split(ycbcr_image)
ret, th1 = cv2.threshold(Cr, 180, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
nb_comp, output, stats, centroids = cv2.connectedComponentsWithStats(th1, connectivity=8)
sizes = stats[1:, -1]
nb_comp -= 1
min_size = 7000
img2 = np.zeros((output.shape))
for i in range(0, nb_comp):
if sizes[i] >= min_size:
img2[output == i + 1] = 255
img3 = img2.astype(np.uint8)
cnts = cv2.findContours(img3.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
print("[INFO] {} unique contours found".format(len(cnts)))
for (i, c) in enumerate(cnts):
((x, y), _) = cv2.minEnclosingCircle(c)
cv2.putText(image, "#{}".format(i + 1), (int(x) - 10, int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
with col2:
st.subheader("Mask Image")
image2 = Image.open("img2.jpg")
st.image(image2)
with col3:
st.subheader("Output Image")
image3 = Image.open("Result_Apple_Image.jpg")
st.image(image3)
This three-column approach can similarly be applied to other fruits.
Section 1.2: Displaying Results
To present the data on the sidebar and display the results of the detected fruit areas, we can use the following code:
if fruit_choice == "Apple":
st.sidebar.subheader("Denoising Filters Used")
st.sidebar.text("Fast Non-Local Means")
st.sidebar.subheader("Blur Filters Used")
st.sidebar.text("Median")
st.sidebar.subheader("Color Space Channel Used")
st.sidebar.text("Cr Channel in YCrCb")
st.sidebar.subheader("Thresholding Used")
st.sidebar.text("Binary and OTSU")
st.text("Fruit Count and Pixel Area Information")
st.markdown(f"The number of apples in the image is {len(cnts):}")
area_list = []
for i in range(len(cnts)):
count = cnts[i]
area = cv2.contourArea(count)
st.markdown(f"The area of apple object ** {i + 1:} **is: {area:} Pixels")
area_list.append(area)
To run the application from the terminal, use the following command:
streamlit run app.py
We hope you find this guide helpful! Feel free to connect with me on LinkedIn and Twitter for more insights.
Chapter 2: Video Tutorials
To further enhance your understanding, check out these informative videos:
This video titled "Creating an Awesome Web App with Python and Streamlit" showcases the process of building an engaging web application using Python and Streamlit.
In this video, "Build A Beautiful Machine Learning Web App With Streamlit And Scikit-learn," you will learn how to integrate machine learning capabilities into your Streamlit web app.