Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,93 @@
|
|
| 1 |
-
|
| 2 |
-
import tensorflow as tf
|
| 3 |
-
from tensorflow.keras.models import load_model
|
| 4 |
-
from tensorflow.keras.preprocessing import image
|
| 5 |
-
import numpy as np
|
| 6 |
-
from google.colab import files
|
| 7 |
import cv2
|
| 8 |
-
|
|
|
|
| 9 |
import pickle
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
img_array = img_array[np.newaxis, :, :, :]
|
| 33 |
-
return img_array
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
print("Predicted class index:", predicted_class_index)
|
| 57 |
-
print("Predicted class:", predicted_class)
|
|
|
|
| 1 |
+
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tensorflow.keras.models import load_model
|
| 5 |
import pickle
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Load the model and label encoder (cached for performance)
|
| 10 |
+
@st.cache_resource
|
| 11 |
+
def load_resources():
|
| 12 |
+
try:
|
| 13 |
+
model = load_model('captains_cv2_model.keras', compile=False)
|
| 14 |
+
with open('label_encoder.pkl', 'rb') as file:
|
| 15 |
+
label_encoder = pickle.load(file)
|
| 16 |
+
return model, label_encoder
|
| 17 |
+
except Exception as e:
|
| 18 |
+
st.error(f"Error loading resources: {str(e)}")
|
| 19 |
+
return None, None
|
| 20 |
+
|
| 21 |
+
# Preprocess the image (adjusted to match your Colab code)
|
| 22 |
+
def preprocess_image(image_path, target_size=(64, 64)):
|
| 23 |
+
try:
|
| 24 |
+
img = cv2.imread(image_path)
|
| 25 |
+
if img is None:
|
| 26 |
+
raise ValueError("Failed to load image")
|
| 27 |
+
img = cv2.resize(img, target_size) # Resize to 64x64
|
| 28 |
+
img_array = np.asarray(img) # Convert to numpy array, shape: (64, 64, 3)
|
| 29 |
+
img_array = img_array[np.newaxis, :, :, :] # Add batch dimension, shape: (1, 64, 64, 3)
|
| 30 |
+
return img_array
|
| 31 |
+
except Exception as e:
|
| 32 |
+
st.error(f"Error preprocessing image: {str(e)}")
|
| 33 |
+
return None
|
| 34 |
|
| 35 |
+
# Main Streamlit app
|
| 36 |
+
def main():
|
| 37 |
+
# Load model and label encoder
|
| 38 |
+
model, label_encoder = load_resources()
|
| 39 |
+
if model is None or label_encoder is None:
|
| 40 |
+
st.error("Failed to load model or label encoder. Please check the files and try again.")
|
| 41 |
+
return
|
| 42 |
|
| 43 |
+
# UI setup
|
| 44 |
+
st.title("Image Classification App")
|
| 45 |
+
st.write("Upload an image to get a prediction using the pre-trained CNN model.")
|
| 46 |
|
| 47 |
+
# File uploader
|
| 48 |
+
uploaded_file = st.file_uploader("Choose an image to classify...", type=["jpg", "jpeg", "png"])
|
| 49 |
|
| 50 |
+
if uploaded_file is not None:
|
| 51 |
+
# Display the uploaded image
|
| 52 |
+
image = Image.open(uploaded_file)
|
| 53 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 54 |
|
| 55 |
+
# Save the uploaded file temporarily with its original extension
|
| 56 |
+
file_extension = os.path.splitext(uploaded_file.name)[1].lower()
|
| 57 |
+
temp_filename = f"temp_image{file_extension}"
|
| 58 |
+
with open(temp_filename, "wb") as f:
|
| 59 |
+
f.write(uploaded_file.getvalue())
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
try:
|
| 62 |
+
# Preprocess the image
|
| 63 |
+
processed_image = preprocess_image(temp_filename)
|
| 64 |
+
if processed_image is None:
|
| 65 |
+
raise ValueError("Image preprocessing failed")
|
| 66 |
|
| 67 |
+
# Display processed image shape for debugging
|
| 68 |
+
st.write(f"Processed image shape: {processed_image.shape}")
|
| 69 |
|
| 70 |
+
# Make prediction
|
| 71 |
+
prediction = model.predict(processed_image)
|
| 72 |
+
predicted_class_index = np.argmax(prediction, axis=1)[0]
|
| 73 |
+
predicted_class = label_encoder.inverse_transform([predicted_class_index])[0]
|
| 74 |
|
| 75 |
+
# Display results
|
| 76 |
+
st.subheader("Prediction Results")
|
| 77 |
+
st.write(f"**Predicted Class:** {predicted_class}")
|
| 78 |
+
st.write(f"**Predicted Class Index:** {predicted_class_index}")
|
| 79 |
+
|
| 80 |
+
# Display prediction probabilities
|
| 81 |
+
st.write("**Prediction Probabilities:**")
|
| 82 |
+
for class_name, prob in zip(label_encoder.classes_, prediction[0]):
|
| 83 |
+
st.write(f"{class_name}: {prob:.4f}")
|
| 84 |
|
| 85 |
+
except Exception as e:
|
| 86 |
+
st.error(f"Error during prediction: {str(e)}")
|
| 87 |
|
| 88 |
+
# Clean up temporary file
|
| 89 |
+
if os.path.exists(temp_filename):
|
| 90 |
+
os.remove(temp_filename)
|
| 91 |
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
main()
|
|
|
|
|
|