trohith89 commited on
Commit
5a5b14c
·
verified ·
1 Parent(s): 1b7540f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -43
app.py CHANGED
@@ -1,57 +1,93 @@
1
- # Import necessary libraries
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
- from google.colab.patches import cv2_imshow
 
9
  import pickle
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Upload your model and label encoder files to Colab
12
- print("Please upload your captains_cv2_model.keras file")
13
- uploaded_model = files.upload()
14
- model_filename = list(uploaded_model.keys())[0]
 
 
 
15
 
16
- print("Please upload your label_encoder.pkl file")
17
- uploaded_encoder = files.upload()
18
- encoder_filename = list(uploaded_encoder.keys())[0]
19
 
20
- # Load the pretrained model
21
- model = load_model(model_filename)
22
 
23
- # Load the label encoder
24
- with open(encoder_filename, 'rb') as file:
25
- label_encoder = pickle.load(file)
 
26
 
27
- # Function to preprocess the image (adjust based on your model's requirements)
28
- def preprocess_image(img_path, target_size=(64, 64)): # Adjust target_size as per your model
29
-
30
- img = cv2.imread(img_path)
31
- img_array = np.asarray(img)
32
- img_array = img_array[np.newaxis, :, :, :]
33
- return img_array
34
 
35
- # Upload an image to predict
36
- print("Please upload an image to classify")
37
- uploaded_image = files.upload()
 
 
38
 
39
- # Get the uploaded image filename
40
- img_filename = list(uploaded_image.keys())[0]
41
 
42
- # Preprocess the image
43
- processed_image = preprocess_image(img_filename)
 
 
44
 
45
- # Make prediction
46
- prediction = model.predict(processed_image)
 
 
 
 
 
 
 
47
 
48
- # Get the predicted class index
49
- predicted_class_index = np.argmax(prediction, axis=1)[0]
50
 
51
- # Decode the prediction using the label encoder
52
- predicted_class = label_encoder.inverse_transform([predicted_class_index])[0]
 
53
 
54
- # Output the prediction
55
- print("Prediction probabilities:", prediction)
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()