Spaces:
Runtime error

Tdanyim commited on
Commit
f65cfcd
·
verified ·
1 Parent(s): 405c308

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +169 -8
src/streamlit_app.py CHANGED
@@ -1,8 +1,11 @@
1
  from pathlib import Path
 
2
 
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
  import streamlit as st
 
 
6
  from PIL import Image
7
  from scipy.io import loadmat
8
 
@@ -12,9 +15,13 @@ st.set_page_config(page_title="kIQT MRI Reconstruction", layout="wide")
12
  LF_DIR = Path("data/LF")
13
  HF_DIR = Path("data/HF")
14
  MASK_DIR = Path("mask/prs")
 
15
  TARGET_SIZE = (256, 256)
16
 
17
 
 
 
 
18
  def prepare_image_for_display(arr: np.ndarray) -> np.ndarray:
19
  """
20
  Convert an array into a 2D image for display.
@@ -41,7 +48,7 @@ def prepare_image_for_display(arr: np.ndarray) -> np.ndarray:
41
  def resize_image_np(img_np: np.ndarray, target_size=(256, 256)) -> np.ndarray:
42
  """
43
  Resize a 2D NumPy image using PIL bicubic interpolation.
44
- PIL expects (width, height).
45
  """
46
  img_np = np.asarray(img_np, dtype=np.float32)
47
  pil_img = Image.fromarray(img_np)
@@ -50,26 +57,26 @@ def resize_image_np(img_np: np.ndarray, target_size=(256, 256)) -> np.ndarray:
50
 
51
 
52
  def fft2c(image: np.ndarray) -> np.ndarray:
53
- """Compute centered 2D FFT."""
54
  return np.fft.fftshift(
55
  np.fft.fft2(np.fft.ifftshift(image, axes=(-2, -1))),
56
- axes=(-2, -1)
57
  )
58
 
59
 
60
  def ifft2c(kspace: np.ndarray) -> np.ndarray:
61
- """Compute centered 2D IFFT and return magnitude image."""
62
  return np.abs(
63
  np.fft.ifftshift(
64
  np.fft.ifft2(np.fft.fftshift(kspace, axes=(-2, -1))),
65
- axes=(-2, -1)
66
  )
67
  )
68
 
69
 
70
  def load_mask(mask_path: Path) -> np.ndarray:
71
  """
72
- Load and preprocess undersampling mask from .mat file.
73
  Expects key: 'mask_matrix'
74
  """
75
  mask_data = loadmat(mask_path)
@@ -129,9 +136,117 @@ def show_array_stats(title: str, arr: np.ndarray):
129
  st.write(f"**Std:** {np.std(arr):.6f}")
130
 
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def main():
133
  st.title("kIQT: MRI Reconstruction Demo")
134
- st.write("Inspect paired LF/HF images, their k-space, and undersampled reconstruction.")
135
 
136
  if not LF_DIR.exists():
137
  st.error("Missing folder: `data/LF`")
@@ -145,6 +260,10 @@ def main():
145
  st.error("Missing folder: `mask/prs`")
146
  st.stop()
147
 
 
 
 
 
148
  paired_cases, lf_only, hf_only = collect_paired_cases(LF_DIR, HF_DIR)
149
 
150
  if lf_only:
@@ -165,13 +284,19 @@ def main():
165
  selected_mask = st.sidebar.selectbox(
166
  "Choose a mask",
167
  options=mask_files,
168
- format_func=lambda p: p.name
169
  )
170
 
171
  lf_path = paired_cases[selected_case]["lf"]
172
  hf_path = paired_cases[selected_case]["hf"]
173
 
174
  try:
 
 
 
 
 
 
175
  # Load images
176
  lf_img = np.load(lf_path, allow_pickle=False)
177
  hf_img = np.load(hf_path, allow_pickle=False)
@@ -203,9 +328,25 @@ def main():
203
  lf_recon_ud = ifft2c(lf_kspace_ud)
204
  hf_recon_ud = ifft2c(hf_kspace_ud)
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  st.subheader("Selected Inputs")
207
  st.write(f"**Case:** {selected_case}")
208
  st.write(f"**Mask:** {selected_mask.name}")
 
 
209
 
210
  info_col1, info_col2 = st.columns(2)
211
  with info_col1:
@@ -302,12 +443,32 @@ def main():
302
  plt.tight_layout()
303
  st.pyplot(fig3)
304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  st.markdown("### Processed Data Statistics")
306
  col_a, col_b = st.columns(2)
307
  with col_a:
308
  show_array_stats("LF Resized", lf_resized)
309
  show_array_stats("LF Reconstructed", lf_recon)
310
  show_array_stats("LF Undersampled Reconstruction", lf_recon_ud)
 
 
311
  with col_b:
312
  show_array_stats("HF Resized", hf_resized)
313
  show_array_stats("HF Reconstructed", hf_recon)
 
1
  from pathlib import Path
2
+ import time
3
 
4
  import matplotlib.pyplot as plt
5
  import numpy as np
6
  import streamlit as st
7
+ import torch
8
+ import torch.nn as nn
9
  from PIL import Image
10
  from scipy.io import loadmat
11
 
 
15
  LF_DIR = Path("data/LF")
16
  HF_DIR = Path("data/HF")
17
  MASK_DIR = Path("mask/prs")
18
+ MODEL_PATH = Path("weight/udksp30Unet_weight.pth")
19
  TARGET_SIZE = (256, 256)
20
 
21
 
22
+ # =========================
23
+ # Utility Functions
24
+ # =========================
25
  def prepare_image_for_display(arr: np.ndarray) -> np.ndarray:
26
  """
