File size: 4,485 Bytes
fde9a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()