Update app.py
Browse files
app.py
CHANGED
@@ -1,399 +1,436 @@
|
|
1 |
-
import os
|
2 |
-
import sys
|
3 |
-
import shutil
|
4 |
-
import importlib.util
|
5 |
-
from io import BytesIO
|
6 |
-
from ultralytics import YOLO
|
7 |
-
from PIL import Image
|
8 |
-
|
9 |
-
import torch
|
10 |
-
# βββ FORCE CPU ONLY βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
11 |
-
torch.Tensor.cuda = lambda self, *args, **kwargs: self
|
12 |
-
torch.nn.Module.cuda = lambda self, *args, **kwargs: self
|
13 |
-
torch.cuda.synchronize = lambda *args, **kwargs: None
|
14 |
-
torch.cuda.is_available= lambda : False
|
15 |
-
torch.cuda.device_count= lambda : 0
|
16 |
-
_orig_to = torch.Tensor.to
|
17 |
-
def _to_cpu(self, *args, **kwargs):
|
18 |
-
new_args = []
|
19 |
-
for a in args:
|
20 |
-
if isinstance(a, str) and a.lower().startswith("cuda"):
|
21 |
-
new_args.append("cpu")
|
22 |
-
elif isinstance(a, torch.device) and a.type=="cuda":
|
23 |
-
new_args.append(torch.device("cpu"))
|
24 |
-
else:
|
25 |
-
new_args.append(a)
|
26 |
-
if "device" in kwargs:
|
27 |
-
dev = kwargs["device"]
|
28 |
-
if (isinstance(dev, str) and dev.lower().startswith("cuda")) or \
|
29 |
-
(isinstance(dev, torch.device) and dev.type=="cuda"):
|
30 |
-
kwargs["device"] = torch.device("cpu")
|
31 |
-
return _orig_to(self, *new_args, **kwargs)
|
32 |
-
torch.Tensor.to = _to_cpu
|
33 |
-
|
34 |
-
from torch.utils.data import DataLoader as _DL
|
35 |
-
def _dl0(ds, *a, **kw):
|
36 |
-
kw['num_workers'] = 0
|
37 |
-
return _DL(ds, *a, **kw)
|
38 |
-
import torch.utils.data as _du
|
39 |
-
_du.DataLoader = _dl0
|
40 |
-
|
41 |
-
import cv2
|
42 |
-
import numpy as np
|
43 |
-
import streamlit as st
|
44 |
-
from argparse import Namespace
|
45 |
-
|
46 |
-
# βββ DYNAMIC IMPORT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
47 |
-
REPO = os.path.dirname(os.path.abspath(__file__))
|
48 |
-
sys.path.append(REPO)
|
49 |
-
models_dir = os.path.join(REPO, "models")
|
50 |
-
os.makedirs(models_dir, exist_ok=True)
|
51 |
-
open(os.path.join(models_dir, "__init__.py"), "a").close()
|
52 |
-
|
53 |
-
def load_mod(name, path):
|
54 |
-
spec = importlib.util.spec_from_file_location(name, path)
|
55 |
-
m = importlib.util.module_from_spec(spec)
|
56 |
-
spec.loader.exec_module(m)
|
57 |
-
sys.modules[name] = m
|
58 |
-
return m
|
59 |
-
|
60 |
-
dataset_mod = load_mod("dataset", os.path.join(REPO, "dataset.py"))
|
61 |
-
decoder_mod = load_mod("decoder", os.path.join(REPO, "decoder.py"))
|
62 |
-
draw_mod = load_mod("draw_points", os.path.join(REPO, "draw_points.py"))
|
63 |
-
test_mod = load_mod("test", os.path.join(REPO, "test.py"))
|
64 |
-
load_mod("models.dec_net", os.path.join(models_dir, "dec_net.py"))
|
65 |
-
load_mod("models.model_parts", os.path.join(models_dir, "model_parts.py"))
|
66 |
-
load_mod("models.resnet", os.path.join(models_dir, "resnet.py"))
|
67 |
-
load_mod("models.spinal_net", os.path.join(models_dir, "spinal_net.py"))
|
68 |
-
|
69 |
-
BaseDataset = dataset_mod.BaseDataset
|
70 |
-
Network = test_mod.Network
|
71 |
-
|
72 |
-
# βββ STREAMLIT UI
|
73 |
-
st.set_page_config(layout="wide", page_title="Vertebral Compression Fracture")
|
74 |
-
|
75 |
-
st.markdown(
|
76 |
-
"""
|
77 |
-
<div style='border: 2px solid #0080FF; border-radius: 5px; padding: 10px'>
|
78 |
-
<h1 style='text-align: center; color: #0080FF'>
|
79 |
-
𦴠Vertebral Compression Fracture Detection πΌοΈ
|
80 |
-
</h1>
|
81 |
-
</div>
|
82 |
-
""", unsafe_allow_html=True)
|
83 |
-
st.markdown("")
|
84 |
-
st.markdown("")
|
85 |
-
st.markdown("")
|
86 |
-
col1, col2, col3, col4 = st.columns(4)
|
87 |
-
|
88 |
-
with col4:
|
89 |
-
feature = st.selectbox(
|
90 |
-
"π Select Feature",
|
91 |
-
["How to use", "AP - Detection", "AP - Cobb angle" , "LA - Image Segmetation", "Contract"],
|
92 |
-
index=0, # default to "AP"
|
93 |
-
help="Choose which view to display"
|
94 |
-
)
|
95 |
-
|
96 |
-
if feature == "How to use":
|
97 |
-
st.markdown("## π How to use this app")
|
98 |
-
|
99 |
-
col1, col2, col3 = st.columns(3)
|
100 |
-
|
101 |
-
with col1:
|
102 |
-
st.markdown(
|
103 |
-
"""
|
104 |
-
<div style='border:2px solid #00BFFF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
105 |
-
<h2>Step 1οΈβ£</h2>
|
106 |
-
<p>Go to <b>AP - Detection</b> or <b>LA - Image Segmentation</b></p>
|
107 |
-
<p>Select a sample image or upload your own image file.</p>
|
108 |
-
<p style='color:#008000;'><b>β
Tip:</b> Best with X-ray images with clear vertebra visibility.</p>
|
109 |
-
</div>
|
110 |
-
""",
|
111 |
-
unsafe_allow_html=True
|
112 |
-
)
|
113 |
-
|
114 |
-
with col2:
|
115 |
-
st.markdown(
|
116 |
-
"""
|
117 |
-
<div style='border:2px solid #00BFFF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
118 |
-
<h2>Step 2οΈβ£</h2>
|
119 |
-
<p>Press the <b>Enter</b> button.</p>
|
120 |
-
<p>The system will process your image automatically.</p>
|
121 |
-
<p style='color:#FFA500;'><b>β³ Note:</b> Processing time depends on image size.</p>
|
122 |
-
</div>
|
123 |
-
""",
|
124 |
-
unsafe_allow_html=True
|
125 |
-
)
|
126 |
-
|
127 |
-
with col3:
|
128 |
-
st.markdown(
|
129 |
-
"""
|
130 |
-
<div style='border:2px solid #00BFFF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
131 |
-
<h2>Step 3οΈβ£</h2>
|
132 |
-
<p>See the prediction results:</p>
|
133 |
-
<p style= text-align:left > 1. Bounding boxes & landmarks (AP)</p>
|
134 |
-
<p style= text-align:left > 2. Segmentation masks (LA)</p>
|
135 |
-
</div>
|
136 |
-
""",
|
137 |
-
unsafe_allow_html=True
|
138 |
-
)
|
139 |
-
|
140 |
-
st.markdown(" ")
|
141 |
-
st.info("ΰΈͺΰΈ²ΰΈ‘ΰΈ²ΰΈ£ΰΈΰΉΰΈ₯ΰΈ·ΰΈΰΈΰΈΰΈ΅ΰΉΰΈΰΈΰΈ£ΰΉΰΉΰΈΰΉΰΈΰΉΰΈ²ΰΈ Select Feature ΰΉΰΈΰΈ’ΰΉΰΈΰΉΰΈ₯ΰΉΰΈ°ΰΈΰΈ΅ΰΉΰΈΰΈΰΈ£ΰΉΰΈΰΈ°ΰΈ‘ΰΈ΅ΰΈΰΈ±ΰΈ§ΰΈΰΈ’ΰΉΰΈ²ΰΈΰΈΰΈ³ΰΈΰΈ±ΰΈΰΉΰΈ«ΰΉΰΈ§ΰΉΰΈ²ΰΉΰΈΰΉΰΈΰΈ’ΰΈ±ΰΈΰΉΰΈ")
|
142 |
-
|
143 |
-
# store original dimensions
|
144 |
-
elif feature == "AP - Detection":
|
145 |
-
uploaded = st.file_uploader("", type=["jpg", "jpeg", "png"])
|
146 |
-
orig_w = orig_h = None
|
147 |
-
img0 = None
|
148 |
-
run = st.button("Enter", use_container_width=True)
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
if uploaded:
|
173 |
-
buf = uploaded.getvalue()
|
174 |
-
arr = np.frombuffer(buf, np.uint8)
|
175 |
-
img0 = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
176 |
-
orig_h, orig_w = img0.shape[:2]
|
177 |
-
st.image(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB),
|
178 |
-
|
179 |
-
|
180 |
-
elif sample_img is not None:
|
181 |
-
img_path = os.path.join(REPO, sample_img)
|
182 |
-
img0 = cv2.imread(img_path)
|
183 |
-
if img0 is not None:
|
184 |
-
orig_h, orig_w = img0.shape[:2]
|
185 |
-
st.image(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB),
|
186 |
-
caption=f"Sample Image: {sample_img}",
|
187 |
-
use_container_width=True)
|
188 |
-
else:
|
189 |
-
st.error(f"Cannot find {sample_img} in directory!")
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
with
|
194 |
-
st.subheader("
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
)
|
211 |
-
|
212 |
-
os.
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
name = os.path.splitext(
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
net =
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
for (x1, y1), (x2, y2), (x3, y3), (x4, y4) in zip(
|
257 |
-
zip(tlx, tly), zip(trx, try_),
|
258 |
-
zip(blx, bly), zip(brx, bry)):
|
259 |
-
tm = np.array([(x1 + x2) / 2, (y1 + y2) / 2])
|
260 |
-
bm = np.array([(x3 + x4) / 2, (y3 + y4) / 2])
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
if
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
st.image(
|
356 |
-
|
357 |
-
elif
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
)
|
397 |
-
|
398 |
-
|
399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import shutil
|
4 |
+
import importlib.util
|
5 |
+
from io import BytesIO
|
6 |
+
from ultralytics import YOLO
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
import torch
|
10 |
+
# βββ FORCE CPU ONLY βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
11 |
+
torch.Tensor.cuda = lambda self, *args, **kwargs: self
|
12 |
+
torch.nn.Module.cuda = lambda self, *args, **kwargs: self
|
13 |
+
torch.cuda.synchronize = lambda *args, **kwargs: None
|
14 |
+
torch.cuda.is_available= lambda : False
|
15 |
+
torch.cuda.device_count= lambda : 0
|
16 |
+
_orig_to = torch.Tensor.to
|
17 |
+
def _to_cpu(self, *args, **kwargs):
|
18 |
+
new_args = []
|
19 |
+
for a in args:
|
20 |
+
if isinstance(a, str) and a.lower().startswith("cuda"):
|
21 |
+
new_args.append("cpu")
|
22 |
+
elif isinstance(a, torch.device) and a.type=="cuda":
|
23 |
+
new_args.append(torch.device("cpu"))
|
24 |
+
else:
|
25 |
+
new_args.append(a)
|
26 |
+
if "device" in kwargs:
|
27 |
+
dev = kwargs["device"]
|
28 |
+
if (isinstance(dev, str) and dev.lower().startswith("cuda")) or \
|
29 |
+
(isinstance(dev, torch.device) and dev.type=="cuda"):
|
30 |
+
kwargs["device"] = torch.device("cpu")
|
31 |
+
return _orig_to(self, *new_args, **kwargs)
|
32 |
+
torch.Tensor.to = _to_cpu
|
33 |
+
|
34 |
+
from torch.utils.data import DataLoader as _DL
|
35 |
+
def _dl0(ds, *a, **kw):
|
36 |
+
kw['num_workers'] = 0
|
37 |
+
return _DL(ds, *a, **kw)
|
38 |
+
import torch.utils.data as _du
|
39 |
+
_du.DataLoader = _dl0
|
40 |
+
|
41 |
+
import cv2
|
42 |
+
import numpy as np
|
43 |
+
import streamlit as st
|
44 |
+
from argparse import Namespace
|
45 |
+
|
46 |
+
# βββ DYNAMIC IMPORT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
47 |
+
REPO = os.path.dirname(os.path.abspath(__file__))
|
48 |
+
sys.path.append(REPO)
|
49 |
+
models_dir = os.path.join(REPO, "models")
|
50 |
+
os.makedirs(models_dir, exist_ok=True)
|
51 |
+
open(os.path.join(models_dir, "__init__.py"), "a").close()
|
52 |
+
|
53 |
+
def load_mod(name, path):
|
54 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
55 |
+
m = importlib.util.module_from_spec(spec)
|
56 |
+
spec.loader.exec_module(m)
|
57 |
+
sys.modules[name] = m
|
58 |
+
return m
|
59 |
+
|
60 |
+
dataset_mod = load_mod("dataset", os.path.join(REPO, "dataset.py"))
|
61 |
+
decoder_mod = load_mod("decoder", os.path.join(REPO, "decoder.py"))
|
62 |
+
draw_mod = load_mod("draw_points", os.path.join(REPO, "draw_points.py"))
|
63 |
+
test_mod = load_mod("test", os.path.join(REPO, "test.py"))
|
64 |
+
load_mod("models.dec_net", os.path.join(models_dir, "dec_net.py"))
|
65 |
+
load_mod("models.model_parts", os.path.join(models_dir, "model_parts.py"))
|
66 |
+
load_mod("models.resnet", os.path.join(models_dir, "resnet.py"))
|
67 |
+
load_mod("models.spinal_net", os.path.join(models_dir, "spinal_net.py"))
|
68 |
+
|
69 |
+
BaseDataset = dataset_mod.BaseDataset
|
70 |
+
Network = test_mod.Network
|
71 |
+
|
72 |
+
# βββ STREAMLIT UI βββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββ
|
73 |
+
st.set_page_config(layout="wide", page_title="Vertebral Compression Fracture")
|
74 |
+
|
75 |
+
st.markdown(
|
76 |
+
"""
|
77 |
+
<div style='border: 2px solid #0080FF; border-radius: 5px; padding: 10px'>
|
78 |
+
<h1 style='text-align: center; color: #0080FF'>
|
79 |
+
𦴠Vertebral Compression Fracture Detection πΌοΈ
|
80 |
+
</h1>
|
81 |
+
</div>
|
82 |
+
""", unsafe_allow_html=True)
|
83 |
+
st.markdown("")
|
84 |
+
st.markdown("")
|
85 |
+
st.markdown("")
|
86 |
+
col1, col2, col3, col4 = st.columns(4)
|
87 |
+
|
88 |
+
with col4:
|
89 |
+
feature = st.selectbox(
|
90 |
+
"π Select Feature",
|
91 |
+
["How to use", "AP - Detection", "AP - Cobb angle" , "LA - Image Segmetation", "Contract"],
|
92 |
+
index=0, # default to "AP"
|
93 |
+
help="Choose which view to display"
|
94 |
+
)
|
95 |
+
|
96 |
+
if feature == "How to use":
|
97 |
+
st.markdown("## π How to use this app")
|
98 |
+
|
99 |
+
col1, col2, col3 = st.columns(3)
|
100 |
+
|
101 |
+
with col1:
|
102 |
+
st.markdown(
|
103 |
+
"""
|
104 |
+
<div style='border:2px solid #00BFFF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
105 |
+
<h2>Step 1οΈβ£</h2>
|
106 |
+
<p>Go to <b>AP - Detection</b> or <b>LA - Image Segmentation</b></p>
|
107 |
+
<p>Select a sample image or upload your own image file.</p>
|
108 |
+
<p style='color:#008000;'><b>β
Tip:</b> Best with X-ray images with clear vertebra visibility.</p>
|
109 |
+
</div>
|
110 |
+
""",
|
111 |
+
unsafe_allow_html=True
|
112 |
+
)
|
113 |
+
|
114 |
+
with col2:
|
115 |
+
st.markdown(
|
116 |
+
"""
|
117 |
+
<div style='border:2px solid #00BFFF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
118 |
+
<h2>Step 2οΈβ£</h2>
|
119 |
+
<p>Press the <b>Enter</b> button.</p>
|
120 |
+
<p>The system will process your image automatically.</p>
|
121 |
+
<p style='color:#FFA500;'><b>β³ Note:</b> Processing time depends on image size.</p>
|
122 |
+
</div>
|
123 |
+
""",
|
124 |
+
unsafe_allow_html=True
|
125 |
+
)
|
126 |
+
|
127 |
+
with col3:
|
128 |
+
st.markdown(
|
129 |
+
"""
|
130 |
+
<div style='border:2px solid #00BFFF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
131 |
+
<h2>Step 3οΈβ£</h2>
|
132 |
+
<p>See the prediction results:</p>
|
133 |
+
<p style= text-align:left > 1. Bounding boxes & landmarks (AP)</p>
|
134 |
+
<p style= text-align:left > 2. Segmentation masks (LA)</p>
|
135 |
+
</div>
|
136 |
+
""",
|
137 |
+
unsafe_allow_html=True
|
138 |
+
)
|
139 |
+
|
140 |
+
st.markdown(" ")
|
141 |
+
st.info("ΰΈͺΰΈ²ΰΈ‘ΰΈ²ΰΈ£ΰΈΰΉΰΈ₯ΰΈ·ΰΈΰΈΰΈΰΈ΅ΰΉΰΈΰΈΰΈ£ΰΉΰΉΰΈΰΉΰΈΰΉΰΈ²ΰΈ Select Feature ΰΉΰΈΰΈ’ΰΉΰΈΰΉΰΈ₯ΰΉΰΈ°ΰΈΰΈ΅ΰΉΰΈΰΈΰΈ£ΰΉΰΈΰΈ°ΰΈ‘ΰΈ΅ΰΈΰΈ±ΰΈ§ΰΈΰΈ’ΰΉΰΈ²ΰΈΰΈΰΈ³ΰΈΰΈ±ΰΈΰΉΰΈ«ΰΉΰΈ§ΰΉΰΈ²ΰΉΰΈΰΉΰΈΰΈ’ΰΈ±ΰΈΰΉΰΈ")
|
142 |
+
|
143 |
+
# store original dimensions
|
144 |
+
elif feature == "AP - Detection":
|
145 |
+
uploaded = st.file_uploader("", type=["jpg", "jpeg", "png"])
|
146 |
+
orig_w = orig_h = None
|
147 |
+
img0 = None
|
148 |
+
run = st.button("Enter", use_container_width=True)
|
149 |
+
|
150 |
+
# βββ Maintain selected sample in session state βββββββββ
|
151 |
+
if "sample_img" not in st.session_state:
|
152 |
+
st.session_state.sample_img = None
|
153 |
+
|
154 |
+
# βββ SAMPLE BUTTONS βββββββββββββββββββββββββββββββββββββ
|
155 |
+
with col1:
|
156 |
+
if st.button(" 1οΈβ£ Example", use_container_width=True):
|
157 |
+
st.session_state.sample_img = "image_1.jpg"
|
158 |
+
with col2:
|
159 |
+
if st.button(" 2οΈβ£ Example", use_container_width=True):
|
160 |
+
st.session_state.sample_img = "image_2.jpg"
|
161 |
+
with col3:
|
162 |
+
if st.button(" 3οΈβ£ Example", use_container_width=True):
|
163 |
+
st.session_state.sample_img = "image_3.jpg"
|
164 |
+
|
165 |
+
# βββ UI FOR UPLOAD + DISPLAY βββββββββββββββββββββββββββ
|
166 |
+
col4, col5, col6 = st.columns(3)
|
167 |
+
with col4:
|
168 |
+
st.subheader("1οΈβ£ Upload & Run")
|
169 |
+
|
170 |
+
sample_img = st.session_state.sample_img
|
171 |
+
|
172 |
+
if uploaded:
|
173 |
+
buf = uploaded.getvalue()
|
174 |
+
arr = np.frombuffer(buf, np.uint8)
|
175 |
+
img0 = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
176 |
+
orig_h, orig_w = img0.shape[:2]
|
177 |
+
st.image(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB),
|
178 |
+
caption="Uploaded Image", use_container_width=True)
|
179 |
+
|
180 |
+
elif sample_img is not None:
|
181 |
+
img_path = os.path.join(REPO, sample_img)
|
182 |
+
img0 = cv2.imread(img_path)
|
183 |
+
if img0 is not None:
|
184 |
+
orig_h, orig_w = img0.shape[:2]
|
185 |
+
st.image(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB),
|
186 |
+
caption=f"Sample Image: {sample_img}",
|
187 |
+
use_container_width=True)
|
188 |
+
else:
|
189 |
+
st.error(f"Cannot find {sample_img} in directory!")
|
190 |
+
|
191 |
+
with col5:
|
192 |
+
st.subheader("2οΈβ£ Predictions")
|
193 |
+
with col6:
|
194 |
+
st.subheader("3οΈβ£ Heatmap")
|
195 |
+
|
196 |
+
# βββ ARGS & CHECKPOINT βββββββββββββββββββββββββββββββββ
|
197 |
+
args = Namespace(
|
198 |
+
resume="model_30.pth",
|
199 |
+
data_dir=os.path.join(REPO, "dataPath"),
|
200 |
+
dataset="spinal",
|
201 |
+
phase="test",
|
202 |
+
input_h=1024,
|
203 |
+
input_w=512,
|
204 |
+
down_ratio=4,
|
205 |
+
num_classes=1,
|
206 |
+
K=17,
|
207 |
+
conf_thresh=0.2,
|
208 |
+
)
|
209 |
+
weights_dir = os.path.join(REPO, "weights_spinal")
|
210 |
+
os.makedirs(weights_dir, exist_ok=True)
|
211 |
+
src_ckpt = os.path.join(REPO, "model_backup", args.resume)
|
212 |
+
dst_ckpt = os.path.join(weights_dir, args.resume)
|
213 |
+
if os.path.isfile(src_ckpt) and not os.path.isfile(dst_ckpt):
|
214 |
+
shutil.copy(src_ckpt, dst_ckpt)
|
215 |
+
|
216 |
+
# βββ MAIN LOGIC ββββββββββββββββββββββββββββββββββββββββ
|
217 |
+
if img0 is not None and run and orig_w and orig_h:
|
218 |
+
# determine name for saving
|
219 |
+
if uploaded:
|
220 |
+
name = os.path.splitext(uploaded.name)[0] + ".jpg"
|
221 |
+
else:
|
222 |
+
name = os.path.splitext(sample_img)[0] + ".jpg"
|
223 |
+
|
224 |
+
testd = os.path.join(args.data_dir, "data", "test")
|
225 |
+
os.makedirs(testd, exist_ok=True)
|
226 |
+
cv2.imwrite(os.path.join(testd, name), img0)
|
227 |
+
|
228 |
+
# patch BaseDataset to only load our one image
|
229 |
+
orig_init = BaseDataset.__init__
|
230 |
+
def patched_init(self, data_dir, phase, input_h=None, input_w=None, down_ratio=4):
|
231 |
+
orig_init(self, data_dir, phase, input_h, input_w, down_ratio)
|
232 |
+
if phase == "test":
|
233 |
+
self.img_ids = [name]
|
234 |
+
BaseDataset.__init__ = patched_init
|
235 |
+
|
236 |
+
with st.spinner("Running modelβ¦"):
|
237 |
+
net = Network(args)
|
238 |
+
net.test(args, save=True)
|
239 |
+
|
240 |
+
out_dir = os.path.join(REPO, f"results_{args.dataset}")
|
241 |
+
pred_file = [f for f in os.listdir(out_dir)
|
242 |
+
if f.startswith(name) and f.endswith("_pred.jpg")][0]
|
243 |
+
txtf = os.path.join(out_dir, f"{name}.txt")
|
244 |
+
imgf = os.path.join(out_dir, pred_file)
|
245 |
+
|
246 |
+
# βββ Annotated Predictions βββββββββββββββββββββββββ
|
247 |
+
base = cv2.imread(imgf)
|
248 |
+
txt = np.loadtxt(txtf)
|
249 |
+
tlx, tly = txt[:, 2].astype(int), txt[:, 3].astype(int)
|
250 |
+
trx, try_ = txt[:, 4].astype(int), txt[:, 5].astype(int)
|
251 |
+
blx, bly = txt[:, 6].astype(int), txt[:, 7].astype(int)
|
252 |
+
brx, bry = txt[:, 8].astype(int), txt[:, 9].astype(int)
|
253 |
+
|
254 |
+
# compute midβpoints and heights
|
255 |
+
cts, heights = [], []
|
256 |
+
for (x1, y1), (x2, y2), (x3, y3), (x4, y4) in zip(
|
257 |
+
zip(tlx, tly), zip(trx, try_),
|
258 |
+
zip(blx, bly), zip(brx, bry)):
|
259 |
+
tm = np.array([(x1 + x2) / 2, (y1 + y2) / 2])
|
260 |
+
bm = np.array([(x3 + x4) / 2, (y3 + y4) / 2])
|
261 |
+
cts.append((int(tm[0]), int((tm[1]+bm[1])//2)))
|
262 |
+
heights.append(int(bm[1] - tm[1]))
|
263 |
+
|
264 |
+
# draw lines on 'ann'
|
265 |
+
ann = base.copy()
|
266 |
+
for (cx, cy), h in zip(cts, heights):
|
267 |
+
# topβbottom line
|
268 |
+
cv2.line(ann, (cx, cy - h//2), (cx, cy + h//2), (0, 255, 255), 2)
|
269 |
+
|
270 |
+
# neighborβbased compression percentages
|
271 |
+
for idx, ((cx, cy), height) in enumerate(zip(cts, heights)):
|
272 |
+
# reference = average of neighbors
|
273 |
+
if 0 < idx < len(heights) - 1:
|
274 |
+
ref_h = (heights[idx - 1] + heights[idx + 1]) / 2
|
275 |
+
else:
|
276 |
+
ref_h = np.median(heights)
|
277 |
+
|
278 |
+
percent = abs((ref_h - height) / ref_h * 100)
|
279 |
+
|
280 |
+
# color thresholds
|
281 |
+
if percent > 40:
|
282 |
+
color = (0, 0, 255)
|
283 |
+
elif percent > 20:
|
284 |
+
color = (0, 165, 255)
|
285 |
+
else:
|
286 |
+
color = (0, 255, 0)
|
287 |
+
|
288 |
+
# label
|
289 |
+
text_pos = (cx + 5, cy)
|
290 |
+
cv2.putText(ann, f"{percent:.0f}%", text_pos,
|
291 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2, cv2.LINE_AA)
|
292 |
+
print(f"ΰΈΰΈ£ΰΈ°ΰΈΰΈΉΰΈΰΈΰΈ±ΰΈ§ΰΈΰΈ΅ΰΉ {idx+1}: Compression = {percent:.1f}%")
|
293 |
+
|
294 |
+
# show annotated image
|
295 |
+
ann_resized = cv2.resize(ann, (orig_w, orig_h),
|
296 |
+
interpolation=cv2.INTER_LINEAR)
|
297 |
+
with col5:
|
298 |
+
st.image(cv2.cvtColor(ann_resized, cv2.COLOR_BGR2RGB),
|
299 |
+
use_container_width=True)
|
300 |
+
|
301 |
+
# βββ Heatmap ββββββββββββββββββββββββββββββββββββββββββ
|
302 |
+
H, W = base.shape[:2]
|
303 |
+
heat = np.zeros((H, W), np.float32)
|
304 |
+
for cx, cy in cts:
|
305 |
+
blob = np.zeros_like(heat)
|
306 |
+
blob[cy, cx] = 1.0
|
307 |
+
heat += cv2.GaussianBlur(blob, (0, 0), sigmaX=8, sigmaY=8)
|
308 |
+
heat /= heat.max() + 1e-8
|
309 |
+
hm8 = (heat * 255).astype(np.uint8)
|
310 |
+
hm_c = cv2.applyColorMap(hm8, cv2.COLORMAP_JET)
|
311 |
+
raw = cv2.imread(imgf, cv2.IMREAD_GRAYSCALE)
|
312 |
+
raw_b = cv2.cvtColor(raw, cv2.COLOR_GRAY2BGR)
|
313 |
+
overlay = cv2.addWeighted(raw_b, 0.6, hm_c, 0.4, 0)
|
314 |
+
overlay_resized = cv2.resize(overlay, (orig_w, orig_h),
|
315 |
+
interpolation=cv2.INTER_LINEAR)
|
316 |
+
with col6:
|
317 |
+
st.image(cv2.cvtColor(overlay_resized, cv2.COLOR_BGR2RGB),
|
318 |
+
use_container_width=True)
|
319 |
+
|
320 |
+
|
321 |
+
elif feature == "LA - Image Segmetation":
|
322 |
+
uploaded = st.file_uploader("", type=["jpg", "jpeg", "png"])
|
323 |
+
img0 = None
|
324 |
+
|
325 |
+
# βββ Maintain selected sample in session state βββββββββ
|
326 |
+
if "sample_img_la" not in st.session_state:
|
327 |
+
st.session_state.sample_img_la = None
|
328 |
+
|
329 |
+
# βββ SAMPLE BUTTONS βββββββββββββββββββββββββββββββββββββ
|
330 |
+
with col1:
|
331 |
+
if st.button(" 1οΈβ£ Example ", use_container_width=True):
|
332 |
+
st.session_state.sample_img_la = "image_1_la.jpg"
|
333 |
+
with col2:
|
334 |
+
if st.button(" 2οΈβ£ Example ", use_container_width=True):
|
335 |
+
st.session_state.sample_img_la = "image_2_la.jpg"
|
336 |
+
with col3:
|
337 |
+
if st.button(" 3οΈβ£ Example ", use_container_width=True):
|
338 |
+
st.session_state.sample_img_la = "image_3_la.jpg"
|
339 |
+
|
340 |
+
# βββ UI FOR UPLOAD + DISPLAY βββββββββββββββββββββββββββ
|
341 |
+
run_la = st.button("Enter", use_container_width=True)
|
342 |
+
|
343 |
+
# βββ CONFIDENCE BANNER βββββββββββββββββββββββββββββββββ
|
344 |
+
|
345 |
+
col7, col8 = st.columns(2)
|
346 |
+
|
347 |
+
with col7:
|
348 |
+
st.subheader("πΌοΈ Original Image")
|
349 |
+
|
350 |
+
sample_img_la = st.session_state.sample_img_la
|
351 |
+
|
352 |
+
if uploaded:
|
353 |
+
buf = uploaded.getvalue()
|
354 |
+
img0 = Image.open(BytesIO(buf)).convert("RGB")
|
355 |
+
st.image(img0, caption="Uploaded Image", use_container_width=True)
|
356 |
+
|
357 |
+
elif sample_img_la is not None:
|
358 |
+
img_path = os.path.join(REPO, sample_img_la)
|
359 |
+
if os.path.isfile(img_path):
|
360 |
+
img0 = Image.open(img_path).convert("RGB")
|
361 |
+
st.image(img0, caption=f"Sample Image: {sample_img_la}", use_container_width=True)
|
362 |
+
else:
|
363 |
+
st.error(f"Cannot find {sample_img_la} in directory!")
|
364 |
+
|
365 |
+
with col8:
|
366 |
+
st.subheader("π Predicted Image")
|
367 |
+
|
368 |
+
# βββ PREDICTION ββββββββββββββββββββββββββββββββββββ
|
369 |
+
if img0 is not None and run_la:
|
370 |
+
img_np = np.array(img0)
|
371 |
+
model = YOLO('./best.pt') # path to your weights
|
372 |
+
with st.spinner("Running YOLO modelβ¦"):
|
373 |
+
results = model(img_np, imgsz=640)
|
374 |
+
|
375 |
+
# βββ Compute & Redisplay Confidence ββββββββββββ
|
376 |
+
# get all box confidences (if no boxes, empty array)
|
377 |
+
confidences = (results[0].boxes.conf.cpu().numpy() if hasattr(results[0].boxes, "conf") else np.array([]))
|
378 |
+
avg_conf = confidences.mean() if confidences.size > 0 else 0.0
|
379 |
+
|
380 |
+
# overwrite the placeholder banner with the real value
|
381 |
+
|
382 |
+
|
383 |
+
# βββ Show Segmentation ββββββββββββββββββββββββ
|
384 |
+
pred_img = results[0].plot(boxes=False, probs=False)
|
385 |
+
st.image(pred_img, caption="Prediction Result", use_container_width=True)
|
386 |
+
st.markdown(
|
387 |
+
f"<div style='text-align:center; font-size:20px; color:#4CAF50;'>"
|
388 |
+
f"β¨ **Confidence Level:** {avg_conf*100:.1f}% β¨"
|
389 |
+
"</div>",
|
390 |
+
unsafe_allow_html=True
|
391 |
+
)
|
392 |
+
|
393 |
+
|
394 |
+
elif feature == "Contract":
|
395 |
+
with col1:
|
396 |
+
st.image("dev_1.jpg", caption=None, use_container_width=True)
|
397 |
+
st.markdown(
|
398 |
+
"""
|
399 |
+
<div style='border:2px solid #0080FF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
400 |
+
<h3>Thitsanapat Uma</h3>
|
401 |
+
<a href='https://www.facebook.com/thitsanapat.uma' target='_blank'>
|
402 |
+
π Facebook Profile
|
403 |
+
</a>
|
404 |
+
</div>
|
405 |
+
""",
|
406 |
+
unsafe_allow_html=True
|
407 |
+
)
|
408 |
+
with col2:
|
409 |
+
st.image("dev_2.jpg", caption=None, use_container_width=True)
|
410 |
+
st.markdown(
|
411 |
+
"""
|
412 |
+
<div style='border:2px solid #0080FF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
413 |
+
<h3>Santipab Tongchan</h3>
|
414 |
+
<a href='https://www.facebook.com/santipab.tongchan.2025' target='_blank'>
|
415 |
+
π Facebook Profile
|
416 |
+
</a>
|
417 |
+
</div>
|
418 |
+
""",
|
419 |
+
unsafe_allow_html=True
|
420 |
+
)
|
421 |
+
with col3:
|
422 |
+
st.image("dev_3.jpg", caption=None, use_container_width=True)
|
423 |
+
st.markdown(
|
424 |
+
"""
|
425 |
+
<div style='border:2px solid #0080FF; border-radius:10px; padding:15px; text-align:center; background-color:#F0F8FF'>
|
426 |
+
<h3>Suphanat Kamphapan</h3>
|
427 |
+
<a href='https://www.facebook.com/suphanat.kamphapan' target='_blank'>
|
428 |
+
π Facebook Profile
|
429 |
+
</a>
|
430 |
+
</div>
|
431 |
+
""",
|
432 |
+
unsafe_allow_html=True
|
433 |
+
)
|
434 |
+
|
435 |
+
|
436 |
+
|