Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from sam2.build_sam import build_sam2
|
| 8 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 9 |
+
|
| 10 |
+
# use bfloat16 for the entire notebook
|
| 11 |
+
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
|
| 12 |
+
|
| 13 |
+
if torch.cuda.get_device_properties(0).major >= 8:
|
| 14 |
+
# turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)
|
| 15 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 16 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 17 |
+
|
| 18 |
+
def show_mask(mask, ax, random_color=False, borders = True):
|
| 19 |
+
if random_color:
|
| 20 |
+
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
|
| 21 |
+
else:
|
| 22 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
| 23 |
+
h, w = mask.shape[-2:]
|
| 24 |
+
mask = mask.astype(np.uint8)
|
| 25 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
| 26 |
+
if borders:
|
| 27 |
+
import cv2
|
| 28 |
+
contours, _ = cv2.findContours(mask,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
|
| 29 |
+
# Try to smooth contours
|
| 30 |
+
contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]
|
| 31 |
+
mask_image = cv2.drawContours(mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2)
|
| 32 |
+
ax.imshow(mask_image)
|
| 33 |
+
|
| 34 |
+
def show_points(coords, labels, ax, marker_size=375):
|
| 35 |
+
pos_points = coords[labels==1]
|
| 36 |
+
neg_points = coords[labels==0]
|
| 37 |
+
ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
|
| 38 |
+
ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
|
| 39 |
+
|
| 40 |
+
def show_box(box, ax):
|
| 41 |
+
x0, y0 = box[0], box[1]
|
| 42 |
+
w, h = box[2] - box[0], box[3] - box[1]
|
| 43 |
+
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0, 0, 0, 0), lw=2))
|
| 44 |
+
|
| 45 |
+
def show_masks(image, masks, scores, point_coords=None, box_coords=None, input_labels=None, borders=True):
|
| 46 |
+
masks_store = []
|
| 47 |
+
for i, (mask, score) in enumerate(zip(masks, scores)):
|
| 48 |
+
plt.figure(figsize=(10, 10))
|
| 49 |
+
plt.imshow(image)
|
| 50 |
+
show_mask(mask, plt.gca(), borders=borders)
|
| 51 |
+
if point_coords is not None:
|
| 52 |
+
assert input_labels is not None
|
| 53 |
+
show_points(point_coords, input_labels, plt.gca())
|
| 54 |
+
if box_coords is not None:
|
| 55 |
+
# boxes
|
| 56 |
+
show_box(box_coords, plt.gca())
|
| 57 |
+
if len(scores) > 1:
|
| 58 |
+
plt.title(f"Mask {i+1}, Score: {score:.3f}", fontsize=18)
|
| 59 |
+
plt.axis('off')
|
| 60 |
+
# plt.show()
|
| 61 |
+
|
| 62 |
+
# Save the figure as a JPG file
|
| 63 |
+
filename = f"masked_image_{i+1}.jpg"
|
| 64 |
+
plt.savefig(filename, format='jpg', bbox_inches='tight')
|
| 65 |
+
|
| 66 |
+
masks_store.append(filename)
|
| 67 |
+
|
| 68 |
+
# Close the figure to free up memory
|
| 69 |
+
plt.close()
|
| 70 |
+
|
| 71 |
+
return masks_store
|
| 72 |
+
|
| 73 |
+
def sam_process(input_image):
|
| 74 |
+
image = Image.open(input_image)
|
| 75 |
+
image = np.array(image.convert("RGB"))
|
| 76 |
+
|
| 77 |
+
sam2_checkpoint = "./checkpoints/sam2_hiera_large.pt"
|
| 78 |
+
model_cfg = "sam2_hiera_l.yaml"
|
| 79 |
+
|
| 80 |
+
sam2_model = build_sam2(model_cfg, sam2_checkpoint, device="cuda")
|
| 81 |
+
|
| 82 |
+
predictor = SAM2ImagePredictor(sam2_model)
|
| 83 |
+
|
| 84 |
+
predictor.set_image(image)
|
| 85 |
+
|
| 86 |
+
input_point = np.array([[539 384]])
|
| 87 |
+
input_label = np.array([1])
|
| 88 |
+
|
| 89 |
+
print(predictor._features["image_embed"].shape, predictor._features["image_embed"][-1].shape)
|
| 90 |
+
|
| 91 |
+
masks, scores, logits = predictor.predict(
|
| 92 |
+
point_coords=input_point,
|
| 93 |
+
point_labels=input_label,
|
| 94 |
+
multimask_output=True,
|
| 95 |
+
)
|
| 96 |
+
sorted_ind = np.argsort(scores)[::-1]
|
| 97 |
+
masks = masks[sorted_ind]
|
| 98 |
+
scores = scores[sorted_ind]
|
| 99 |
+
logits = logits[sorted_ind]
|
| 100 |
+
|
| 101 |
+
print(masks.shape)
|
| 102 |
+
|
| 103 |
+
results = show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label, borders=True)
|
| 104 |
+
print(results)
|
| 105 |
+
|
| 106 |
+
return results
|
| 107 |
+
|
| 108 |
+
with gr.Blocks() as demo:
|
| 109 |
+
with gr.Column():
|
| 110 |
+
input_image = gr.Image(label="input image", type="filepath"),
|
| 111 |
+
submit_btn = gr.Button("Submit")
|
| 112 |
+
output_result = gr.Textbox()
|
| 113 |
+
submit_btn.click(
|
| 114 |
+
fn = sam_process,
|
| 115 |
+
inputs = [input_image],
|
| 116 |
+
outputs = [output_result]
|
| 117 |
+
)
|
| 118 |
+
demo.launch()
|