|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import torch |
| 4 | +from PIL import Image |
| 5 | + |
| 6 | +from refiners.fluxion.utils import image_to_tensor, no_grad, normalize, tensor_to_image |
| 7 | +from refiners.foundationals.swin.mvanet import MVANet |
| 8 | + |
| 9 | +BoundingBox = tuple[int, int, int, int] |
| 10 | + |
| 11 | + |
| 12 | +class BoxSegmenter: |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + *, |
| 16 | + margin: float = 0.05, |
| 17 | + weights: Path | str | dict[str, torch.Tensor] | None = None, |
| 18 | + device: torch.device | str = "cpu", |
| 19 | + ): |
| 20 | + assert margin >= 0 |
| 21 | + self.margin = margin |
| 22 | + |
| 23 | + self.device = torch.device(device) |
| 24 | + self.model = MVANet(device=self.device).eval() |
| 25 | + |
| 26 | + if weights is None: |
| 27 | + from huggingface_hub.file_download import hf_hub_download # type: ignore[reportUnknownVariableType] |
| 28 | + |
| 29 | + weights = hf_hub_download( |
| 30 | + repo_id="finegrain/finegrain-box-segmenter", |
| 31 | + filename="model.safetensors", |
| 32 | + revision="v0.1", |
| 33 | + ) |
| 34 | + |
| 35 | + if isinstance(weights, dict): |
| 36 | + self.model.load_state_dict(weights) |
| 37 | + else: |
| 38 | + self.model.load_from_safetensors(weights) |
| 39 | + |
| 40 | + def __call__(self, img: Image.Image, box_prompt: BoundingBox | None = None) -> Image.Image: |
| 41 | + return self.run(img, box_prompt) |
| 42 | + |
| 43 | + def add_margin(self, box: BoundingBox) -> BoundingBox: |
| 44 | + x0, y0, x1, y1 = box |
| 45 | + mx = int((x1 - x0) * self.margin) |
| 46 | + my = int((y1 - y0) * self.margin) |
| 47 | + return (x0 - mx, y0 - my, x1 + mx, y1 + my) |
| 48 | + |
| 49 | + @staticmethod |
| 50 | + def crop_pad(img: Image.Image, box: BoundingBox) -> Image.Image: |
| 51 | + img = img.convert("RGB") |
| 52 | + |
| 53 | + x0, y0, x1, y1 = box |
| 54 | + px0, py0, px1, py1 = (max(0, -x0), max(0, -y0), max(0, x1 - img.width), max(0, y1 - img.height)) |
| 55 | + if (px0, py0, px1, py1) == (0, 0, 0, 0): |
| 56 | + return img.crop(box) |
| 57 | + |
| 58 | + padded = Image.new("RGB", (img.width + px0 + px1, img.height + py0 + py1)) |
| 59 | + padded.paste(img, (px0, py0)) |
| 60 | + return padded.crop((x0 + px0, y0 + py0, x1 + px0, y1 + py0)) |
| 61 | + |
| 62 | + def predict(self, img: Image.Image) -> Image.Image: |
| 63 | + in_t = image_to_tensor(img.resize((1024, 1024), Image.Resampling.BILINEAR)).squeeze() |
| 64 | + in_t = normalize(in_t, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]).unsqueeze(0) |
| 65 | + with no_grad(): |
| 66 | + prediction: torch.Tensor = self.model(in_t.to(self.device)).sigmoid() |
| 67 | + return tensor_to_image(prediction).resize(img.size, Image.Resampling.BILINEAR) |
| 68 | + |
| 69 | + def run(self, img: Image.Image, box_prompt: BoundingBox | None = None) -> Image.Image: |
| 70 | + if box_prompt is None: |
| 71 | + box_prompt = (0, 0, img.width, img.height) |
| 72 | + |
| 73 | + box = self.add_margin(box_prompt) |
| 74 | + cropped = self.crop_pad(img, box) |
| 75 | + prediction = self.predict(cropped) |
| 76 | + |
| 77 | + out = Image.new("L", (img.width, img.height)) |
| 78 | + out.paste(prediction, box) |
| 79 | + return out |
0 commit comments