27
  Convert an array into a 2D image for display.
 
48
  def resize_image_np(img_np: np.ndarray, target_size=(256, 256)) -> np.ndarray:
49
  """
50
  Resize a 2D NumPy image using PIL bicubic interpolation.
51
+ PIL expects size as (width, height).
52
  """
53
  img_np = np.asarray(img_np, dtype=np.float32)
54
  pil_img = Image.fromarray(img_np)
 
57
 
58
 
59
  def fft2c(image: np.ndarray) -> np.ndarray:
60
+ """Centered 2D FFT."""
61
  return np.fft.fftshift(
62
  np.fft.fft2(np.fft.ifftshift(image, axes=(-2, -1))),
63
+ axes=(-2, -1),
64
  )
65
 
66
 
67
  def ifft2c(kspace: np.ndarray) -> np.ndarray:
68
+ """Centered 2D IFFT returning magnitude image."""
69
  return np.abs(
70
  np.fft.ifftshift(
71
  np.fft.ifft2(np.fft.fftshift(kspace, axes=(-2, -1))),
72
+ axes=(-2, -1),
73
  )
74
  )
75
 
76
 
77
  def load_mask(mask_path: Path) -> np.ndarray:
78
  """
79
+ Load undersampling mask from .mat file.
80
  Expects key: 'mask_matrix'
81
  """
82
  mask_data = loadmat(mask_path)
 
136
  st.write(f"**Std:** {np.std(arr):.6f}")
137
 
138
 
139
+ # =========================
140
+ # Model Definition
141
+ # =========================
142
+ class UNetBlock(nn.Module):
143
+ def __init__(self, in_channels, out_channels, kernel_size=3, padding=1):
144
+ super().__init__()
145
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding)
146
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, padding=padding)
147
+ self.relu = nn.ReLU(inplace=True)
148
+
149
+ def forward(self, x):
150
+ x = self.relu(self.conv1(x))
151
+ x = self.relu(self.conv2(x))
152
+ return x
153
+
154
+
155
+ class KSpaceUNet(nn.Module):
156
+ def __init__(self, input_channels=2, output_channels=2, num_filters=64):
157
+ super().__init__()
158
+
159
+ self.enc1 = UNetBlock(input_channels, num_filters)
160
+ self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
161
+
162
+ self.enc2 = UNetBlock(num_filters, num_filters * 2)
163
+ self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
164
+
165
+ self.enc3 = UNetBlock(num_filters * 2, num_filters * 4)
166
+ self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)
167
+
168
+ self.bottleneck = UNetBlock(num_filters * 4, num_filters * 8)
169
+
170
+ self.up3 = nn.ConvTranspose2d(num_filters * 8, num_filters * 4, kernel_size=2, stride=2)
171
+ self.dec3 = UNetBlock(num_filters * 8, num_filters * 4)
172
+
173
+ self.up2 = nn.ConvTranspose2d(num_filters * 4, num_filters * 2, kernel_size=2, stride=2)
174
+ self.dec2 = UNetBlock(num_filters * 4, num_filters * 2)
175
+
176
+ self.up1 = nn.ConvTranspose2d(num_filters * 2, num_filters, kernel_size=2, stride=2)
177
+ self.dec1 = UNetBlock(num_filters * 2, num_filters)
178
+
179
+ self.final_conv = nn.Conv2d(num_filters, output_channels, kernel_size=1)
180
+
181
+ def forward(self, x):
182
+ e1 = self.enc1(x)
183
+ p1 = self.pool1(e1)
184
+
185
+ e2 = self.enc2(p1)
186
+ p2 = self.pool2(e2)
187
+
188
+ e3 = self.enc3(p2)
189
+ p3 = self.pool3(e3)
190
+
191
+ b = self.bottleneck(p3)
192
+
193
+ u3 = self.up3(b)
194
+ d3 = self.dec3(torch.cat([u3, e3], dim=1))
195
+
196
+ u2 = self.up2(d3)
197
+ d2 = self.dec2(torch.cat([u2, e2], dim=1))
198
+
199
+ u1 = self.up1(d2)
200
+ d1 = self.dec1(torch.cat([u1, e1], dim=1))
201
+
202
+ return self.final_conv(d1)
203
+
204
+
205
+ def get_device():
206
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
207
+
208
+
209
+ @st.cache_resource
210
+ def load_model(model_path_str: str):
211
+ model_path = Path(model_path_str)
212
+ device = get_device()
213
+
214
+ model = KSpaceUNet().to(device)
215
+ checkpoint = torch.load(model_path, map_location=device)
216
+ model.load_state_dict(checkpoint)
217
+ model.eval()
218
+
219
+ return model, str(device)
220
+
221
+
222
+ def prepare_model_input_from_kspace(kspace: np.ndarray) -> torch.Tensor:
223
+ """
224
+ Convert complex k-space into model input tensor:
225
+ (H, W) complex -> (1, 2, H, W) float32
226
+ channels = [real, imag]
227
+ """
228
+ real = np.real(kspace).astype(np.float32)
229
+ imag = np.imag(kspace).astype(np.float32)
230
+ stacked = np.stack([real, imag], axis=0)
231
+ tensor = torch.from_numpy(stacked).unsqueeze(0)
232
+ return tensor
233
+
234
+
235
+ def model_output_to_complex(pred: np.ndarray) -> np.ndarray:
236
+ """
237
+ Convert model output from shape (2, H, W) to complex k-space.
238
+ """
239
+ real = pred[0]
240
+ imag = pred[1]
241
+ return real + 1j * imag
242
+
243
+
244
+ # =========================
245
+ # Main App
246
+ # =========================
247
  def main():
