ji-song's picture
Initial release (seed 0 weights)
bd2e9e8 verified
Raw History Blame Contribute Delete
8.32 kB
#!/usr/bin/env python3
"""Tiled inference for the floorplan-global D-FINE detectors (STR / SPA / OBJ).
Floor-plan drawings are large and their symbols are small, so the models were trained on
1920x1920 tiles cut with 25% overlap. This script reproduces that protocol at inference time:
image -> 1920px tiles (25% overlap) -> D-FINE per tile -> shift boxes back to page
-> optional truncated-box filter -> per-class NMS across tiles
Requirements
* Upstream D-FINE source (Apache-2.0), pinned commit 956d170:
git clone https://github.com/Peterande/D-FINE && git -C D-FINE checkout 956d170
* torch, torchvision, pillow, pyyaml, safetensors (see requirements.txt)
Usage
python inference/infer.py --dfine-root ./D-FINE --image plan.png --out plan.json
python inference/infer.py --dfine-root ./D-FINE --image plan.png --viz plan_viz.png --device cuda:0
--model-dir defaults to the repository root (the folder that contains config.yml,
config.json and model.safetensors), i.e. the parent of this script's folder.
Output: JSON list of {"label", "category_id", "bbox": [x, y, w, h], "score"} in page pixels.
"""
import argparse
import json
import sys
from pathlib import Path
import torch
import torchvision.transforms as T
from PIL import Image
def tile_starts(size: int, tile: int, stride: int):
if size <= tile:
return [0]
starts = list(range(0, size - tile + 1, stride))
if starts[-1] != size - tile:
starts.append(size - tile)
return starts
def make_tiles(im: Image.Image, input_size: int, tile: int, stride: int):
w, h = im.size
meta = [(x0, y0, min(tile, w - x0), min(tile, h - y0))
for y0 in tile_starts(h, tile, stride) for x0 in tile_starts(w, tile, stride)]
tfm = T.Compose([T.Resize((input_size, input_size)), T.ToTensor()])
tiles = torch.stack([tfm(im.crop((x0, y0, x0 + tw, y0 + th))) for x0, y0, tw, th in meta])
return tiles, meta
def load_model(dfine_root: Path, model_dir: Path, device: str):
sys.path.insert(0, str(dfine_root))
from src.core import YAMLConfig # upstream D-FINE
from safetensors.torch import load_file
cfg = YAMLConfig(str(model_dir / "config.yml"))
cfg.model.load_state_dict(load_file(str(model_dir / "model.safetensors")), strict=True)
class Detector(torch.nn.Module):
def __init__(self):
super().__init__()
self.model = cfg.model.deploy()
self.postprocessor = cfg.postprocessor.deploy()
def forward(self, images, orig_sizes):
return self.postprocessor(self.model(images), orig_sizes)
return Detector().to(device).eval()
@torch.no_grad()
def detect(model, im, meta_cfg, device, batch_size=4, score_thr=None, nms_iou=None,
drop_truncated=False, trunc_edge=6.0):
from torchvision.ops import nms
tile = int(meta_cfg["tile_size"])
stride = round(tile * (1 - float(meta_cfg["tile_overlap"])))
score_thr = float(meta_cfg["score_threshold"] if score_thr is None else score_thr)
nms_iou = float(meta_cfg["nms_iou"] if nms_iou is None else nms_iou)
id2label = {int(k): v for k, v in meta_cfg["id2label"].items()}
tiles, meta = make_tiles(im, int(meta_cfg["input_size"]), tile, stride)
W = max(x0 + tw for x0, _, tw, _ in meta)
H = max(y0 + th for _, y0, _, th in meta)
e = float(trunc_edge)
tm = torch.tensor(meta, dtype=torch.float32, device=device)
cov = (tm[:, 0] + e, tm[:, 1] + e, tm[:, 0] + tm[:, 2] - e, tm[:, 1] + tm[:, 3] - e)
boxes_all, scores_all, labels_all = [], [], []
for i in range(0, len(meta), batch_size):
bm = meta[i:i + batch_size]
sizes = torch.tensor([[tw, th] for _, _, tw, th in bm], dtype=torch.float32, device=device)
labels, boxes, scores = model(tiles[i:i + batch_size].to(device), sizes)
for j, (x0, y0, tw, th) in enumerate(bm):
keep = scores[j] > score_thr
if drop_truncated and keep.any():
# A box glued to an *interior* tile edge is usually a cut-off fragment; drop it when
# another tile fully contains it (that tile sees the whole object).
b = boxes[j]
touch = torch.zeros_like(keep)
if x0 > 0:
touch |= b[:, 0] < e
if y0 > 0:
touch |= b[:, 1] < e
if x0 + tw < W:
touch |= b[:, 2] > tw - e
if y0 + th < H:
touch |= b[:, 3] > th - e
cand = keep & touch
if cand.any():
gx1, gy1, gx2, gy2 = (b[:, 0:1] + x0, b[:, 1:2] + y0, b[:, 2:3] + x0, b[:, 3:4] + y0)
covered = ((cov[0] <= gx1) & (cov[1] <= gy1) & (gx2 <= cov[2]) & (gy2 <= cov[3])).any(dim=1)
keep = keep & ~(cand & covered)
if not keep.any():
continue
b = boxes[j][keep].clone()
b[:, [0, 2]] += x0
b[:, [1, 3]] += y0
boxes_all.append(b)
scores_all.append(scores[j][keep])
labels_all.append(labels[j][keep])
if not boxes_all:
return []
boxes, scores, labels = torch.cat(boxes_all), torch.cat(scores_all), torch.cat(labels_all)
out = []
for cls in labels.unique().tolist():
if int(cls) not in id2label:
continue
m = labels == cls
k = nms(boxes[m], scores[m], iou_threshold=nms_iou)
for (x1, y1, x2, y2), s in zip(boxes[m][k].tolist(), scores[m][k].tolist()):
out.append({"label": id2label[int(cls)], "category_id": int(cls),
"bbox": [round(x1, 2), round(y1, 2), round(x2 - x1, 2), round(y2 - y1, 2)],
"score": round(s, 4)})
return sorted(out, key=lambda d: -d["score"])
def draw_viz(im, dets, path):
from PIL import ImageDraw
palette = [(230, 25, 75), (60, 180, 75), (0, 130, 200), (245, 130, 48), (145, 30, 180), (70, 240, 240),
(240, 50, 230), (210, 245, 60), (0, 128, 128), (170, 110, 40), (128, 0, 0), (0, 0, 128)]
canvas = im.copy()
dr = ImageDraw.Draw(canvas)
for d in dets:
x, y, w, h = d["bbox"]
c = palette[d["category_id"] % len(palette)]
dr.rectangle([x, y, x + w, y + h], outline=c, width=3)
dr.text((x + 3, y + 2), f'{d["label"]} {d["score"]:.2f}', fill=c)
canvas.save(path)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--dfine-root", required=True, type=Path, help="upstream D-FINE checkout (commit 956d170)")
ap.add_argument("--model-dir", type=Path, default=Path(__file__).resolve().parent.parent,
help="folder with config.yml, config.json, model.safetensors (default: repository root)")
ap.add_argument("--image", required=True, type=Path)
ap.add_argument("--out", type=Path, default=None, help="output JSON (default: stdout)")
ap.add_argument("--viz", type=Path, default=None, help="also write an overlay PNG with the boxes")
ap.add_argument("--device", default="cuda:0" if torch.cuda.is_available() else "cpu")
ap.add_argument("--batch-size", type=int, default=4)
ap.add_argument("--score-thr", type=float, default=None, help="override config.json score_threshold")
ap.add_argument("--nms-iou", type=float, default=None, help="override config.json nms_iou")
ap.add_argument("--drop-truncated", action="store_true",
help="drop cut-off fragments at interior tile edges (off by default = protocol of the reported metrics)")
a = ap.parse_args()
meta_cfg = json.loads((a.model_dir / "config.json").read_text())
model = load_model(a.dfine_root, a.model_dir, a.device)
Image.MAX_IMAGE_PIXELS = None # drawings can be very large
im = Image.open(a.image).convert("RGB")
dets = detect(model, im, meta_cfg, a.device, a.batch_size, a.score_thr, a.nms_iou, a.drop_truncated)
if a.viz:
draw_viz(im, dets, a.viz)
text = json.dumps(dets, ensure_ascii=False)
if a.out:
a.out.write_text(text + "\n")
print(f"{len(dets)} detections -> {a.out}", file=sys.stderr)
else:
print(text)
if __name__ == "__main__":
main()