File size: 3,090 Bytes
db89723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

from pathlib import Path
from PIL import Image


DEFAULT_TILE_SIZE = 128
DEFAULT_OVERLAP = 32


def calculate_positions(length, tile_size, overlap):
    """
    Calculate tile starting positions along one dimension.

    The final tile always reaches the image boundary.
    """

    if tile_size <= 0:
        raise ValueError("tile_size must be positive.")

    if overlap < 0 or overlap >= tile_size:
        raise ValueError(
            "overlap must satisfy 0 <= overlap < tile_size."
        )

    stride = tile_size - overlap

    if length <= tile_size:
        return [0]

    positions = list(range(0, length - tile_size + 1, stride))

    # Ensure the final region is covered.
    last_position = length - tile_size

    if positions[-1] != last_position:
        positions.append(last_position)

    return positions


def create_tiles(
    image,
    tile_size=DEFAULT_TILE_SIZE,
    overlap=DEFAULT_OVERLAP
):
    """
    Split a PIL image into overlapping tiles.

    Returns:
        list of dictionaries containing:
            image
            x
            y
            width
            height
            index
    """

    if not isinstance(image, Image.Image):
        raise TypeError(
            "image must be a PIL.Image.Image"
        )

    image = image.convert("RGB")

    width, height = image.size

    x_positions = calculate_positions(
        width,
        tile_size,
        overlap
    )

    y_positions = calculate_positions(
        height,
        tile_size,
        overlap
    )

    tiles = []

    index = 0

    for y in y_positions:

        for x in x_positions:

            right = min(
                x + tile_size,
                width
            )

            bottom = min(
                y + tile_size,
                height
            )

            tile = image.crop(
                (x, y, right, bottom)
            )

            tiles.append(
                {
                    "image": tile,
                    "x": x,
                    "y": y,
                    "width": right - x,
                    "height": bottom - y,
                    "index": index
                }
            )

            index += 1

    return tiles


def save_tiles(
    tiles,
    output_dir,
    prefix="tile"
):
    """
    Save generated tiles to disk.
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(
        parents=True,
        exist_ok=True
    )

    metadata = []

    for tile_info in tiles:

        image = tile_info["image"]

        filename = (
            f"{prefix}_"
            f"{tile_info['index']:03d}_"
            f"x{tile_info['x']}_"
            f"y{tile_info['y']}.png"
        )

        path = output_dir / filename

        image.save(path)

        metadata.append(
            {
                "index": tile_info["index"],
                "x": tile_info["x"],
                "y": tile_info["y"],
                "width": tile_info["width"],
                "height": tile_info["height"],
                "filename": filename
            }
        )

    return metadata