flaviagiammarino commited on
Commit
8c2476e
1 Parent(s): e08b6b7

Upload tf_example.py

Browse files
Files changed (1) hide show
  1. scripts/tf_example.py +42 -0
scripts/tf_example.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from PIL import Image
5
+ from transformers import TFSamModel, SamProcessor
6
+
7
+ model = TFSamModel.from_pretrained("flaviagiammarino/medsam-vit-base")
8
+ processor = SamProcessor.from_pretrained("flaviagiammarino/medsam-vit-base")
9
+
10
+ img_url = "https://raw.githubusercontent.com/bowang-lab/MedSAM/main/assets/img_demo.png"
11
+ raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
12
+ input_boxes = [95., 255., 190., 350.]
13
+
14
+ inputs = processor(raw_image, input_boxes=[[input_boxes]], return_tensors="tf")
15
+ outputs = model(**inputs, multimask_output=False)
16
+ masks = processor.image_processor.post_process_masks([outputs.pred_masks.numpy()[0],], inputs["original_sizes"].numpy(), inputs["reshaped_input_sizes"].numpy())
17
+
18
+ def show_mask(mask, ax, random_color):
19
+ if random_color:
20
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
21
+ else:
22
+ color = np.array([251/255, 252/255, 30/255, 0.6])
23
+ h, w = mask.shape[-2:]
24
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
25
+ ax.imshow(mask_image)
26
+
27
+ def show_box(box, ax):
28
+ x0, y0 = box[0], box[1]
29
+ w, h = box[2] - box[0], box[3] - box[1]
30
+ ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor="blue", facecolor=(0, 0, 0, 0), lw=2))
31
+
32
+ fig, ax = plt.subplots(1, 2, figsize=(10, 5))
33
+ ax[0].imshow(np.array(raw_image))
34
+ show_box(input_boxes, ax[0])
35
+ ax[0].set_title("Input Image and Bounding Box")
36
+ ax[0].axis("off")
37
+ ax[1].imshow(np.array(raw_image))
38
+ show_mask(masks[0], ax=ax[1], random_color=False)
39
+ show_box(input_boxes, ax[1])
40
+ ax[1].set_title("MedSAM Segmentation")
41
+ ax[1].axis("off")
42
+ plt.show()