Path: blob/main/streamlit_app.py
78 views
from __future__ import division, print_function1import streamlit as st2from PIL import Image, ImageOps34# coding=utf-85import sys6import os7import glob8import re9import numpy as np10import tensorflow as tf1112import pathlib13import wget1415from tensorflow.keras.applications.resnet50 import preprocess_input16from tensorflow.keras.models import load_model17from tensorflow.keras.preprocessing import image1819# Flask utils20from flask import Flask, redirect, url_for, request, render_template21from werkzeug.utils import secure_filename2223# from gevent.pywsgi import WSGIServer2425# Model saved with Keras model.save()26MODEL_PATH = 'model_resnet.hdf5'27MODEL_URL = 'https://github.com/DARK-art108/Cotton-Leaf-Disease-Prediction/releases/download/v1.0/model_resnet.hdf5'28UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'static', 'uploads')2930# Download model if not present31while not pathlib.Path(MODEL_PATH).is_file():32print(f'Model {MODEL_PATH} not found. Downloading...')33wget.download(MODEL_URL)3435# Define a flask app36app = Flask(__name__)3738# Define upload path39app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER4041# Developing in the absence of TensorFlow :P (Python 3.9.0 x64)42# def load_model(aa):43# class a:44# @staticmethod45# def predict(*args):46# return 147# return a()4849# class image:50# @staticmethod51# def load_img(path, target_size):52# return 'a'5354# @staticmethod55# def img_to_array(img):56# return 'v'5758# Load your trained model5960model = load_model(MODEL_PATH)61def model_predict(img, MODEL_PATH):62# Create the array of the right shape to feed into the keras model63data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)64image = img65#image sizing66size = (224, 224)67image = ImageOps.fit(image, size, Image.ANTIALIAS)6869#turn the image into a numpy array70image_array = np.asarray(image)71# Normalize the image72normalized_image_array = (image_array.astype(np.float32) / 127.0) - 17374# Load the image into the array75data[0] = normalized_image_array7677# run the inference78prediction = model.predict(data)79return np.argmax(prediction, axis=1) # return position of the highest probability8081st.title("Cotton Leaf Disease Prediction")82st.header("Transfer Learning Using RESNET51V2")83st.text("Upload a Cotton Leaf Disease or Non-Diseased Image")8485uploaded_file = st.file_uploader("Choose a Cotton Leaf Image...", type="jpg")86if uploaded_file is not None:87image = Image.open(uploaded_file)88st.image(image, caption='Uploaded Cotton Leaf Image', use_column_width=True)89st.write("")90st.write("Classifying...")91label = model_predict(image, 'model_resnet.hdf5')92if label == 0:93st.write("The leaf is a diseased cotton leaf.")94elif label == 1:95st.write("The leaf is a diseased cotton plant.")96elif label == 2:97st.write("The leaf is a fresh cotton leaf.")98else:99st.write("The leaf is a fresh cotton plant.")100101102