Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

tiler.py 5.5 KB

You have to be logged in to leave a comment. Sign In
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
163
164
165
166
167
168
169
170
  1. # flake8: noqa: E402
  2. import argparse
  3. import warnings
  4. from pathlib import Path
  5. from typing import Optional, Tuple, Union
  6. import xarray
  7. warnings.filterwarnings("ignore", category=UserWarning)
  8. import math
  9. from dataclasses import dataclass
  10. import numpy as np
  11. import rioxarray
  12. from deadtrees.utils.data_handling import (
  13. make_blocks_vectorized,
  14. unmake_blocks_vectorized,
  15. )
  16. @dataclass
  17. class TileInfo:
  18. size: Tuple[int, int]
  19. subtiles: Tuple[int, int]
  20. def divisible_without_remainder(a, b):
  21. if b == 0:
  22. return False
  23. return True if a % b == 0 else False
  24. def inspect_tile(
  25. infile: Union[str, Path, xarray.DataArray],
  26. tile_shape: Tuple[int, int] = (8192, 8192),
  27. subtile_shape: Tuple[int, int] = (512, 512),
  28. ) -> TileInfo:
  29. with rioxarray.open_rasterio(infile).sel(band=1, drop=True) if not isinstance(
  30. infile, xarray.DataArray
  31. ) else infile as da:
  32. shape = tuple(da.shape)
  33. if not divisible_without_remainder(tile_shape[0], subtile_shape[0]):
  34. raise ValueError(f"Shapes unaligned (v): {tile_shape[0], subtile_shape[0]}")
  35. if not divisible_without_remainder(tile_shape[1], subtile_shape[1]):
  36. raise ValueError(f"Shapes unaligned (h): {tile_shape[1], subtile_shape[1]}")
  37. subtiles = (
  38. math.ceil(shape[0] / subtile_shape[0]),
  39. math.ceil(shape[1] / subtile_shape[1]),
  40. )
  41. return TileInfo(size=shape, subtiles=subtiles)
  42. class Tiler:
  43. def __init__(
  44. self,
  45. infile: Optional[Union[str, Path]] = None,
  46. tile_shape: Optional[Tuple[int, int]] = (2048, 2048),
  47. subtile_shape: Optional[Tuple[int, int]] = (256, 256),
  48. ) -> None:
  49. self._infile = infile
  50. self._tile_shape = tile_shape
  51. self._subtile_shape = subtile_shape
  52. if subtile_shape[0] != subtile_shape[1]:
  53. raise ValueError("Subtile required to have matching x/y dims")
  54. self._source: Optional[xarray.DataArray] = None
  55. self._target: Optional[xarray.DataArray] = None
  56. self._indata: Optional[np.ndarray] = None
  57. self._outdata: Optional[np.ndarray] = None
  58. self._batch_shape: Optional[np.ndarray] = None
  59. self._subtiles_to_use: Optional[np.ndarray] = None
  60. self._tile_info: Optional[TileInfo] = None
  61. def load_file(
  62. self,
  63. infile: Union[str, Path],
  64. tile_shape: Optional[Tuple[int, int]] = None,
  65. subtile_shape: Optional[Tuple[int, int]] = None,
  66. ) -> None:
  67. self._infile = infile
  68. self._tile_shape = tile_shape or self._tile_shape
  69. if subtile_shape:
  70. if subtile_shape[0] != subtile_shape[1]:
  71. raise ValueError("Subtile required to have matching x/y dims")
  72. self._subtile_shape = subtile_shape or self._subtile_shape
  73. self._tile_info = inspect_tile(
  74. self._infile, self._tile_shape, self._subtile_shape
  75. )
  76. self._source = rioxarray.open_rasterio(
  77. self._infile, chunks={"band": 4, "x": 256, "y": 256}
  78. )
  79. # define padded indata array and place original data inside
  80. sv = self._source.values
  81. if self._tile_shape != self._tile_info.size:
  82. self._indata = np.zeros((4, *self._tile_shape), dtype=self._source.dtype)
  83. self._indata[:, 0 : sv.shape[1], 0 : sv.shape[2]] = sv
  84. else:
  85. self._indata = sv
  86. # output xarray (single band)
  87. self._target = (
  88. self._source.sel(band=1, drop=True).astype("uint8").copy(deep=True)
  89. )
  90. # define padded outdata array
  91. self._outdata = np.zeros(self._tile_shape, dtype="uint8")
  92. # mark only necessary subtiles
  93. subtiles_mask = np.zeros(
  94. (
  95. self._tile_shape[0] // self._subtile_shape[0],
  96. self._tile_shape[1] // self._subtile_shape[1],
  97. ),
  98. dtype=bool,
  99. )
  100. subtiles_mask[
  101. 0 : self._tile_info.subtiles[0], 0 : self._tile_info.subtiles[1]
  102. ] = 1
  103. self._subtiles_to_use = subtiles_mask.ravel()
  104. def write_file(self, outfile: Union[str, Path]) -> None:
  105. if self._target is not None:
  106. # copy data from outdata array into dataarray
  107. self._target[:] = self._outdata[
  108. 0 : self._tile_info.size[0], 0 : self._tile_info.size[1]
  109. ]
  110. self._target.rio.to_raster(outfile, compress="LZW", tiled=True)
  111. def get_batches(self) -> np.ndarray:
  112. subtiles = make_blocks_vectorized(self._indata, self._subtile_shape[0])
  113. self._batch_shape = self._batch_shape or subtiles.shape
  114. return subtiles[self._subtiles_to_use]
  115. def put_batches(self, batches: np.ndarray) -> None:
  116. batches_expanded = []
  117. batch_idx = 0
  118. for flag in self._subtiles_to_use:
  119. if flag == 1:
  120. batches_expanded.append(batches[batch_idx])
  121. batch_idx += 1
  122. else:
  123. batches_expanded.append(np.zeros(batches[0].shape))
  124. batches_expanded = np.array(batches_expanded)
  125. self._outdata = unmake_blocks_vectorized(
  126. batches_expanded,
  127. self._subtile_shape[0],
  128. self._tile_shape[0],
  129. self._tile_shape[1],
  130. )
  131. # pass data into geo-registered rioxarray object (only subset of expanded tile if not complete tile)
  132. self._target = self._target.load()
  133. self._target.loc[:] = self._outdata[
  134. 0 : self._tile_info.size[0], 0 : self._tile_info.size[1]
  135. ]
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...