248
  st.title("kIQT: MRI Reconstruction Demo")
249
+ st.write("Inspect paired LF/HF images, undersampling, and GPU-ready model inference.")
250
 
251
  if not LF_DIR.exists():
252
  st.error("Missing folder: `data/LF`")
 
260
  st.error("Missing folder: `mask/prs`")
261
  st.stop()
262
 
263
+ if not MODEL_PATH.exists():
264
+ st.error("Missing model file: `models/unet_weights.pth`")
265
+ st.stop()
266
+
267
  paired_cases, lf_only, hf_only = collect_paired_cases(LF_DIR, HF_DIR)
268
 
269
  if lf_only:
 
284
  selected_mask = st.sidebar.selectbox(
285
  "Choose a mask",
286
  options=mask_files,
287
+ format_func=lambda p: p.name,
288
  )
289
 
290
  lf_path = paired_cases[selected_case]["lf"]
291
  hf_path = paired_cases[selected_case]["hf"]
292
 
293
  try:
294
+ model, device_str = load_model(str(MODEL_PATH))
295
+ device = torch.device(device_str)
296
+
297
+ st.sidebar.markdown("### Runtime")
298
+ st.sidebar.write(f"**Device:** {device_str}")
299
+
300
  # Load images
301
  lf_img = np.load(lf_path, allow_pickle=False)
302
  hf_img = np.load(hf_path, allow_pickle=False)
 
328
  lf_recon_ud = ifft2c(lf_kspace_ud)
329
  hf_recon_ud = ifft2c(hf_kspace_ud)
330
 
331
+ # Model inference on LF undersampled k-space
332
+ model_input = prepare_model_input_from_kspace(lf_kspace_ud).to(device)
333
+
334
+ start_time = time.perf_counter()
335
+ with torch.no_grad():
336
+ pred_tensor = model(model_input)
337
+ if device.type == "cuda":
338
+ torch.cuda.synchronize()
339
+ inference_time = time.perf_counter() - start_time
340
+
341
+ pred_np = pred_tensor.squeeze(0).detach().cpu().numpy() # (2, H, W)
342
+ pred_kspace_complex = model_output_to_complex(pred_np)
343
+ pred_image = ifft2c(pred_kspace_complex)
344
+
345
  st.subheader("Selected Inputs")
346
  st.write(f"**Case:** {selected_case}")
347
  st.write(f"**Mask:** {selected_mask.name}")
348
+ st.write(f"**Inference Device:** {device_str}")
349
+ st.write(f"**Inference Time:** {inference_time:.4f} seconds")
350
 
351
  info_col1, info_col2 = st.columns(2)
352
  with info_col1:
 
443
  plt.tight_layout()
444
  st.pyplot(fig3)
445
 
446
+ st.markdown("### Model Reconstruction")
447
+ fig4, axes4 = plt.subplots(1, 3, figsize=(15, 5))
448
+
449
+ axes4[0].imshow(lf_recon_ud, cmap="gray")
450
+ axes4[0].set_title("Undersampled Input")
451
+
452
+ axes4[1].imshow(pred_image, cmap="gray")
453
+ axes4[1].set_title("Model Output")
454
+
455
+ axes4[2].imshow(hf_resized, cmap="gray")
456
+ axes4[2].set_title("Ground Truth")
457
+
458
+ for ax in axes4:
459
+ ax.axis("off")
460
+
461
+ plt.tight_layout()
462
+ st.pyplot(fig4)
463
+
464
  st.markdown("### Processed Data Statistics")
465
  col_a, col_b = st.columns(2)
466
  with col_a:
467
  show_array_stats("LF Resized", lf_resized)
468
  show_array_stats("LF Reconstructed", lf_recon)
469
  show_array_stats("LF Undersampled Reconstruction", lf_recon_ud)
470
+ show_array_stats("Predicted Image", pred_image)
471
+
472
  with col_b:
473
  show_array_stats("HF Resized", hf_resized)
474
  show_array_stats("HF Reconstructed", hf_recon)