mjolnir1122 commited on
Commit
027c43f
·
verified ·
1 Parent(s): 066ab9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -44
app.py CHANGED
@@ -1,54 +1,42 @@
1
  import streamlit as st
2
- import pickle
3
- import cv2
4
  import numpy as np
5
- from skimage.transform import resize
6
- from PIL import Image
7
-
8
- import pickle
9
-
10
- try:
11
- with open("knn_model.pkl", "rb") as f:
12
- knn_model = pickle.load(f)
13
- print("Model loaded successfully!")
14
- except Exception as e:
15
- print(f"Error loading model: {e}")
16
-
17
- # Load the trained KNN model
18
- with open("knn_model.pkl", "rb") as f:
19
- knn_model = pickle.load(f)
20
-
21
- # Load class labels (fixing the filename)
22
- with open("class_labels.pkl", "rb") as f:
23
- class_labels = pickle.load(f) # Ensure it is a list or dictionary
24
-
25
- # Function to preprocess image
26
- def preprocess_image(image):
27
- """Resizes and flattens the image for model prediction."""
28
- image = np.array(image) # Convert PIL image to numpy array
29
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Convert RGB to BGR
30
- image_resized = resize(image, (224, 224)) # Resize to 224x224
31
- image_flattened = image_resized.flatten().reshape(1, -1) # Flatten
32
- return image_flattened
33
-
34
- # Prediction Function
35
  def predict_animal(image):
36
- """Predicts the class of the uploaded image."""
37
- processed_image = preprocess_image(image)
38
  prediction = knn_model.predict(processed_image)[0] # Get predicted index
39
- return class_labels[prediction] # Get class name from labels
 
 
 
40
 
41
- # Streamlit UI
42
- st.title("🐾 Animal Image Classifier")
43
- st.write("Upload an image of an animal and click **Identify** to predict the species.")
44
 
45
- # Upload Image
46
- uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
47
 
48
- if uploaded_image is not None:
49
- image = Image.open(uploaded_image)
50
- st.image(image, caption="Uploaded Image", use_column_width=True)
51
 
52
  if st.button("Identify"):
53
  prediction = predict_animal(image)
54
- st.success(f"**Predicted Animal:** {prediction} 🐾")
 
1
  import streamlit as st
 
 
2
  import numpy as np
3
+ import joblib
4
+ import cv2
5
+ from tensorflow.keras.applications import VGG16
6
+ from tensorflow.keras.applications.vgg16 import preprocess_input
7
+
8
+ # Load model and class labels
9
+ knn_model = joblib.load("knn_model.pkl")
10
+ class_labels = joblib.load("class_labels.pkl")
11
+
12
+ # Load VGG16 feature extractor (same as used in training)
13
+ feature_extractor = VGG16(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
14
+
15
+ def extract_features(image):
16
+ """Extracts features using the same model used during training (VGG16 in this case)."""
17
+ image = cv2.resize(image, (224, 224)) # Resize image to 224x224
18
+ image = np.expand_dims(image, axis=0) # Add batch dimension
19
+ image = preprocess_input(image) # Apply VGG16 preprocessing
20
+ features = feature_extractor.predict(image)
21
+ return features.flatten().reshape(1, -1) # Reshape to match model input
22
+
 
 
 
 
 
 
 
 
 
 
23
  def predict_animal(image):
24
+ """Preprocess the image and make a prediction."""
25
+ processed_image = extract_features(image) # Extract features
26
  prediction = knn_model.predict(processed_image)[0] # Get predicted index
27
+ predicted_label = list(class_labels.keys())[list(class_labels.values()).index(prediction)]
28
+ return predicted_label
29
+
30
+ st.title("Animal Image Classifier")
31
 
32
+ uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "png", "jpeg"])
 
 
33
 
34
+ if uploaded_file is not None:
35
+ image = np.array(cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), cv2.IMREAD_COLOR))
36
 
37
+ # Display the image
38
+ st.image(image, caption="Uploaded Image", use_container_width=True)
 
39
 
40
  if st.button("Identify"):
41
  prediction = predict_animal(image)
42
+ st.success(f"Predicted Animal: **{prediction}**")