DasariHarshitha commited on
Commit
1493076
Β·
verified Β·
1 Parent(s): c73cc6c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -108
app.py CHANGED
@@ -1,108 +1,108 @@
1
- import streamlit as st
2
- import os
3
- import cv2
4
- import numpy as np
5
- import pandas as pd
6
- import random
7
- from sklearn.model_selection import train_test_split
8
- from sklearn.linear_model import LogisticRegression
9
- from sklearn.neighbors import KNeighborsClassifier
10
- from sklearn.tree import DecisionTreeClassifier
11
-
12
- # ------------------------ PAGE CONFIG & STYLING ------------------------
13
- st.set_page_config(page_title="Potato Leaf Disease Classifier", layout="centered")
14
-
15
- # Custom background styling (you must place 'Plant.jpg' in the root folder)
16
- st.markdown("""
17
- <style>
18
- .stApp {
19
- background-image: url('Plant.jpg');
20
- background-size: cover;
21
- background-attachment: fixed;
22
- background-position: center;
23
- backdrop-filter: blur(2px);
24
- }
25
- </style>
26
- """, unsafe_allow_html=True)
27
-
28
- # ------------------------ TITLE & DESCRIPTION ------------------------
29
- st.title("πŸ₯” Potato Leaf Disease Classifier")
30
- st.markdown("""
31
- <div style='font-size: 17px; line-height: 1.6;'>
32
- This project aims to automatically classify the health condition of potato leaves using grayscale images from different disease categories.
33
- The model helps farmers and agricultural experts identify potential diseases early and take appropriate actions to ensure healthy crop production.
34
- </div>
35
- """, unsafe_allow_html=True)
36
-
37
- # ------------------------ CONFIG ------------------------
38
- BASE_PATH = r"C:/Users/Harshu/OneDrive/Documents/Potato/PotatoPlants" # Ensure this folder exists in your app's directory
39
- folders = [f for f in os.listdir(BASE_PATH) if os.path.isdir(os.path.join(BASE_PATH, f))]
40
-
41
- # ------------------------ MODEL SELECTION ------------------------
42
- st.markdown("<h4 style='margin-top: 30px;'>🧠 <b>Select Classifier</b></h4>", unsafe_allow_html=True)
43
-
44
- model_choice = st.selectbox(
45
- "Choose a machine learning model to classify potato diseases",
46
- ["Logistic Regression", "KNN", "Decision Tree"],
47
- index=0
48
- )
49
-
50
- # ------------------------ LOAD DATA ------------------------
51
- @st.cache_data
52
- def load_data():
53
- images, labels = [], []
54
- for folder in folders:
55
- full_path = os.path.join(BASE_PATH, folder)
56
- for img_name in os.listdir(full_path):
57
- img_path = os.path.join(full_path, img_name)
58
- img = cv2.imread(img_path, 0) # Read in grayscale
59
- if img is not None:
60
- resized = cv2.resize(img, (100, 100))
61
- images.append(resized.flatten())
62
- labels.append(folder.split("___")[-1])
63
- return pd.DataFrame(images), pd.Series(labels)
64
-
65
- X, y = load_data()
66
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=27)
67
-
68
- # ------------------------ MODEL TRAINING ------------------------
69
- st.markdown("### πŸ”§ Training the model...")
70
-
71
- with st.spinner("Training in progress..."):
72
- if model_choice == "Logistic Regression":
73
- model = LogisticRegression(max_iter=200)
74
- elif model_choice == "KNN":
75
- model = KNeighborsClassifier()
76
- else:
77
- model = DecisionTreeClassifier()
78
-
79
- model.fit(X_train, y_train)
80
- accuracy = model.score(X_test, y_test)
81
-
82
- st.success(f"βœ… {model_choice} trained with accuracy: **{accuracy:.2f}**")
83
-
84
- # ------------------------ RANDOM IMAGE TESTING ------------------------
85
- st.markdown("### πŸ” Test on a Random Image")
86
-
87
- if st.button("Test Random Image"):
88
- random_folder = random.choice(folders)
89
- folder_path = os.path.join(BASE_PATH, random_folder)
90
- random_image_file = random.choice(os.listdir(folder_path))
91
- image_path = os.path.join(folder_path, random_image_file)
92
-
93
- img = cv2.imread(image_path, 0)
94
- resized = cv2.resize(img, (100, 100))
95
- flat = resized.flatten().reshape(1, -1)
96
- prediction = model.predict(flat)[0]
97
- actual = random_folder.split("___")[-1]
98
-
99
- # Convert grayscale to RGB for better browser compatibility
100
- color_img = cv2.cvtColor(resized, cv2.COLOR_GRAY2RGB)
101
-
102
- st.image(color_img, caption="πŸ“· Randomly selected potato leaf", use_container_width=True)
103
- st.markdown(f"<h3 style='color:green;'>βœ… Actual: <b>{actual}</b></h3>", unsafe_allow_html=True)
104
- st.markdown(f"<h3 style='color:blue;'>πŸ€– Predicted: <b>{prediction}</b></h3>", unsafe_allow_html=True)
105
-
106
- # ------------------------ FOOTER ------------------------
107
- st.markdown("---")
108
- st.markdown("<center>Made with ❀️ for smart agriculture 🌾</center>", unsafe_allow_html=True)
 
