figure4-visualization-dataset / scripts /make_coordinate_grids.py
XIAOHAOYANG's picture
Add files using upload-large-folder tool
fde9a21 verified
Raw History Blame Contribute Delete
4.49 kB
#!/usr/bin/env python3
"""Render normalized coordinate grids for manual instance-order annotation.
The source image is never cropped. Output previews preserve aspect ratio and
label x/y coordinates in [0, 1], making the reviewed boxes portable back to the
full-resolution model input.
"""
from __future__ import annotations
import argparse
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageOps
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff"}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input_dir", type=Path)
parser.add_argument("output_dir", type=Path)
parser.add_argument("--max-width", type=int, default=1800)
parser.add_argument("--max-height", type=int, default=1400)
parser.add_argument("--minor-step", type=float, default=0.05)
parser.add_argument("--major-step", type=float, default=0.10)
return parser.parse_args()
def load_font(size: int) -> ImageFont.ImageFont:
for path in (
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf",
):
if Path(path).exists():
return ImageFont.truetype(path, size=size)
return ImageFont.load_default()
def step_values(step: float) -> list[float]:
if not 0 < step <= 1:
raise ValueError("grid step must be in (0, 1]")
count = round(1 / step)
if abs(count * step - 1.0) > 1e-6:
raise ValueError("grid step must divide 1 exactly")
return [index * step for index in range(count + 1)]
def outlined_text(
draw: ImageDraw.ImageDraw,
xy: tuple[int, int],
value: str,
font: ImageFont.ImageFont,
anchor: str,
) -> None:
draw.text(
xy,
value,
font=font,
anchor=anchor,
fill=(255, 255, 255),
stroke_width=3,
stroke_fill=(0, 0, 0),
)
def main() -> None:
args = parse_args()
paths = sorted(
path
for path in args.input_dir.iterdir()
if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES
)
if not paths:
raise ValueError(f"No images found in {args.input_dir}")
minor_values = step_values(args.minor_step)
major_values = step_values(args.major_step)
args.output_dir.mkdir(parents=True, exist_ok=True)
for path in paths:
with Image.open(path) as source:
image = ImageOps.exif_transpose(source).convert("RGB")
source_size = image.size
image.thumbnail((args.max_width, args.max_height), Image.Resampling.LANCZOS)
width, height = image.size
draw = ImageDraw.Draw(image, "RGBA")
minor_width = max(1, round(max(width, height) / 1000))
major_width = max(2, round(max(width, height) / 500))
for value in minor_values:
x = round(value * (width - 1))
y = round(value * (height - 1))
draw.line((x, 0, x, height - 1), fill=(255, 220, 0, 90), width=minor_width)
draw.line((0, y, width - 1, y), fill=(255, 220, 0, 90), width=minor_width)
font = load_font(max(18, round(max(width, height) / 65)))
for value in major_values:
x = round(value * (width - 1))
y = round(value * (height - 1))
draw.line((x, 0, x, height - 1), fill=(0, 255, 255, 190), width=major_width)
draw.line((0, y, width - 1, y), fill=(0, 255, 255, 190), width=major_width)
label = f"{value:.1f}"
label_x = min(max(x, 28), width - 28)
label_y = min(max(y, 24), height - 24)
outlined_text(draw, (label_x, 5), f"x={label}", font, "ma")
outlined_text(draw, (5, label_y), f"y={label}", font, "lm")
title_font = load_font(max(22, round(max(width, height) / 50)))
title = f"{path.name} | source {source_size[0]}x{source_size[1]}"
box = draw.textbbox((0, 0), title, font=title_font, stroke_width=2)
pad = max(8, round(max(width, height) / 180))
draw.rectangle(
(0, height - (box[3] - box[1]) - 2 * pad, min(width, box[2] + 2 * pad), height),
fill=(0, 0, 0, 175),
)
outlined_text(draw, (pad, height - pad), title, title_font, "ls")
output = args.output_dir / f"{path.stem}_grid.jpg"
image.save(output, quality=94, subsampling=0)
print(output)
if __name__ == "__main__":
main()