-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
60 lines (46 loc) · 1.84 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import json
from PIL import Image
import numpy as np
import tensorflow as tf
import streamlit as st
working_dir = os.path.dirname(os.path.abspath(__file__))
model_path = f"{working_dir}/trained_model/plant_disease_prediction_model.h5"
# Load the pre-trained model
model = tf.keras.models.load_model(model_path)
# loading the class names
class_indices = json.load(open(f"{working_dir}/class_indices.json"))
# Function to Load and Preprocess the Image using Pillow
def load_and_preprocess_image(image_path, target_size=(224, 224)):
# Load the image
img = Image.open(image_path)
# Resize the image
img = img.resize(target_size)
# Convert the image to a numpy array
img_array = np.array(img)
# Add batch dimension
img_array = np.expand_dims(img_array, axis=0)
# Scale the image values to [0, 1]
img_array = img_array.astype('float32') / 255.
return img_array
# Function to Predict the Class of an Image
def predict_image_class(model, image_path, class_indices):
preprocessed_img = load_and_preprocess_image(image_path)
predictions = model.predict(preprocessed_img)
predicted_class_index = np.argmax(predictions, axis=1)[0]
predicted_class_name = class_indices[str(predicted_class_index)]
return predicted_class_name
# Streamlit App
st.title('Plant Disease Classifier')
uploaded_image = st.file_uploader("Upload an image...", type=["jpg", "jpeg", "png"])
if uploaded_image is not None:
image = Image.open(uploaded_image)
col1, col2 = st.columns(2)
with col1:
resized_img = image.resize((150, 150))
st.image(resized_img)
with col2:
if st.button('Classify'):
# Preprocess the uploaded image and predict the class
prediction = predict_image_class(model, uploaded_image, class_indices)
st.success(f'Prediction: {str(prediction)}')