Spaces:
Sleeping
Sleeping
File size: 6,023 Bytes
e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad fb667fe e6062ad d5de94c e6062ad d5de94c e6062ad 217e57c e6062ad b33fab8 d5de94c b33fab8 e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c e6062ad d5de94c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
import tempfile
import time
from typing import Any
from collections.abc import Sequence
import gradio as gr
import numpy as np
import pillow_heif
import spaces
import torch
from gradio_image_annotation import image_annotator
from gradio_imageslider import ImageSlider
from PIL import Image
from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
from refiners.fluxion.utils import no_grad
from refiners.solutions import BoxSegmenter
BoundingBox = tuple[int, int, int, int]
pillow_heif.register_heif_opener()
pillow_heif.register_avif_opener()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize segmenter
segmenter = BoxSegmenter(device="cpu")
segmenter.device = device
segmenter.model = segmenter.model.to(device=segmenter.device)
def bbox_union(bboxes: Sequence[list[int]]) -> BoundingBox | None:
if not bboxes:
return None
for bbox in bboxes:
assert len(bbox) == 4
assert all(isinstance(x, int) for x in bbox)
return (
min(bbox[0] for bbox in bboxes),
min(bbox[1] for bbox in bboxes),
max(bbox[2] for bbox in bboxes),
max(bbox[3] for bbox in bboxes),
)
def apply_mask(
img: Image.Image,
mask_img: Image.Image,
defringe: bool = True,
) -> Image.Image:
assert img.size == mask_img.size
img = img.convert("RGB")
mask_img = mask_img.convert("L")
if defringe:
# Mitigate edge halo effects via color decontamination
rgb, alpha = np.asarray(img) / 255.0, np.asarray(mask_img) / 255.0
foreground = estimate_foreground_ml(rgb, alpha)
img = Image.fromarray((foreground * 255).astype("uint8"))
result = Image.new("RGBA", img.size)
result.paste(img, (0, 0), mask_img)
return result
@spaces.GPU
def _gpu_process(
img: Image.Image,
bbox: BoundingBox | None,
) -> tuple[Image.Image, BoundingBox | None, list[str]]:
time_log: list[str] = []
t0 = time.time()
mask = segmenter(img, bbox)
time_log.append(f"segment: {time.time() - t0}")
return mask, bbox, time_log
def _process(
img: Image.Image,
bbox: BoundingBox | None,
) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
# enforce max dimensions for pymatting performance reasons
if img.width > 2048 or img.height > 2048:
orig_res = max(img.width, img.height)
img.thumbnail((2048, 2048))
if isinstance(bbox, tuple):
x0, y0, x1, y1 = (int(x * 2048 / orig_res) for x in bbox)
bbox = (x0, y0, x1, y1)
mask, bbox, time_log = _gpu_process(img, bbox)
t0 = time.time()
masked_alpha = apply_mask(img, mask, defringe=True)
time_log.append(f"crop: {time.time() - t0}")
print(", ".join(time_log))
masked_rgb = Image.alpha_composite(Image.new("RGBA", masked_alpha.size, "white"), masked_alpha)
thresholded = mask.point(lambda p: 255 if p > 10 else 0)
bbox = thresholded.getbbox()
to_dl = masked_alpha.crop(bbox)
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
to_dl.save(temp, format="PNG")
temp.close()
return (img, masked_rgb), gr.DownloadButton(value=temp.name, interactive=True)
def process_bbox(prompts: dict[str, Any]) -> tuple[tuple[Image.Image, Image.Image], gr.DownloadButton]:
assert isinstance(img := prompts["image"], Image.Image)
assert isinstance(boxes := prompts["boxes"], list)
if len(boxes) == 1:
assert isinstance(box := boxes[0], dict)
bbox = tuple(box[k] for k in ["xmin", "ymin", "xmax", "ymax"])
else:
assert len(boxes) == 0
bbox = None
return _process(img, bbox)
def on_change_bbox(prompts: dict[str, Any] | None):
return gr.update(interactive=prompts is not None)
TITLE = """
<center>
<h1 style="font-size: 1.5rem; margin-bottom: 0.5rem;">
Object Cutter With Bounding Box
</h1>
<p>
Create high-quality HD cutouts for any object in your image using bounding box selection.
<br>
The object will be available on a transparent background, ready to paste elsewhere.
</p>
<p>
This space uses the
<a
href="https://huggingface.co/finegrain/finegrain-box-segmenter"
target="_blank"
>Finegrain Box Segmenter model</a>,
trained with a mix of natural data curated by Finegrain and
<a
href="https://huggingface.co/datasets/Nfiniteai/product-masks-sample"
target="_blank"
>synthetic data provided by Nfinite</a>.
</p>
</center>
"""
with gr.Blocks() as demo:
gr.HTML(TITLE)
with gr.Row():
with gr.Column():
annotator = image_annotator(
image_type="pil",
disable_edit_boxes=True,
show_download_button=False,
show_share_button=False,
single_box=True,
label="Input",
)
btn = gr.ClearButton(value="Cut Out Object", interactive=False)
with gr.Column():
oimg = ImageSlider(label="Before / After", show_download_button=False)
dlbt = gr.DownloadButton("Download Cutout", interactive=False)
btn.add(oimg)
annotator.change(
fn=on_change_bbox,
inputs=[annotator],
outputs=[btn],
)
btn.click(
fn=process_bbox,
inputs=[annotator],
outputs=[oimg, dlbt],
)
examples = [
{
"image": "examples/potted-plant.jpg",
"boxes": [{"xmin": 51, "ymin": 511, "xmax": 639, "ymax": 1255}],
},
{
"image": "examples/chair.jpg",
"boxes": [{"xmin": 98, "ymin": 330, "xmax": 973, "ymax": 1468}],
},
{
"image": "examples/black-lamp.jpg",
"boxes": [{"xmin": 88, "ymin": 148, "xmax": 700, "ymax": 1414}],
},
]
ex = gr.Examples(
examples=examples,
inputs=[annotator],
outputs=[oimg, dlbt],
fn=process_bbox,
cache_examples=True,
)
demo.launch(share=False) |