jkisolo.com

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:

  1. Title
  2. Sidebar
  3. Subheader
  4. 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.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Unlocking the Secrets of ChatGPT and DALLE: AI Prompt Mastery

Discover how to modify ChatGPT's system prompts to improve your AI-generated outputs and explore the flexibility of DALLE.

Unearthing Ancient Viruses: Insights from Tibetan Glacier Ice

Scientists have discovered ancient viruses in Tibetan glacier ice, shedding light on the past and potential impacts on climate change.

Innovative Approaches to RAG: Embracing Full-Document Retrieval

Explore the evolution of Retrieval Augmented Generation (RAG) and the benefits of full-document retrieval.

Understanding Ansible Variables: A Comprehensive Guide

Explore the significance of Ansible variables, their definition, usage, and best practices for effective automation management.

A Holistic Approach to Healing: Welcome to the HEAL Institute

Discover the HEAL Institute, a holistic healing space that fosters personal growth and wellness for everyone.

Embracing Change: A Journey Through Life's Transitions

Explore the bittersweet nature of change and personal growth through poetry and reflection, and find motivation for your own journey.

Mastering Small Talk: 5 Essential Tips for Instant Connections

Discover five key strategies for improving small talk and making genuine connections with others.

Meditate Together: Discovering Tranquility in a Digital Era

Explore how Meditate Together unites individuals in mindfulness and tranquility, offering a virtual space for self-discovery and community.