Spaces:
Running
on
Zero
Running
on
Zero
major: add sam2 masking tab
Browse files- .gitignore +1 -0
- app.py +6 -15
- sam2_mask.py +201 -0
.gitignore
CHANGED
|
@@ -1 +1,2 @@
|
|
| 1 |
.env
|
|
|
|
|
|
| 1 |
.env
|
| 2 |
+
__pycache__/*
|
app.py
CHANGED
|
@@ -9,13 +9,10 @@ from controlnet_union import ControlNetModel_Union
|
|
| 9 |
from pipeline_fill_sd_xl import StableDiffusionXLFillPipeline
|
| 10 |
from PIL import Image, ImageDraw
|
| 11 |
import numpy as np
|
| 12 |
-
from
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
# predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2.1-hiera-large", device="cuda")
|
| 15 |
-
# print(predictor)
|
| 16 |
-
# with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
| 17 |
-
# predictor.set_image(<your_image>)
|
| 18 |
-
# masks, _, _ = predictor.predict(<input_prompts>)
|
| 19 |
|
| 20 |
MODELS = {
|
| 21 |
"RealVisXL V5.0 Lightning": "SG161222/RealVisXL_V5.0_Lightning",
|
|
@@ -479,15 +476,6 @@ with gr.Blocks(css=css, fill_height=True) as demo:
|
|
| 479 |
)
|
| 480 |
with gr.Column():
|
| 481 |
preview_button = gr.Button("Preview alignment and mask")
|
| 482 |
-
gr.Examples(
|
| 483 |
-
examples=[
|
| 484 |
-
["./examples/example_1.webp", 1280, 720, "Middle"],
|
| 485 |
-
["./examples/example_2.jpg", 1440, 810, "Left"],
|
| 486 |
-
["./examples/example_3.jpg", 1024, 1024, "Top"],
|
| 487 |
-
["./examples/example_3.jpg", 1024, 1024, "Bottom"],
|
| 488 |
-
],
|
| 489 |
-
inputs=[input_image_outpaint, width_slider, height_slider, alignment_dropdown],
|
| 490 |
-
)
|
| 491 |
with gr.Column():
|
| 492 |
result_outpaint = ImageSlider(
|
| 493 |
interactive=False,
|
|
@@ -496,6 +484,9 @@ with gr.Blocks(css=css, fill_height=True) as demo:
|
|
| 496 |
use_as_input_button_outpaint = gr.Button("Use as Input Image", visible=False)
|
| 497 |
history_gallery = gr.Gallery(label="History", columns=6, object_fit="contain", interactive=False)
|
| 498 |
preview_image = gr.Image(label="Preview")
|
|
|
|
|
|
|
|
|
|
| 499 |
with gr.TabItem("Misc"):
|
| 500 |
with gr.Column():
|
| 501 |
clear_cache_button = gr.Button("Clear CUDA Cache")
|
|
|
|
| 9 |
from pipeline_fill_sd_xl import StableDiffusionXLFillPipeline
|
| 10 |
from PIL import Image, ImageDraw
|
| 11 |
import numpy as np
|
| 12 |
+
from sam2_mask import create_sam2_tab, sam_process
|
| 13 |
+
|
| 14 |
+
#from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
MODELS = {
|
| 18 |
"RealVisXL V5.0 Lightning": "SG161222/RealVisXL_V5.0_Lightning",
|
|
|
|
| 476 |
)
|
| 477 |
with gr.Column():
|
| 478 |
preview_button = gr.Button("Preview alignment and mask")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
with gr.Column():
|
| 480 |
result_outpaint = ImageSlider(
|
| 481 |
interactive=False,
|
|
|
|
| 484 |
use_as_input_button_outpaint = gr.Button("Use as Input Image", visible=False)
|
| 485 |
history_gallery = gr.Gallery(label="History", columns=6, object_fit="contain", interactive=False)
|
| 486 |
preview_image = gr.Image(label="Preview")
|
| 487 |
+
with gr.TabItem("SAM2 Masking"):
|
| 488 |
+
input_image, points_map, output_result_mask = create_sam2_tab()
|
| 489 |
+
|
| 490 |
with gr.TabItem("Misc"):
|
| 491 |
with gr.Column():
|
| 492 |
clear_cache_button = gr.Button("Clear CUDA Cache")
|
sam2_mask.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
os.environ["TORCH_CUDNN_SDPA_ENABLED"] = "1"
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
import cv2
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from PIL import Image, ImageFilter
|
| 9 |
+
from sam2.build_sam import build_sam2
|
| 10 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 11 |
+
|
| 12 |
+
def preprocess_image(image):
|
| 13 |
+
return image, gr.State([]), gr.State([]), image
|
| 14 |
+
|
| 15 |
+
def get_point(point_type, tracking_points, trackings_input_label, first_frame_path, evt: gr.SelectData):
|
| 16 |
+
print(f"You selected {evt.value} at {evt.index} from {evt.target}")
|
| 17 |
+
tracking_points.value.append(evt.index)
|
| 18 |
+
print(f"TRACKING POINT: {tracking_points.value}")
|
| 19 |
+
if point_type == "include":
|
| 20 |
+
trackings_input_label.value.append(1)
|
| 21 |
+
elif point_type == "exclude":
|
| 22 |
+
trackings_input_label.value.append(0)
|
| 23 |
+
print(f"TRACKING INPUT LABEL: {trackings_input_label.value}")
|
| 24 |
+
# Open the image and get its dimensions
|
| 25 |
+
transparent_background = Image.open(first_frame_path).convert('RGBA')
|
| 26 |
+
w, h = transparent_background.size
|
| 27 |
+
# Define the circle radius as a fraction of the smaller dimension
|
| 28 |
+
fraction = 0.02 # You can adjust this value as needed
|
| 29 |
+
radius = int(fraction * min(w, h))
|
| 30 |
+
# Create a transparent layer to draw on
|
| 31 |
+
transparent_layer = np.zeros((h, w, 4), dtype=np.uint8)
|
| 32 |
+
for index, track in enumerate(tracking_points.value):
|
| 33 |
+
if trackings_input_label.value[index] == 1:
|
| 34 |
+
cv2.circle(transparent_layer, track, radius, (0, 255, 0, 255), -1)
|
| 35 |
+
else:
|
| 36 |
+
cv2.circle(transparent_layer, track, radius, (255, 0, 0, 255), -1)
|
| 37 |
+
# Convert the transparent layer back to an image
|
| 38 |
+
transparent_layer = Image.fromarray(transparent_layer, 'RGBA')
|
| 39 |
+
selected_point_map = Image.alpha_composite(transparent_background, transparent_layer)
|
| 40 |
+
return tracking_points, trackings_input_label, selected_point_map
|
| 41 |
+
|
| 42 |
+
# use bfloat16 for the entire notebook
|
| 43 |
+
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
|
| 44 |
+
if torch.cuda.get_device_properties(0).major >= 8:
|
| 45 |
+
# turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)
|
| 46 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 47 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 48 |
+
|
| 49 |
+
def show_mask(mask, ax, random_color=False, borders=True):
|
| 50 |
+
if random_color:
|
| 51 |
+
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
|
| 52 |
+
else:
|
| 53 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
| 54 |
+
h, w = mask.shape[-2:]
|
| 55 |
+
mask = mask.astype(np.uint8)
|
| 56 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
| 57 |
+
if borders:
|
| 58 |
+
import cv2
|
| 59 |
+
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
|
| 60 |
+
# Try to smooth contours
|
| 61 |
+
contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]
|
| 62 |
+
mask_image = cv2.drawContours(mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2)
|
| 63 |
+
ax.imshow(mask_image)
|
| 64 |
+
|
| 65 |
+
def show_points(coords, labels, ax, marker_size=375):
|
| 66 |
+
pos_points = coords[labels == 1]
|
| 67 |
+
neg_points = coords[labels == 0]
|
| 68 |
+
ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
|
| 69 |
+
ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
|
| 70 |
+
|
| 71 |
+
def show_box(box, ax):
|
| 72 |
+
x0, y0 = box[0], box[1]
|
| 73 |
+
w, h = box[2] - box[0], box[3] - box[1]
|
| 74 |
+
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0, 0, 0, 0), lw=2))
|
| 75 |
+
|
| 76 |
+
def show_masks(image, masks, scores, point_coords=None, box_coords=None, input_labels=None, borders=True):
|
| 77 |
+
combined_images = [] # List to store filenames of images with masks overlaid
|
| 78 |
+
mask_images = [] # List to store filenames of separate mask images
|
| 79 |
+
for i, (mask, score) in enumerate(zip(masks, scores)):
|
| 80 |
+
# ---- Original Image with Mask Overlaid ----
|
| 81 |
+
plt.figure(figsize=(10, 10))
|
| 82 |
+
plt.imshow(image)
|
| 83 |
+
show_mask(mask, plt.gca(), borders=borders) # Draw the mask with borders
|
| 84 |
+
if box_coords is not None:
|
| 85 |
+
show_box(box_coords, plt.gca())
|
| 86 |
+
if len(scores) > 1:
|
| 87 |
+
plt.title(f"Mask {i+1}, Score: {score:.3f}", fontsize=18)
|
| 88 |
+
plt.axis('off')
|
| 89 |
+
# Save the figure as a JPG file
|
| 90 |
+
combined_filename = f"combined_image_{i+1}.jpg"
|
| 91 |
+
plt.savefig(combined_filename, format='jpg', bbox_inches='tight')
|
| 92 |
+
combined_images.append(combined_filename)
|
| 93 |
+
plt.close() # Close the figure to free up memory
|
| 94 |
+
# ---- Separate Mask Image (White Mask on Black Background) ----
|
| 95 |
+
# Create a black image
|
| 96 |
+
mask_image = np.zeros_like(image, dtype=np.uint8)
|
| 97 |
+
# The mask is a binary array where the masked area is 1, else 0.
|
| 98 |
+
# Convert the mask to a white color in the mask_image
|
| 99 |
+
mask_layer = (mask > 0).astype(np.uint8) * 255
|
| 100 |
+
for c in range(3): # Assuming RGB, repeat mask for all channels
|
| 101 |
+
mask_image[:, :, c] = mask_layer
|
| 102 |
+
# Save the mask image
|
| 103 |
+
mask_filename = f"mask_image_{i+1}.png"
|
| 104 |
+
Image.fromarray(mask_image).save(mask_filename)
|
| 105 |
+
mask_images.append(mask_filename)
|
| 106 |
+
plt.close() # Close the figure to free up memory
|
| 107 |
+
return combined_images, mask_images
|
| 108 |
+
|
| 109 |
+
def sam_process(input_image, tracking_points, trackings_input_label):
|
| 110 |
+
image = Image.open(input_image)
|
| 111 |
+
image = np.array(image.convert("RGB"))
|
| 112 |
+
# if checkpoint == "tiny":
|
| 113 |
+
# sam2_checkpoint = "./checkpoints/sam2_hiera_tiny.pt"
|
| 114 |
+
# model_cfg = "sam2_hiera_t.yaml"
|
| 115 |
+
# elif checkpoint == "small":
|
| 116 |
+
# sam2_checkpoint = "./checkpoints/sam2_hiera_small.pt"
|
| 117 |
+
# model_cfg = "sam2_hiera_s.yaml"
|
| 118 |
+
# elif checkpoint == "base-plus":
|
| 119 |
+
# sam2_checkpoint = "./checkpoints/sam2_hiera_base_plus.pt"
|
| 120 |
+
# model_cfg = "sam2_hiera_b+.yaml"
|
| 121 |
+
# elif checkpoint == "large":
|
| 122 |
+
# sam2_checkpoint = "./checkpoints/sam2_hiera_large.pt"
|
| 123 |
+
# model_cfg = "sam2_hiera_l.yaml"
|
| 124 |
+
predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2.1-hiera-large")
|
| 125 |
+
# print(predictor)
|
| 126 |
+
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
| 127 |
+
predictor.set_image(image)
|
| 128 |
+
input_point = np.array(tracking_points.value)
|
| 129 |
+
input_label = np.array(trackings_input_label.value)
|
| 130 |
+
print(predictor._features["image_embed"].shape, predictor._features["image_embed"][-1].shape)
|
| 131 |
+
masks, scores, logits = predictor.predict(
|
| 132 |
+
point_coords=input_point,
|
| 133 |
+
point_labels=input_label,
|
| 134 |
+
multimask_output=False,
|
| 135 |
+
)
|
| 136 |
+
sorted_ind = np.argsort(scores)[::-1]
|
| 137 |
+
masks = masks[sorted_ind]
|
| 138 |
+
scores = scores[sorted_ind]
|
| 139 |
+
logits = logits[sorted_ind]
|
| 140 |
+
print(masks.shape)
|
| 141 |
+
results, mask_results = show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label, borders=True)
|
| 142 |
+
print(results)
|
| 143 |
+
return results[0], mask_results[0]
|
| 144 |
+
# sam2_model = build_sam2(model_cfg, sam2_checkpoint, device="cuda")
|
| 145 |
+
# predictor = SAM2ImagePredictor(sam2_model)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def create_sam2_tab():
|
| 150 |
+
first_frame_path = gr.State()
|
| 151 |
+
tracking_points = gr.State([])
|
| 152 |
+
trackings_input_label = gr.State([])
|
| 153 |
+
with gr.Column():
|
| 154 |
+
gr.Markdown("# SAM2 Image Predictor")
|
| 155 |
+
gr.Markdown("This is a simple demo for image segmentation with SAM2.")
|
| 156 |
+
gr.Markdown("""Instructions:
|
| 157 |
+
1. Upload your image
|
| 158 |
+
2. With 'include' point type selected, Click on the object to mask
|
| 159 |
+
3. Switch to 'exclude' point type if you want to specify an area to avoid
|
| 160 |
+
4. Submit !
|
| 161 |
+
""")
|
| 162 |
+
with gr.Row():
|
| 163 |
+
with gr.Column():
|
| 164 |
+
input_image = gr.Image(label="input image", interactive=False, type="filepath", visible=False)
|
| 165 |
+
points_map = gr.Image(
|
| 166 |
+
label="points map",
|
| 167 |
+
type="filepath",
|
| 168 |
+
interactive=True
|
| 169 |
+
)
|
| 170 |
+
with gr.Row():
|
| 171 |
+
point_type = gr.Radio(label="point type", choices=["include", "exclude"], value="include")
|
| 172 |
+
clear_points_btn = gr.Button("Clear Points")
|
| 173 |
+
checkpoint = gr.Dropdown(label="Checkpoint", choices=["tiny", "small", "base-plus", "large"], value="tiny")
|
| 174 |
+
submit_btn = gr.Button("Submit")
|
| 175 |
+
with gr.Column():
|
| 176 |
+
output_result = gr.Image()
|
| 177 |
+
output_result_mask = gr.Image()
|
| 178 |
+
clear_points_btn.click(
|
| 179 |
+
fn=admin_preprocess_image,
|
| 180 |
+
inputs=input_image,
|
| 181 |
+
outputs=[first_frame_path, tracking_points, trackings_input_label, points_map],
|
| 182 |
+
queue=False
|
| 183 |
+
)
|
| 184 |
+
points_map.upload(
|
| 185 |
+
fn=admin_preprocess_image,
|
| 186 |
+
inputs=[points_map],
|
| 187 |
+
outputs=[first_frame_path, tracking_points, trackings_input_label, input_image],
|
| 188 |
+
queue=False
|
| 189 |
+
)
|
| 190 |
+
points_map.select(
|
| 191 |
+
fn=admin_get_point,
|
| 192 |
+
inputs=[point_type, tracking_points, trackings_input_label, first_frame_path],
|
| 193 |
+
outputs=[tracking_points, trackings_input_label, points_map],
|
| 194 |
+
queue=False
|
| 195 |
+
)
|
| 196 |
+
submit_btn.click(
|
| 197 |
+
fn=sam_process,
|
| 198 |
+
inputs=[input_image, checkpoint, tracking_points, trackings_input_label],
|
| 199 |
+
outputs=[output_result, output_result_mask]
|
| 200 |
+
)
|
| 201 |
+
return input_image, points_map, output_result_mask
|