Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import joblib
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image
|
5 |
+
from tensorflow.keras.preprocessing.image import load_img, img_to_array
|
6 |
+
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
|
7 |
+
|
8 |
+
# Load the trained KNN model and class names
|
9 |
+
knn = joblib.load('knn_model.pkl') # Replace with the correct path
|
10 |
+
class_names = joblib.load('class_names.pkl') # Replace with the correct path
|
11 |
+
|
12 |
+
# Function to extract features using ResNet50
|
13 |
+
def extract_features(img):
|
14 |
+
# Load the pre-trained ResNet50 model (without the top layer)
|
15 |
+
model = ResNet50(weights='imagenet', include_top=False, pooling='avg')
|
16 |
+
# Extract features from the image
|
17 |
+
features = model.predict(img)
|
18 |
+
return features
|
19 |
+
|
20 |
+
# Streamlit app title
|
21 |
+
st.title("Animal Classification App")
|
22 |
+
|
23 |
+
# Description of the app
|
24 |
+
st.write("This app classifies animals based on uploaded images using a trained KNN model.")
|
25 |
+
|
26 |
+
# Upload image
|
27 |
+
uploaded_file = st.file_uploader("Upload an image of an animal", type=["jpg", "jpeg", "png"])
|
28 |
+
|
29 |
+
# Process the uploaded image and predict
|
30 |
+
if uploaded_file is not None:
|
31 |
+
# Open the image and display it
|
32 |
+
image = Image.open(uploaded_file)
|
33 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
34 |
+
|
35 |
+
# Resize and preprocess the image
|
36 |
+
image = image.resize((224, 224)) # Resize the image to 224x224
|
37 |
+
img_array = img_to_array(image) # Convert image to array
|
38 |
+
img_array = np.expand_dims(img_array, axis=0) # Expand dimensions to match ResNet50 input
|
39 |
+
img_array = preprocess_input(img_array) # Preprocess for ResNet50
|
40 |
+
|
41 |
+
# Extract features using ResNet50
|
42 |
+
features = extract_features(img_array)
|
43 |
+
|
44 |
+
# Predict using the trained KNN model
|
45 |
+
prediction = knn.predict(features)
|
46 |
+
|
47 |
+
# Display the predicted class
|
48 |
+
st.write(f"Prediction: {class_names[prediction[0]]}")
|