Update app.py
Browse files
app.py
CHANGED
@@ -1,38 +1,95 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import joblib
|
3 |
-
import numpy as np
|
4 |
-
from sklearn.neighbors import KNeighborsClassifier
|
5 |
-
from tensorflow.keras.preprocessing import image
|
6 |
import os
|
|
|
|
|
7 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
#
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
#
|
20 |
-
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
img_array = np.array(img) # Convert the image to numpy array
|
30 |
-
img_array = img_array.flatten().reshape(1, -1) # Flatten the image and reshape it to match the input for KNN model
|
31 |
|
32 |
-
#
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
-
|
37 |
-
|
38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import numpy as np
|
3 |
+
import joblib
|
4 |
from PIL import Image
|
5 |
+
import streamlit as st
|
6 |
+
from sklearn.neighbors import KNeighborsClassifier
|
7 |
+
from sklearn.model_selection import train_test_split
|
8 |
+
from sklearn.metrics import accuracy_score
|
9 |
+
|
10 |
+
# Paths and global constants
|
11 |
+
#DATASET_PATH = "path_to_your_dataset" # Update with your dataset path
|
12 |
+
MODEL_PATH = "knn_model.pkl"
|
13 |
+
CLASS_NAMES_PATH = "class_names.pkl"
|
14 |
+
TARGET_SIZE = (64, 64)
|
15 |
|
16 |
+
# Helper function to load and preprocess dataset
|
17 |
+
def load_dataset(dataset_path, target_size):
|
18 |
+
images = []
|
19 |
+
labels = []
|
20 |
+
class_names = sorted(os.listdir(dataset_path)) # Sort for consistent class indexing
|
21 |
+
for idx, class_name in enumerate(class_names):
|
22 |
+
class_path = os.path.join(dataset_path, class_name)
|
23 |
+
if not os.path.isdir(class_path):
|
24 |
+
continue
|
25 |
+
for image_name in os.listdir(class_path):
|
26 |
+
image_path = os.path.join(class_path, image_name)
|
27 |
+
try:
|
28 |
+
img = Image.open(image_path).convert('RGB')
|
29 |
+
img = img.resize(target_size)
|
30 |
+
img_array = np.array(img).flatten() # Flatten to a single array
|
31 |
+
images.append(img_array)
|
32 |
+
labels.append(idx)
|
33 |
+
except Exception as e:
|
34 |
+
print(f"Error loading image {image_path}: {e}")
|
35 |
+
return np.array(images), np.array(labels), class_names
|
36 |
|
37 |
+
# Function to train and save KNN model
|
38 |
+
def train_and_save_model(dataset_path, target_size, model_path, class_names_path):
|
39 |
+
# Load data
|
40 |
+
X, y, class_names = load_dataset(dataset_path, target_size)
|
41 |
+
# Split dataset
|
42 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
|
43 |
+
# Train KNN model
|
44 |
+
knn = KNeighborsClassifier(n_neighbors=3)
|
45 |
+
knn.fit(X_train, y_train)
|
46 |
+
# Evaluate model
|
47 |
+
y_pred = knn.predict(X_test)
|
48 |
+
accuracy = accuracy_score(y_test, y_pred)
|
49 |
+
print(f"KNN Model Accuracy: {accuracy * 100:.2f}%")
|
50 |
+
# Save model and class names
|
51 |
+
joblib.dump(knn, model_path)
|
52 |
+
joblib.dump(class_names, class_names_path)
|
53 |
+
print(f"Model and class names saved to {model_path} and {class_names_path}")
|
54 |
+
return knn, class_names
|
55 |
|
56 |
+
# Preprocess image for prediction
|
57 |
+
def preprocess_image(image_path, target_size):
|
58 |
+
img = Image.open(image_path).convert('RGB')
|
59 |
+
img = img.resize(target_size)
|
60 |
+
img_array = np.array(img).flatten()
|
61 |
+
return img_array.reshape(1, -1) # Add batch dimension
|
62 |
|
63 |
+
# Main Streamlit app
|
64 |
+
def main():
|
65 |
+
st.title("Animal Classifier")
|
66 |
+
st.write("Upload an image of an animal to predict its category.")
|
67 |
|
68 |
+
# Load model and class names
|
69 |
+
if not os.path.exists(MODEL_PATH) or not os.path.exists(CLASS_NAMES_PATH):
|
70 |
+
st.error("Model or class names file not found. Please train the model first.")
|
71 |
+
return
|
72 |
|
73 |
+
knn = joblib.load(MODEL_PATH)
|
74 |
+
class_names = joblib.load(CLASS_NAMES_PATH)
|
|
|
|
|
75 |
|
76 |
+
# Upload image
|
77 |
+
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
78 |
+
if uploaded_file:
|
79 |
+
st.image(uploaded_file, caption="Uploaded Image", use_container_width=True)
|
80 |
+
try:
|
81 |
+
img_array = preprocess_image(uploaded_file, TARGET_SIZE)
|
82 |
+
if img_array.shape[1] != knn.n_features_in_:
|
83 |
+
st.error(f"Feature size mismatch: Model expects {knn.n_features_in_} features, but input has {img_array.shape[1]}.")
|
84 |
+
else:
|
85 |
+
prediction = knn.predict(img_array)
|
86 |
+
st.success(f"The predicted animal is: {class_names[prediction[0]]}")
|
87 |
+
except Exception as e:
|
88 |
+
st.error(f"Error processing image: {e}")
|
89 |
|
90 |
+
# Train and save model (Uncomment if running for the first time)
|
91 |
+
# train_and_save_model(DATASET_PATH, TARGET_SIZE, MODEL_PATH, CLASS_NAMES_PATH)
|
92 |
|
93 |
+
# Run Streamlit app
|
94 |
+
if __name__ == "__main__":
|
95 |
+
main()
|