-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
172 lines (149 loc) · 5.77 KB
/
app.py
File metadata and controls
172 lines (149 loc) · 5.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import streamlit as st
import tensorflow as tf
from tensorflow import keras
import numpy as np
from PIL import Image
import cv2
import matplotlib.pyplot as plt
# Page configuration
st.set_page_config(
page_title="Microscopic Organism Classifier",
page_icon="🔬",
layout="wide"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 42px;
font-weight: bold;
color: #2E86AB;
text-align: center;
margin-bottom: 30px;
}
.sub-header {
font-size: 20px;
color: #666;
text-align: center;
margin-bottom: 40px;
}
.prediction-box {
background-color: #f0f8ff;
padding: 20px;
border-radius: 10px;
border-left: 5px solid #2E86AB;
margin: 20px 0;
}
</style>
""", unsafe_allow_html=True)
# Load model
@st.cache_resource
def load_model():
try:
model = keras.models.load_model('microscopic_organism_classifier.h5')
return model
except:
st.warning("Model file not found. Please train the model first.")
return None
# Class names (update based on your dataset)
CLASS_NAMES = ['Amoeba', 'Diatom', 'Euglena', 'Paramecium', 'Volvox']
def preprocess_image(image, target_size=(128, 128)):
"""Preprocess uploaded image"""
img = image.resize(target_size)
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
return img_array
def predict_organism(model, image):
"""Make prediction on image"""
processed_img = preprocess_image(image)
predictions = model.predict(processed_img)[0]
predicted_class_idx = np.argmax(predictions)
predicted_class = CLASS_NAMES[predicted_class_idx]
confidence = predictions[predicted_class_idx] * 100
return predicted_class, confidence, predictions
# Main UI
st.markdown('<p class="main-header">🔬 Microscopic Organism Classifier</p>', unsafe_allow_html=True)
st.markdown('<p class="sub-header">Upload microscopic images for instant AI-powered identification</p>', unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.header("📋 About")
st.info("""
This application uses deep learning (CNN) to classify microscopic organisms from images.
**Supported Organisms:**
- Amoeba
- Diatom
- Euglena
- Paramecium
- Volvox
**How to use:**
1. Upload an image
2. Get instant classification
3. View confidence scores
""")
st.header("⚙️ Model Info")
st.metric("Model Type", "CNN")
st.metric("Input Size", "128x128")
st.metric("Classes", len(CLASS_NAMES))
# Main content
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("📤 Upload Image")
uploaded_file = st.file_uploader(
"Choose a microscopic organism image",
type=['png', 'jpg', 'jpeg'],
help="Upload a clear microscopic image for best results"
)
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image', use_container_width=True)
# Classify button
if st.button('🔍 Classify Organism', type='primary', use_container_width=True):
model = load_model()
if model is not None:
with st.spinner('Analyzing image...'):
predicted_class, confidence, all_predictions = predict_organism(model, image)
with col2:
st.subheader("📊 Results")
# Prediction box
st.markdown(f"""
<div class="prediction-box">
<h2 style="color: #2E86AB; margin: 0;">Predicted: {predicted_class}</h2>
<h3 style="color: #666; margin-top: 10px;">Confidence: {confidence:.2f}%</h3>
</div>
""", unsafe_allow_html=True)
# Probability chart
st.subheader("Probability Distribution")
fig, ax = plt.subplots(figsize=(10, 6))
colors = ['#2E86AB' if i == np.argmax(all_predictions) else '#A7C6D9'
for i in range(len(CLASS_NAMES))]
ax.barh(CLASS_NAMES, all_predictions, color=colors)
ax.set_xlabel('Probability', fontsize=12)
ax.set_xlim([0, 1])
ax.grid(axis='x', alpha=0.3)
plt.tight_layout()
st.pyplot(fig)
# Detailed probabilities
st.subheader("Detailed Probabilities")
for i, class_name in enumerate(CLASS_NAMES):
prob = all_predictions[i] * 100
st.progress(all_predictions[i])
st.text(f"{class_name}: {prob:.2f}%")
# Interpretation
if confidence > 90:
st.success("✅ High confidence prediction!")
elif confidence > 70:
st.info("ℹ️ Moderate confidence. Consider image quality.")
else:
st.warning("⚠️ Low confidence. Please upload a clearer image.")
# Sample images section
st.markdown("---")
st.subheader("📸 Sample Test Images")
st.info("Don't have an image? Download sample microscopic organism images from these sources: [Kaggle Plankton Dataset](https://www.kaggle.com) or Google Images")
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666; padding: 20px;">
<p>Developed with ❤️ using TensorFlow & Streamlit</p>
<p>For production deployment, contact me for full implementation with 20+ organism classes</p>
</div>
""", unsafe_allow_html=True)