MingGatsby commited on
Commit
2046f76
1 Parent(s): 1b8a13f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -147
app.py CHANGED
@@ -105,7 +105,7 @@ WINDOW_WIDTH_MAX = 3000
105
  # Evaluation Transforms
106
  eval_transforms = Compose(
107
  [
108
- LoadImage(image_only=True),
109
  AsChannelFirst(),
110
  ScaleIntensityRangePercentiles(lower=20, upper=80, b_min=0.0, b_max=1.0, clip=False, relative=True),
111
  Resize(spatial_size=SPATIAL_SIZE)
@@ -115,7 +115,7 @@ eval_transforms = Compose(
115
  # CAM Transforms
116
  cam_transforms = Compose(
117
  [
118
- LoadImage(image_only=True),
119
  AsChannelFirst(),
120
  Resize(spatial_size=SPATIAL_SIZE)
121
  ]
@@ -124,7 +124,7 @@ cam_transforms = Compose(
124
  # Original Transforms
125
  original_transforms = Compose(
126
  [
127
- LoadImage(image_only=True),
128
  AsChannelFirst()
129
  ]
130
  )
@@ -138,15 +138,15 @@ def image_to_bytes(image):
138
  # if os.path.exists("tempDir"):
139
  # shutil.rmtree(os.path.join("tempDir"))
140
 
141
- def create_dir(dirname: str):
142
- if not os.path.exists(dirname):
143
- os.makedirs(dirname, exist_ok=True)
144
 
145
- create_dir("CT_tempDir")
146
- create_dir("MRI_tempDir")
147
 
148
- # Get the current working directory
149
- current_directory = os.getcwd()
150
 
151
  set_determinism(seed=SEED)
152
  torch.manual_seed(SEED)
@@ -184,140 +184,155 @@ CT_WINDOW_WIDTH = st.sidebar.number_input("CT Window Width", min_value=WINDOW_WI
184
 
185
  uploaded_mri_file = st.file_uploader("Upload a candidate MRI DICOM", type=["dcm"])
186
  if uploaded_mri_file is not None:
187
- # Save the uploaded file to a temporary location
188
- mri_temp_path = os.path.join("MRI_tempDir", uploaded_mri_file.name)
189
- with open(mri_temp_path, "wb") as f:
190
- f.write(uploaded_mri_file.getbuffer())
191
-
192
- full_mri_temp_path = current_directory +"\\"+ mri_temp_path
193
-
194
- # Apply evaluation transforms to the DICOM image for model prediction
195
- image_tensor = eval_transforms(full_mri_temp_path).unsqueeze(0).to(device)
196
-
197
- # Predict
198
- with torch.no_grad():
199
- outputs = mri_model(image_tensor).sigmoid().to("cpu").numpy()
200
- prob = outputs[0][0]
201
- CLOTS_CLASSIFICATION = False
202
- if(prob >= MRI_INFERENCE_THRESHOLD):
203
- CLOTS_CLASSIFICATION=True
204
-
205
- st.header("MRI Classification")
206
- st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")
207
- st.subheader(f"Confidence : {prob * 100:.1f}%")
208
-
209
- # Load the original DICOM image for download
210
- download_image_tensor = original_transforms(full_mri_temp_path).unsqueeze(0).to(device)
211
- download_image = download_image_tensor.squeeze()
212
-
213
- # Transform the download image and apply windowing
214
- transformed_download_image = DICOM_Utils.transform_image_for_display(download_image)
215
- windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)
216
-
217
- # Streamlit button to trigger image download
218
- image_data = image_to_bytes(Image.fromarray(windowed_download_image))
219
- st.download_button(
220
- label="Download MRI Image",
221
- data=image_data,
222
- file_name="downloaded_mri_image.png",
223
- mime="image/png"
224
- )
225
-
226
- # Load the original DICOM image for display
227
- display_image_tensor = cam_transforms(full_mri_temp_path).unsqueeze(0).to(device)
228
- display_image = display_image_tensor.squeeze()
229
-
230
- # Transform the image and apply windowing
231
- transformed_image = DICOM_Utils.transform_image_for_display(display_image)
232
- windowed_image = DICOM_Utils.apply_windowing(transformed_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)
233
- st.image(Image.fromarray(windowed_image), caption="Original MRI Visualization", use_column_width=True)
234
-
235
- # Expand to three channels
236
- windowed_image = np.expand_dims(windowed_image, axis=2)
237
- windowed_image = np.tile(windowed_image, [1, 1, 3])
238
-
239
- # Ensure both are of float32 type
240
- windowed_image = windowed_image.astype(np.float32)
241
-
242
- # Normalize to [0, 1] range
243
- windowed_image = np.float32(windowed_image) / 255
244
-
245
- # Build the CAM (Class Activation Map)
246
- target_layers = [mri_model.model.norm]
247
- cam = GradCAM(model=mri_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)
248
- grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])
249
- grayscale_cam = grayscale_cam[0, :]
250
-
251
- # Now you can safely call the show_cam_on_image function
252
- visualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)
253
- st.image(Image.fromarray(visualization), caption="CAM MRI Visualization", use_column_width=True)
254
-
255
- uploaded_ct_file = st.file_uploader("Upload a candidate CT DICOM", type=["dcm"])
256
- if uploaded_ct_file is not None:
257
- # Save the uploaded file to a temporary location
258
- ct_temp_path = os.path.join("CT_tempDir", uploaded_ct_file.name)
259
- with open(ct_temp_path, "wb") as f:
260
- f.write(uploaded_ct_file.getbuffer())
261
-
262
- full_ct_temp_path = current_directory +"\\"+ ct_temp_path
263
-
264
- # Apply evaluation transforms to the DICOM image for model prediction
265
- image_tensor = eval_transforms(full_ct_temp_path).unsqueeze(0).to(device)
266
-
267
- # Predict
268
- with torch.no_grad():
269
- outputs = ct_model(image_tensor).sigmoid().to("cpu").numpy()
270
- prob = outputs[0][0]
271
- CLOTS_CLASSIFICATION = False
272
- if(prob >= CT_INFERENCE_THRESHOLD):
273
- CLOTS_CLASSIFICATION=True
274
-
275
- st.header("CT Classification")
276
- st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")
277
- st.subheader(f"Confidence : {prob * 100:.1f}%")
278
-
279
- # Load the original DICOM image for download
280
- download_image_tensor = original_transforms(full_ct_temp_path).unsqueeze(0).to(device)
281
- download_image = download_image_tensor.squeeze()
282
-
283
- # Transform the download image and apply windowing
284
- transformed_download_image = DICOM_Utils.transform_image_for_display(download_image)
285
- windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)
286
-
287
- # Streamlit button to trigger image download
288
- image_data = image_to_bytes(Image.fromarray(windowed_download_image))
289
- st.download_button(
290
- label="Download CT Image",
291
- data=image_data,
292
- file_name="downloaded_ct_image.png",
293
- mime="image/png"
294
- )
295
-
296
- # Load the original DICOM image for display
297
- display_image_tensor = cam_transforms(full_ct_temp_path).unsqueeze(0).to(device)
298
- display_image = display_image_tensor.squeeze()
299
-
300
- # Transform the image and apply windowing
301
- transformed_image = DICOM_Utils.transform_image_for_display(display_image)
302
- windowed_image = DICOM_Utils.apply_windowing(transformed_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)
303
- st.image(Image.fromarray(windowed_image), caption="Original CT Visualization", use_column_width=True)
304
-
305
- # Expand to three channels
306
- windowed_image = np.expand_dims(windowed_image, axis=2)
307
- windowed_image = np.tile(windowed_image, [1, 1, 3])
308
-
309
- # Ensure both are of float32 type
310
- windowed_image = windowed_image.astype(np.float32)
311
-
312
- # Normalize to [0, 1] range
313
- windowed_image = np.float32(windowed_image) / 255
314
-
315
- # Build the CAM (Class Activation Map)
316
- target_layers = [ct_model.model.norm]
317
- cam = GradCAM(model=ct_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)
318
- grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])
319
- grayscale_cam = grayscale_cam[0, :]
320
-
321
- # Now you can safely call the show_cam_on_image function
322
- visualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)
323
- st.image(Image.fromarray(visualization), caption="CAM CT Visualization", use_column_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  # Evaluation Transforms
106
  eval_transforms = Compose(
107
  [
108
+ # LoadImage(image_only=True),
109
  AsChannelFirst(),
110
  ScaleIntensityRangePercentiles(lower=20, upper=80, b_min=0.0, b_max=1.0, clip=False, relative=True),
111
  Resize(spatial_size=SPATIAL_SIZE)
 
115
  # CAM Transforms
116
  cam_transforms = Compose(
117
  [
118
+ # LoadImage(image_only=True),
119
  AsChannelFirst(),
120
  Resize(spatial_size=SPATIAL_SIZE)
121
  ]
 
124
  # Original Transforms
125
  original_transforms = Compose(
126
  [
127
+ # LoadImage(image_only=True),
128
  AsChannelFirst()
129
  ]
130
  )
 
138
  # if os.path.exists("tempDir"):
139
  # shutil.rmtree(os.path.join("tempDir"))
140
 
141
+ # def create_dir(dirname: str):
142
+ # if not os.path.exists(dirname):
143
+ # os.makedirs(dirname, exist_ok=True)
144
 
145
+ # create_dir("CT_tempDir")
146
+ # create_dir("MRI_tempDir")
147
 
148
+ # # Get the current working directory
149
+ # current_directory = os.getcwd()
150
 
151
  set_determinism(seed=SEED)
152
  torch.manual_seed(SEED)
 
184
 
185
  uploaded_mri_file = st.file_uploader("Upload a candidate MRI DICOM", type=["dcm"])
186
  if uploaded_mri_file is not None:
187
+ # To check file details
188
+ file_details = {"FileName": uploaded_mri_file.name, "FileType": uploaded_mri_file.type, "FileSize": uploaded_mri_file.size}
189
+ st.write(file_details)
190
+
191
+ import pydicom
192
+ # Read DICOM file into NumPy array
193
+ dicom_data = pydicom.dcmread(uploaded_mri_file)
194
+ dicom_array = dicom_data.pixel_array
195
+
196
+ # Convert the data type to float32
197
+ dicom_array = dicom_array.astype(np.float32)
198
+
199
+ # Then add a channel dimension
200
+ dicom_array = dicom_array[:, :, np.newaxis]
201
+
202
+ # Check the shape and dtype of dicom_array
203
+ st.write(f"Shape of dicom_array: {dicom_array.shape}")
204
+ st.write(f"Data type of dicom_array: {dicom_array.dtype}")
205
+
206
+ transformed_array = eval_transforms(dicom_array)
207
+
208
+ # Convert to PyTorch tensor and move to device
209
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
210
+ image_tensor = transformed_array.clone().detach().unsqueeze(0).to(device)
211
+
212
+ # Predict
213
+ with torch.no_grad():
214
+ outputs = mri_model(image_tensor).sigmoid().to("cpu").numpy()
215
+ prob = outputs[0][0]
216
+ CLOTS_CLASSIFICATION = False
217
+ if(prob >= MRI_INFERENCE_THRESHOLD):
218
+ CLOTS_CLASSIFICATION=True
219
+
220
+ st.header("MRI Classification")
221
+ st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")
222
+ st.subheader(f"Confidence : {prob * 100:.1f}%")
223
+
224
+ # Load the original DICOM image for download
225
+ download_image_tensor = original_transforms(dicom_array).unsqueeze(0).to(device)
226
+ download_image = download_image_tensor.squeeze()
227
+
228
+ # Transform the download image and apply windowing
229
+ transformed_download_image = DICOM_Utils.transform_image_for_display(download_image)
230
+ windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)
231
+
232
+ # Streamlit button to trigger image download
233
+ image_data = image_to_bytes(Image.fromarray(windowed_download_image))
234
+ st.download_button(
235
+ label="Download MRI Image",
236
+ data=image_data,
237
+ file_name="downloaded_mri_image.png",
238
+ mime="image/png"
239
+ )
240
+
241
+ # Load the original DICOM image for display
242
+ display_image_tensor = cam_transforms(dicom_array).unsqueeze(0).to(device)
243
+ display_image = display_image_tensor.squeeze()
244
+
245
+ # Transform the image and apply windowing
246
+ transformed_image = DICOM_Utils.transform_image_for_display(display_image)
247
+ windowed_image = DICOM_Utils.apply_windowing(transformed_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)
248
+ st.image(Image.fromarray(windowed_image), caption="Original MRI Visualization", use_column_width=True)
249
+
250
+ # Expand to three channels
251
+ windowed_image = np.expand_dims(windowed_image, axis=2)
252
+ windowed_image = np.tile(windowed_image, [1, 1, 3])
253
+
254
+ # Ensure both are of float32 type
255
+ windowed_image = windowed_image.astype(np.float32)
256
+
257
+ # Normalize to [0, 1] range
258
+ windowed_image = np.float32(windowed_image) / 255
259
+
260
+ # Build the CAM (Class Activation Map)
261
+ target_layers = [mri_model.model.norm]
262
+ cam = GradCAM(model=mri_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)
263
+ grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])
264
+ grayscale_cam = grayscale_cam[0, :]
265
+
266
+ # Now you can safely call the show_cam_on_image function
267
+ visualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)
268
+ st.image(Image.fromarray(visualization), caption="CAM MRI Visualization", use_column_width=True)
269
+
270
+ # uploaded_ct_file = st.file_uploader("Upload a candidate CT DICOM", type=["dcm"])
271
+ # if uploaded_ct_file is not None:
272
+ # # Save the uploaded file to a temporary location
273
+ # ct_temp_path = os.path.join("CT_tempDir", uploaded_ct_file.name)
274
+ # with open(ct_temp_path, "wb") as f:
275
+ # f.write(uploaded_ct_file.getbuffer())
276
+
277
+ # full_ct_temp_path = current_directory +"\\"+ ct_temp_path
278
+
279
+ # # Apply evaluation transforms to the DICOM image for model prediction
280
+ # image_tensor = eval_transforms(full_ct_temp_path).unsqueeze(0).to(device)
281
+
282
+ # # Predict
283
+ # with torch.no_grad():
284
+ # outputs = ct_model(image_tensor).sigmoid().to("cpu").numpy()
285
+ # prob = outputs[0][0]
286
+ # CLOTS_CLASSIFICATION = False
287
+ # if(prob >= CT_INFERENCE_THRESHOLD):
288
+ # CLOTS_CLASSIFICATION=True
289
+
290
+ # st.header("CT Classification")
291
+ # st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")
292
+ # st.subheader(f"Confidence : {prob * 100:.1f}%")
293
+
294
+ # # Load the original DICOM image for download
295
+ # download_image_tensor = original_transforms(full_ct_temp_path).unsqueeze(0).to(device)
296
+ # download_image = download_image_tensor.squeeze()
297
+
298
+ # # Transform the download image and apply windowing
299
+ # transformed_download_image = DICOM_Utils.transform_image_for_display(download_image)
300
+ # windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)
301
+
302
+ # # Streamlit button to trigger image download
303
+ # image_data = image_to_bytes(Image.fromarray(windowed_download_image))
304
+ # st.download_button(
305
+ # label="Download CT Image",
306
+ # data=image_data,
307
+ # file_name="downloaded_ct_image.png",
308
+ # mime="image/png"
309
+ # )
310
+
311
+ # # Load the original DICOM image for display
312
+ # display_image_tensor = cam_transforms(full_ct_temp_path).unsqueeze(0).to(device)
313
+ # display_image = display_image_tensor.squeeze()
314
+
315
+ # # Transform the image and apply windowing
316
+ # transformed_image = DICOM_Utils.transform_image_for_display(display_image)
317
+ # windowed_image = DICOM_Utils.apply_windowing(transformed_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)
318
+ # st.image(Image.fromarray(windowed_image), caption="Original CT Visualization", use_column_width=True)
319
+
320
+ # # Expand to three channels
321
+ # windowed_image = np.expand_dims(windowed_image, axis=2)
322
+ # windowed_image = np.tile(windowed_image, [1, 1, 3])
323
+
324
+ # # Ensure both are of float32 type
325
+ # windowed_image = windowed_image.astype(np.float32)
326
+
327
+ # # Normalize to [0, 1] range
328
+ # windowed_image = np.float32(windowed_image) / 255
329
+
330
+ # # Build the CAM (Class Activation Map)
331
+ # target_layers = [ct_model.model.norm]
332
+ # cam = GradCAM(model=ct_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)
333
+ # grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])
334
+ # grayscale_cam = grayscale_cam[0, :]
335
+
336
+ # # Now you can safely call the show_cam_on_image function
337
+ # visualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)
338
+ # st.image(Image.fromarray(visualization), caption="CAM CT Visualization", use_column_width=True)