1
+ import streamlit as st
2
+ import os
3
+ import cv2
4
+ import numpy as np
5
+ import pandas as pd
6
+ import random
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.neighbors import KNeighborsClassifier
10
+ from sklearn.tree import DecisionTreeClassifier
11
+
12
+ # ------------------------ PAGE CONFIG & STYLING ------------------------
13
+ st.set_page_config(page_title="Potato Leaf Disease Classifier", layout="centered")
14
+
15
+ # Custom background styling (you must place 'Plant.jpg' in the root folder)
16
+ st.markdown("""
17
+ <style>
18
+ .stApp {
19
+ background-image: url('Plant.jpg');
20
+ background-size: cover;
21
+ background-attachment: fixed;
22
+ background-position: center;
23
+ backdrop-filter: blur(2px);
24
+ }
25
+ </style>
26
+ """, unsafe_allow_html=True)
27
+
28
+ # ------------------------ TITLE & DESCRIPTION ------------------------
29
+ st.title("πŸ₯” Potato Leaf Disease Classifier")
30
+ st.markdown("""
31
+ <div style='font-size: 17px; line-height: 1.6;'>
32
+ This project aims to automatically classify the health condition of potato leaves using grayscale images from different disease categories.
33
+ The model helps farmers and agricultural experts identify potential diseases early and take appropriate actions to ensure healthy crop production.
34
+ </div>
35
+ """, unsafe_allow_html=True)
36
+
37
+ # ------------------------ CONFIG ------------------------
38
+ BASE_PATH = r"PotatoPlants" # Ensure this folder exists in your app's directory
39
+ folders = [f for f in os.listdir(BASE_PATH) if os.path.isdir(os.path.join(BASE_PATH, f))]
40
+
41
+ # ------------------------ MODEL SELECTION ------------------------
42
+ st.markdown("<h4 style='margin-top: 30px;'>🧠 <b>Select Classifier</b></h4>", unsafe_allow_html=True)
43
+
44
+ model_choice = st.selectbox(
45
+ "Choose a machine learning model to classify potato diseases",
46
+ ["Logistic Regression", "KNN", "Decision Tree"],
47
+ index=0
48
+ )
49
+
50
+ # ------------------------ LOAD DATA ------------------------
51
+ @st.cache_data
52
+ def load_data():
53
+ images, labels = [], []
54
+ for folder in folders:
55
+ full_path = os.path.join(BASE_PATH, folder)
56
+ for img_name in os.listdir(full_path):
57
+ img_path = os.path.join(full_path, img_name)
58
+ img = cv2.imread(img_path, 0) # Read in grayscale
59
+ if img is not None:
60
+ resized = cv2.resize(img, (100, 100))
61
+ images.append(resized.flatten())
62
+ labels.append(folder.split("___")[-1])
63
+ return pd.DataFrame(images), pd.Series(labels)
64
+
65
+ X, y = load_data()
66
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=27)
67
+
68
+ # ------------------------ MODEL TRAINING ------------------------
69
+ st.markdown("### πŸ”§ Training the model...")
70
+
71
+ with st.spinner("Training in progress..."):
72
+ if model_choice == "Logistic Regression":
73
+ model = LogisticRegression(max_iter=200)
74
+ elif model_choice == "KNN":
75
+ model = KNeighborsClassifier()
76
+ else:
77
+ model = DecisionTreeClassifier()
78
+
79
+ model.fit(X_train, y_train)
80
+ accuracy = model.score(X_test, y_test)
81
+
82
+ st.success(f"βœ… {model_choice} trained with accuracy: **{accuracy:.2f}**")
83
+
84
+ # ------------------------ RANDOM IMAGE TESTING ------------------------
85
+ st.markdown("### πŸ” Test on a Random Image")
86
+
87
+ if st.button("Test Random Image"):
88
+ random_folder = random.choice(folders)
89
+ folder_path = os.path.join(BASE_PATH, random_folder)
90
+ random_image_file = random.choice(os.listdir(folder_path))
91
+ image_path = os.path.join(folder_path, random_image_file)
92
+
93
+ img = cv2.imread(image_path, 0)
94
+ resized = cv2.resize(img, (100, 100))
95
+ flat = resized.flatten().reshape(1, -1)
96
+ prediction = model.predict(flat)[0]
97
+ actual = random_folder.split("___")[-1]
98
+
99
+ # Convert grayscale to RGB for better browser compatibility
100
+ color_img = cv2.cvtColor(resized, cv2.COLOR_GRAY2RGB)
101
+
102
+ st.image(color_img, caption="πŸ“· Randomly selected potato leaf", use_container_width=True)
103
+ st.markdown(f"<h3 style='color:green;'>βœ… Actual: <b>{actual}</b></h3>", unsafe_allow_html=True)
104
+ st.markdown(f"<h3 style='color:blue;'>πŸ€– Predicted: <b>{prediction}</b></h3>", unsafe_allow_html=True)
105
+
106
+ # ------------------------ FOOTER ------------------------
107
+ st.markdown("---")
108
+ st.markdown("<center>Made with ❀️ for smart agriculture 🌾</center>", unsafe_allow_html=True)