Files changed (1) hide show
  1. app.py +100 -0
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import pydicom
5
+ import os
6
+ from skimage import transform
7
+ import torch
8
+ from segment_anything import sam_model_registry
9
+ import matplotlib.pyplot as plt
10
+ from PIL import Image
11
+ import io
12
+
13
+ # Function to load bounding boxes from CSV
14
+ def load_bounding_boxes(csv_file):
15
+ # Assuming CSV file has columns: 'filename', 'x_min', 'y_min', 'x_max', 'y_max'
16
+ df = pd.read_csv(csv_file)
17
+ return df
18
+
19
+ # Function to load DICOM images
20
+ def load_dicom_images(folder_path):
21
+ images = []
22
+ for filename in sorted(os.listdir(folder_path)):
23
+ if filename.endswith(".dcm"):
24
+ filepath = os.path.join(folder_path, filename)
25
+ ds = pydicom.dcmread(filepath)
26
+ img = ds.pixel_array
27
+ images.append(img)
28
+ return np.array(images)
29
+
30
+ # MedSAM inference function
31
+ def medsam_inference(medsam_model, img, box, H, W, target_size):
32
+ # Resize image and box to target size
33
+ img_resized = transform.resize(img, (target_size, target_size), anti_aliasing=True)
34
+ box_resized = np.array(box) * (target_size / np.array([W, H, W, H]))
35
+
36
+ # Convert image to PyTorch tensor
37
+ img_tensor = torch.from_numpy(img_resized).float().unsqueeze(0).unsqueeze(0).to(device) # Add channel and batch dimension
38
+
39
+ # Model expects box in format (x0, y0, x1, y1)
40
+ box_tensor = torch.tensor(box_resized, dtype=torch.float32).unsqueeze(0).to(device) # Add batch dimension
41
+
42
+ # MedSAM inference
43
+ img_embed = medsam_model.image_encoder(img_tensor)
44
+ mask = medsam_model.predict(img_embed, box_tensor)
45
+
46
+ # Post-process mask: resize back to original size
47
+ mask_resized = transform.resize(mask[0].cpu().numpy(), (H, W))
48
+
49
+ return mask_resized
50
+
51
+ # Function for visualizing images with masks
52
+ def visualize(images, masks, box):
53
+ fig, ax = plt.subplots(len(images), 2, figsize=(10, 5*len(images)))
54
+ for i, (image, mask) in enumerate(zip(images, masks)):
55
+ ax[i, 0].imshow(image, cmap='gray')
56
+ ax[i, 0].add_patch(plt.Rectangle((box[0], box[1]), box[2]-box[0], box[3]-box[1], edgecolor="red", facecolor="none"))
57
+ ax[i, 1].imshow(image, cmap='gray')
58
+ ax[i, 1].imshow(mask, alpha=0.5, cmap="jet")
59
+ plt.tight_layout()
60
+ buf = io.BytesIO()
61
+ plt.savefig(buf, format='png')
62
+ plt.close(fig)
63
+ buf.seek(0)
64
+ return buf
65
+
66
+ # Main function for Gradio app
67
+ def process_images(csv_file, dicom_folder, target_size):
68
+ bounding_boxes = load_bounding_boxes(csv_file)
69
+ dicom_images = load_dicom_images(dicom_folder)
70
+
71
+ # Initialize MedSAM model
72
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
73
+ medsam_model = sam_model_registry['your_model_version'](checkpoint='path_to_your_checkpoint')
74
+ medsam_model = medsam_model.to(device)
75
+ medsam_model.eval()
76
+
77
+ masks = []
78
+ for index, row in bounding_boxes.iterrows():
79
+ if index >= len(dicom_images):
80
+ continue # Skip if the index exceeds the number of images
81
+
82
+ image = dicom_images[index]
83
+ H, W = image.shape
84
+ box = [row['x_min'], row['y_min'], row['x_max'], row['y_max']]
85
+
86
+ mask = medsam_inference(medsam_model, image, box, H, W, target_size)
87
+ masks.append(mask)
88
+
89
+ visualizations = visualize(dicom_images, masks, box)
90
+
91
+ return visualizations, np.array(masks)
92
+
93
+ # Set up Gradio interface
94
+ iface = gr.Interface(
95
+ fn=process_images,
96
+ inputs=[gr.inputs.File(type="file"), gr.inputs.Directory()],
97
+ outputs=[gr.outputs.Image(type="plot"), gr.outputs.File(type="numpy")]
98
+ )
99
+
100
+ iface.launch()