Update app.py
Browse files
app.py
CHANGED
@@ -1,95 +1,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
|
8 |
-
|
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 |
-
#
|
17 |
-
|
18 |
-
|
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 |
-
#
|
38 |
-
|
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 |
-
#
|
57 |
-
|
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 |
-
#
|
64 |
-
|
65 |
-
st.title("Animal Classifier")
|
66 |
-
st.write("Upload an image of an animal to predict its category.")
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
|
73 |
-
|
74 |
-
|
|
|
|
|
75 |
|
76 |
-
#
|
77 |
-
|
78 |
-
|
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 |
-
#
|
91 |
-
|
92 |
|
93 |
-
# Run Streamlit app
|
94 |
-
if __name__ == "__main__":
|
95 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Load the pre-trained KNN model and class names
|
10 |
+
knn = joblib.load('knn_model.pk1')
|
11 |
+
class_names = joblib.load('class_names.pk1')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
# Title of the app
|
14 |
+
st.title("Animal Classification Using KNN Model")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
# Description
|
17 |
+
st.write("Upload an image of an animal and the model will predict which animal it is.")
|
|
|
|
|
|
|
|
|
18 |
|
19 |
+
# Upload image
|
20 |
+
uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
|
|
|
|
21 |
|
22 |
+
if uploaded_image is not None:
|
23 |
+
# Display image
|
24 |
+
img = Image.open(uploaded_image)
|
25 |
+
st.image(img, caption='Uploaded Image.', use_column_width=True)
|
26 |
|
27 |
+
# Preprocess the image for prediction
|
28 |
+
img = img.resize((64, 64)) # Resize the image to match the model's expected size (adjust if needed)
|
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 |
+
# Make prediction
|
33 |
+
prediction = knn.predict(img_array)
|
34 |
+
predicted_class = class_names[prediction[0]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
+
# Display prediction
|
37 |
+
st.write(f"Prediction: {predicted_class}")
|
38 |
|
|
|
|
|
|