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

createmasks.py 6.8 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  1. # createmasks stage
  2. import argparse
  3. from functools import partial
  4. from pathlib import Path
  5. from typing import Iterable, Union
  6. import psutil
  7. from pygeos.set_operations import union
  8. import geopandas as gpd
  9. import numpy as np
  10. import pandas as pd
  11. import rioxarray
  12. import xarray as xr
  13. from shapely.geometry import Polygon
  14. from tqdm.contrib.concurrent import process_map
  15. def make_poly(coords: pd.Series) -> Polygon:
  16. """Create Shapely polygon (a tile boundary) from x1,y1 and x2,y2 coordinates"""
  17. xs = [coords[v] for v in "x1,x1,x2,x2,x1".split(",")]
  18. ys = [coords[v] for v in "y1,y2,y2,y1,y1".split(",")]
  19. return Polygon(zip(xs, ys))
  20. def _identify_empty(tile: Union[Path, str]) -> bool:
  21. """Helper func for exclude_nodata_tiles"""
  22. with xr.open_rasterio(tile).sel(band=1) as t:
  23. # original check
  24. # status = True if t.max().values - t.min().values > 0 else False
  25. # check 2 (edge tiles with all white/ black are also detected)
  26. return False if np.isin(t, [0, 255]).all() else True
  27. def exclude_nodata_tiles(
  28. path: Iterable[Union[Path, str]],
  29. tiles_df: gpd.GeoDataFrame,
  30. workers: int,
  31. ) -> gpd.GeoDataFrame:
  32. """Identify tiles that only contain NoData (in parallel)"""
  33. print(f"WORKERS: {workers}")
  34. tile_names = sorted([Path(p) if isinstance(p, str) else p for p in path])
  35. results = process_map(_identify_empty, tile_names, max_workers=workers, chunksize=1)
  36. valid_d = dict([(t.name, r) for t, r in zip(tile_names, results)])
  37. tiles_df["status"] = tiles_df.filename.map(valid_d)
  38. # limit tiles to those with actual data (and delete status column afterwards)
  39. return tiles_df[tiles_df.status == 1].drop("status", axis=1)
  40. def create_tile_grid_gdf(path: Union[Path, str], crs: str) -> gpd.GeoDataFrame:
  41. """Convert gdal_tile split info file into geopandas dataframe"""
  42. tiles_df = pd.read_csv(path, sep=";", header=None)
  43. tiles_df.columns = ["filename", "x1", "x2", "y1", "y2"]
  44. tiles_df["geometry"] = tiles_df.apply(make_poly, axis=1)
  45. tiles_df = tiles_df.drop(["x1", "x2", "y1", "y2"], axis=1)
  46. tiles_gpd = gpd.GeoDataFrame(tiles_df, crs=crs, geometry=tiles_df.geometry)
  47. return tiles_gpd
  48. def split_groundtruth_data_by_tiles(
  49. groundtruth: gpd.GeoDataFrame, tiles_df: gpd.GeoDataFrame
  50. ) -> gpd.GeoDataFrame:
  51. """Split the oberserved dead tree areas into tile segments for faster downstream processing"""
  52. union_gpd = gpd.overlay(tiles_df, groundtruth, how="intersection")
  53. train_files = list(sorted(union_gpd.filename.value_counts().keys()))
  54. tiles_with_groundtruth = tiles_df[tiles_df.filename.isin(train_files)]
  55. return tiles_with_groundtruth, union_gpd # union_gpd[union_gpd.id == 2]
  56. def _mask_tile(
  57. tile_filename: str,
  58. *,
  59. groundtruth_df: gpd.GeoDataFrame,
  60. crs: str,
  61. inpath: Path,
  62. outpath: Path,
  63. simple: bool = False,
  64. ) -> float:
  65. image_tile_path = inpath / tile_filename
  66. mask_tile_path = outpath / tile_filename
  67. with rioxarray.open_rasterio(
  68. image_tile_path, chunks={"band": 4, "x": 256, "y": 256}
  69. ) as tile:
  70. mask_orig = xr.ones_like(tile.load().sel(band=1, drop=True), dtype="uint8")
  71. mask_orig.rio.set_crs(crs)
  72. selection = groundtruth_df.loc[groundtruth_df.filename == tile_filename]
  73. if simple:
  74. # just use the geometry for clipping (single-class)
  75. mask = mask_orig.rio.clip(
  76. selection.geometry,
  77. crs,
  78. drop=False,
  79. invert=False,
  80. all_touched=True,
  81. from_disk=True,
  82. )
  83. else:
  84. # use type col from shapefile to create (multi-)classification masks
  85. classes = [0, 1, 2] # 0: non-class, 1: coniferous, 2: broadleaf
  86. selection.loc[:, "type"] = pd.to_numeric(selection["type"])
  87. masks = [mask_orig * 0]
  88. for c in classes[1:]:
  89. gdf = selection.loc[selection["type"] == c, :]
  90. if len(gdf) > 0:
  91. mask = mask_orig.rio.clip(
  92. gdf.geometry,
  93. crs,
  94. drop=False,
  95. invert=False,
  96. all_touched=True,
  97. from_disk=True,
  98. )
  99. else:
  100. mask = mask_orig * 0
  101. masks.append(mask)
  102. mask = xr.concat(masks, pd.Index(classes, name="classes")).argmax(
  103. dim="classes"
  104. )
  105. mask.astype("uint8").rio.to_raster(mask_tile_path, tiled=True)
  106. mask_sum = np.count_nonzero(mask.values) # just for checks
  107. return mask_sum
  108. def create_tile_mask_geotiffs(
  109. tiles_df_train: gpd.GeoDataFrame, workers: int, **kwargs
  110. ) -> None:
  111. """Create binary mask geotiffs"""
  112. process_map(
  113. partial(_mask_tile, **kwargs),
  114. tiles_df_train.filename.values,
  115. max_workers=workers,
  116. chunksize=1,
  117. )
  118. def create_masks(
  119. indir: Path,
  120. outdir: Path,
  121. shpfile: Path,
  122. workers: int,
  123. simple: bool,
  124. ) -> None:
  125. """
  126. Stage 1: produce masks for training tiles
  127. """
  128. # load domain shape files and use its crs for the entire script
  129. groundtruth = gpd.read_file(shpfile).explode()
  130. if "Type" in list(groundtruth.columns.values):
  131. groundtruth = groundtruth.rename(columns={"Type": "type"})
  132. crs = groundtruth.crs # reference crs
  133. tiles_df = create_tile_grid_gdf(indir / "locations.csv", crs)
  134. tiles_df = exclude_nodata_tiles(
  135. sorted(indir.glob("*.tif")),
  136. tiles_df,
  137. workers,
  138. )
  139. print(f"len2: {len(tiles_df)}")
  140. tiles_df.to_file("locations.shp")
  141. tiles_df_train, groundtruth_df = split_groundtruth_data_by_tiles(
  142. groundtruth, tiles_df
  143. )
  144. create_tile_mask_geotiffs(
  145. tiles_df_train,
  146. workers,
  147. groundtruth_df=groundtruth_df,
  148. crs=crs,
  149. inpath=indir,
  150. outpath=outdir,
  151. simple=simple,
  152. )
  153. def main():
  154. parser = argparse.ArgumentParser()
  155. parser.add_argument("indir", type=Path)
  156. parser.add_argument("outdir", type=Path)
  157. parser.add_argument("shpfile", type=Path)
  158. num_cores = psutil.cpu_count(logical=False)
  159. parser.add_argument(
  160. "--workers",
  161. dest="workers",
  162. type=int,
  163. default=num_cores,
  164. help="number of workers for parallel execution [def: %(default)s]",
  165. )
  166. parser.add_argument(
  167. "--simple",
  168. dest="simple",
  169. default=False,
  170. action="store_true",
  171. help="use just the geometry of the shapefile (no classes)",
  172. )
  173. args = parser.parse_args()
  174. Path(args.outdir).mkdir(parents=True, exist_ok=True)
  175. create_masks(
  176. args.indir,
  177. args.outdir,
  178. args.shpfile,
  179. args.workers,
  180. args.simple,
  181. )
  182. if __name__ == "__main__":
  183. main()
Tip!

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

Comments

Loading...