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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import cv2
|
3 |
+
from PIL import Image, ImageEnhance
|
4 |
+
import numpy as np
|
5 |
+
import time
|
6 |
+
from skimage.metrics import structural_similarity as ssim
|
7 |
+
import base64
|
8 |
+
from datetime import datetime
|
9 |
+
import torch
|
10 |
+
|
11 |
+
# Load pre-trained YOLOv5 model for object detection
|
12 |
+
@st.cache_resource
|
13 |
+
def load_yolo_model():
|
14 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
|
15 |
+
return model
|
16 |
+
|
17 |
+
def load_css():
|
18 |
+
st.markdown("""
|
19 |
+
<style>
|
20 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
21 |
+
|
22 |
+
.stApp {
|
23 |
+
background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
|
24 |
+
font-family: 'Inter', sans-serif;
|
25 |
+
color: #e0e0e0;
|
26 |
+
}
|
27 |
+
|
28 |
+
.main {
|
29 |
+
padding: 2rem;
|
30 |
+
max-width: 1200px;
|
31 |
+
margin: 0 auto;
|
32 |
+
}
|
33 |
+
|
34 |
+
.stButton>button {
|
35 |
+
background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
|
36 |
+
color: white;
|
37 |
+
padding: 0.75rem 1.5rem;
|
38 |
+
border-radius: 10px;
|
39 |
+
border: none;
|
40 |
+
box-shadow: 0 4px 6px rgba(0,0,0,0.2);
|
41 |
+
transition: all 0.3s ease;
|
42 |
+
font-weight: 500;
|
43 |
+
letter-spacing: 0.5px;
|
44 |
+
}
|
45 |
+
|
46 |
+
.stButton>button:hover {
|
47 |
+
transform: translateY(-2px);
|
48 |
+
box-shadow: 0 6px 12px rgba(0,0,0,0.3);
|
49 |
+
}
|
50 |
+
|
51 |
+
.upload-container {
|
52 |
+
background: #2d2d2d;
|
53 |
+
border-radius: 15px;
|
54 |
+
padding: 1.5rem;
|
55 |
+
box-shadow: 0 4px 6px rgba(0,0,0,0.2);
|
56 |
+
transition: all 0.3s ease;
|
57 |
+
margin-bottom: 1rem;
|
58 |
+
}
|
59 |
+
|
60 |
+
.upload-container:hover {
|
61 |
+
box-shadow: 0 6px 12px rgba(0,0,0,0.3);
|
62 |
+
}
|
63 |
+
|
64 |
+
.upload-box {
|
65 |
+
border: 2px dashed #404040;
|
66 |
+
border-radius: 12px;
|
67 |
+
padding: 2rem;
|
68 |
+
text-align: center;
|
69 |
+
background: #333333;
|
70 |
+
transition: all 0.3s ease;
|
71 |
+
cursor: pointer;
|
72 |
+
}
|
73 |
+
|
74 |
+
.upload-box:hover {
|
75 |
+
border-color: #2196F3;
|
76 |
+
background: #383838;
|
77 |
+
}
|
78 |
+
|
79 |
+
.results-container {
|
80 |
+
background: #2d2d2d;
|
81 |
+
border-radius: 15px;
|
82 |
+
padding: 2rem;
|
83 |
+
box-shadow: 0 4px 6px rgba(0,0,0,0.2);
|
84 |
+
color: #e0e0e0;
|
85 |
+
}
|
86 |
+
|
87 |
+
.metric-card {
|
88 |
+
background: #333333;
|
89 |
+
border-radius: 10px;
|
90 |
+
padding: 1rem;
|
91 |
+
margin: 0.5rem 0;
|
92 |
+
border-left: 4px solid #2196F3;
|
93 |
+
color: #e0e0e0;
|
94 |
+
}
|
95 |
+
|
96 |
+
.stProgress > div > div {
|
97 |
+
background: linear-gradient(90deg, #2196F3, #64B5F6);
|
98 |
+
border-radius: 10px;
|
99 |
+
}
|
100 |
+
|
101 |
+
@keyframes pulse {
|
102 |
+
0% { opacity: 1; }
|
103 |
+
50% { opacity: 0.5; }
|
104 |
+
100% { opacity: 1; }
|
105 |
+
}
|
106 |
+
|
107 |
+
.loading {
|
108 |
+
animation: pulse 1.5s infinite;
|
109 |
+
}
|
110 |
+
</style>
|
111 |
+
""", unsafe_allow_html=True)
|
112 |
+
|
113 |
+
def enhance_image(image):
|
114 |
+
"""
|
115 |
+
Basic image enhancement with default settings
|
116 |
+
"""
|
117 |
+
enhancer = ImageEnhance.Brightness(image)
|
118 |
+
image = enhancer.enhance(1.0)
|
119 |
+
enhancer = ImageEnhance.Contrast(image)
|
120 |
+
image = enhancer.enhance(1.0)
|
121 |
+
enhancer = ImageEnhance.Sharpness(image)
|
122 |
+
image = enhancer.enhance(1.0)
|
123 |
+
return image
|
124 |
+
|
125 |
+
def compare_images(img1, img2, progress_bar):
|
126 |
+
"""
|
127 |
+
Compare two images and return the processed image, similarity score, and difference percentage
|
128 |
+
"""
|
129 |
+
try:
|
130 |
+
progress_bar.progress(0)
|
131 |
+
|
132 |
+
# Convert images to numpy arrays and ensure same size
|
133 |
+
img1 = np.array(img1.resize(img2.size))
|
134 |
+
img2 = np.array(img2)
|
135 |
+
progress_bar.progress(20)
|
136 |
+
|
137 |
+
# Normalize images
|
138 |
+
img1 = cv2.normalize(img1, None, 0, 255, cv2.NORM_MINMAX)
|
139 |
+
img2 = cv2.normalize(img2, None, 0, 255, cv2.NORM_MINMAX)
|
140 |
+
|
141 |
+
# Convert to grayscale
|
142 |
+
gray1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
|
143 |
+
gray2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)
|
144 |
+
progress_bar.progress(40)
|
145 |
+
|
146 |
+
# Calculate SSIM
|
147 |
+
score, diff = ssim(gray1, gray2, full=True)
|
148 |
+
progress_bar.progress(60)
|
149 |
+
|
150 |
+
# Generate heatmap
|
151 |
+
diff = (diff * 255).astype(np.uint8)
|
152 |
+
heatmap = cv2.applyColorMap(diff, cv2.COLORMAP_JET)
|
153 |
+
progress_bar.progress(80)
|
154 |
+
|
155 |
+
# Highlight differences in red color
|
156 |
+
diff_mask = cv2.absdiff(gray1, gray2)
|
157 |
+
diff_mask = cv2.cvtColor(diff_mask, cv2.COLOR_GRAY2RGB)
|
158 |
+
diff_mask[np.where((diff_mask == [255, 255, 255]).all(axis=2))] = [0, 0, 255] # Red color for differences
|
159 |
+
|
160 |
+
# Combine original image with difference mask
|
161 |
+
result_img = cv2.addWeighted(img1, 0.7, diff_mask, 0.3, 0)
|
162 |
+
|
163 |
+
# Calculate pixel-wise differences
|
164 |
+
diff_percentage = (np.count_nonzero(diff_mask[:, :, 2] > 0) / (diff_mask.shape[0] * diff_mask.shape[1])) * 100
|
165 |
+
|
166 |
+
# Ensure that the difference percentage is consistent with the similarity score
|
167 |
+
diff_percentage = 100 - (score * 100)
|
168 |
+
|
169 |
+
progress_bar.progress(100)
|
170 |
+
|
171 |
+
return result_img, score, diff_percentage, heatmap
|
172 |
+
|
173 |
+
except Exception as e:
|
174 |
+
st.error(f"Error comparing images: {str(e)}")
|
175 |
+
return None, 0, 0, None
|
176 |
+
|
177 |
+
def detect_objects(image, model):
|
178 |
+
"""
|
179 |
+
Perform object detection on the image using YOLOv5
|
180 |
+
"""
|
181 |
+
try:
|
182 |
+
results = model(image)
|
183 |
+
results_df = results.pandas().xyxy[0]
|
184 |
+
return results_df
|
185 |
+
except Exception as e:
|
186 |
+
st.error(f"Error in object detection: {str(e)}")
|
187 |
+
return None
|
188 |
+
|
189 |
+
def draw_object_boxes(image, objects_df):
|
190 |
+
"""
|
191 |
+
Draw bounding boxes on the image for detected objects
|
192 |
+
"""
|
193 |
+
for _, row in objects_df.iterrows():
|
194 |
+
xmin, ymin, xmax, ymax, confidence, class_name = int(row['xmin']), int(row['ymin']), int(row['xmax']), int(row['ymax']), row['confidence'], row['name']
|
195 |
+
# Draw bounding box
|
196 |
+
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
|
197 |
+
# Add label
|
198 |
+
cv2.putText(image, f"{class_name} {confidence:.2f}", (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
|
199 |
+
return image
|
200 |
+
|
201 |
+
def main():
|
202 |
+
load_css()
|
203 |
+
|
204 |
+
# Initialize session state for results
|
205 |
+
if "results" not in st.session_state:
|
206 |
+
st.session_state.results = None
|
207 |
+
|
208 |
+
# Load YOLOv5 model
|
209 |
+
yolo_model = load_yolo_model()
|
210 |
+
|
211 |
+
# App header
|
212 |
+
st.markdown("""
|
213 |
+
<div style='text-align: center; margin-bottom: 2rem; background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); padding: 2rem; border-radius: 15px; color: white;'>
|
214 |
+
<h1 style='margin: 0;'>π Image Comparison Tool</h1>
|
215 |
+
<p style='margin: 1rem 0 0 0; opacity: 0.9;'>Compare images, highlight differences, and detect objects</p>
|
216 |
+
</div>
|
217 |
+
""", unsafe_allow_html=True)
|
218 |
+
|
219 |
+
# Main content for image upload and display
|
220 |
+
st.markdown("<div class='upload-container'>", unsafe_allow_html=True)
|
221 |
+
st.markdown("### π Upload Images")
|
222 |
+
|
223 |
+
col1, col2 = st.columns(2)
|
224 |
+
|
225 |
+
# Reference Image Upload
|
226 |
+
with col1:
|
227 |
+
reference_image = st.file_uploader(
|
228 |
+
"Drop or select reference image",
|
229 |
+
type=["jpg", "jpeg", "png"],
|
230 |
+
key="reference"
|
231 |
+
)
|
232 |
+
if reference_image:
|
233 |
+
img1 = Image.open(reference_image)
|
234 |
+
img1 = enhance_image(img1)
|
235 |
+
st.image(img1, caption="Reference Image", use_column_width=True)
|
236 |
+
# Clear previous results when a new image is uploaded
|
237 |
+
st.session_state.results = None
|
238 |
+
|
239 |
+
# New Image Upload
|
240 |
+
with col2:
|
241 |
+
new_image = st.file_uploader(
|
242 |
+
"Drop or select comparison image",
|
243 |
+
type=["jpg", "jpeg", "png"],
|
244 |
+
key="new"
|
245 |
+
)
|
246 |
+
if new_image:
|
247 |
+
img2 = Image.open(new_image)
|
248 |
+
img2 = enhance_image(img2)
|
249 |
+
st.image(img2, caption="Comparison Image", use_column_width=True)
|
250 |
+
# Clear previous results when a new image is uploaded
|
251 |
+
st.session_state.results = None
|
252 |
+
|
253 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
254 |
+
|
255 |
+
# Sidebar for results and download
|
256 |
+
st.sidebar.markdown("### π― Analysis Results")
|
257 |
+
|
258 |
+
if reference_image and new_image:
|
259 |
+
compare_button = st.sidebar.button("π Analyze Images", use_container_width=True)
|
260 |
+
|
261 |
+
if compare_button or st.session_state.results:
|
262 |
+
if not st.session_state.results:
|
263 |
+
with st.spinner("Processing images..."):
|
264 |
+
progress_bar = st.sidebar.progress(0)
|
265 |
+
|
266 |
+
start_time = time.time()
|
267 |
+
result_img, score, diff_percentage, heatmap = compare_images(img1, img2, progress_bar)
|
268 |
+
processing_time = time.time() - start_time
|
269 |
+
|
270 |
+
# Perform object detection
|
271 |
+
objects_df = detect_objects(result_img, yolo_model)
|
272 |
+
|
273 |
+
# Draw bounding boxes on the analyzed image
|
274 |
+
if objects_df is not None:
|
275 |
+
result_img = draw_object_boxes(result_img, objects_df)
|
276 |
+
|
277 |
+
# Store results in session state
|
278 |
+
st.session_state.results = {
|
279 |
+
"result_img": result_img,
|
280 |
+
"heatmap": heatmap,
|
281 |
+
"score": score,
|
282 |
+
"diff_percentage": diff_percentage,
|
283 |
+
"processing_time": processing_time,
|
284 |
+
"objects_df": objects_df
|
285 |
+
}
|
286 |
+
|
287 |
+
# Display analyzed image (processed image with differences highlighted) in sidebar
|
288 |
+
st.sidebar.image(st.session_state.results["result_img"], caption="Analyzed Image (Differences Highlighted)", use_column_width=True)
|
289 |
+
|
290 |
+
# Display heatmap in sidebar
|
291 |
+
st.sidebar.image(st.session_state.results["heatmap"], caption="Heatmap", use_column_width=True)
|
292 |
+
|
293 |
+
# Display metrics in sidebar
|
294 |
+
st.sidebar.markdown("### π Metrics")
|
295 |
+
st.sidebar.markdown(f"""
|
296 |
+
<div class='metric-card'>
|
297 |
+
<h4>Similarity Score</h4>
|
298 |
+
<h2 style='color: #2196F3'>{st.session_state.results["score"]:.2%}</h2>
|
299 |
+
</div>
|
300 |
+
""", unsafe_allow_html=True)
|
301 |
+
|
302 |
+
st.sidebar.markdown(f"""
|
303 |
+
<div class='metric-card'>
|
304 |
+
<h4>Difference Detected</h4>
|
305 |
+
<h2 style='color: #2196F3'>{st.session_state.results["diff_percentage"]:.2f}%</h2>
|
306 |
+
</div>
|
307 |
+
""", unsafe_allow_html=True)
|
308 |
+
|
309 |
+
st.sidebar.markdown(f"""
|
310 |
+
<div class='metric-card'>
|
311 |
+
<h4>Processing Time</h4>
|
312 |
+
<h2 style='color: #2196F3'>{st.session_state.results["processing_time"]:.2f}s</h2>
|
313 |
+
</div>
|
314 |
+
""", unsafe_allow_html=True)
|
315 |
+
|
316 |
+
# Display detected objects
|
317 |
+
if st.session_state.results["objects_df"] is not None:
|
318 |
+
st.sidebar.markdown("### π Detected Objects")
|
319 |
+
st.sidebar.dataframe(st.session_state.results["objects_df"])
|
320 |
+
|
321 |
+
# Download analyzed image
|
322 |
+
st.sidebar.markdown("### π₯ Download Analyzed Image")
|
323 |
+
st.sidebar.download_button(
|
324 |
+
"Download Analyzed Image",
|
325 |
+
data=cv2.imencode('.png', cv2.cvtColor(st.session_state.results["result_img"], cv2.COLOR_RGB2BGR))[1].tobytes(),
|
326 |
+
file_name=f"analyzed_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png",
|
327 |
+
mime="image/png"
|
328 |
+
)
|
329 |
+
|
330 |
+
# Footer
|
331 |
+
st.markdown("""
|
332 |
+
<div style='text-align: center; margin-top: 2rem; padding: 1rem; background: #2d2d2d; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.2);'>
|
333 |
+
<p style='color: #888; margin: 0;'>Built with β€οΈ using Streamlit | Last updated: December 2024</p>
|
334 |
+
<p style='color: #888; font-size: 0.9em; margin: 0.5rem 0 0 0;'>Image Comparison Tool v1.0</p>
|
335 |
+
</div>
|
336 |
+
""", unsafe_allow_html=True)
|
337 |
+
|
338 |
+
if __name__ == "__main__":
|
339 |
+
main()
|