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

createdataset.py 15 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
  1. import argparse
  2. import io
  3. import math
  4. import random
  5. import tarfile
  6. import tempfile
  7. from functools import partial, reduce
  8. from pathlib import Path
  9. from typing import Any, Dict, Iterable, List, Optional, Tuple
  10. import psutil
  11. import webdataset as wds
  12. import numpy as np
  13. import pandas as pd
  14. import rioxarray
  15. import xarray as xr
  16. from deadtrees.utils.data_handling import make_blocks_vectorized, split_df
  17. from PIL import Image
  18. from tqdm.contrib.concurrent import process_map
  19. random.seed(42)
  20. Path.ls = lambda x: list(x.iterdir())
  21. SHARDSIZE = 32
  22. OVERSAMPLE_FACTOR = 2 # factor of random samples to dt + ndt samples
  23. """Summary:
  24. This script builds up the final datasets for model training, validation and testing
  25. The final datasets (combo) consists of three parts:
  26. (1) tiles with classified deadtrees (frac > 0)
  27. (2) tiles with non-deadtrees (aka healthy forest tiles, frac = 0)
  28. (3) random other tiles (landuses: urban, arable, water etc., frac unknown, likely 0)
  29. All shards are balanced to contain an equal amount of classified deadtree occurences to
  30. allow a fair use of shards for traingin/ validation/ testing (composition of images should
  31. be fair no matter the use)
  32. Before the final dataset (combo) is created, various (temporary) datasets are created:
  33. (1) train - raw, do not use
  34. (2) train-balanced - balance the amounts of deadpixels (also filter to only include tiles with deadtrees)
  35. (3) train-negsamples - a set of tiles that are guaranteed to contain non-dead trees
  36. (4) train-randomsamples - a set of random other tiles
  37. (X) combo: (2) + (4) [take turns]
  38. """
  39. class Extractor:
  40. """Extract subtiles from rgbn or mask tile"""
  41. def __init__(self, *, tile_size: int = 256, source_dim: int = 2048):
  42. self.tile_size = tile_size
  43. self.source_dim = source_dim
  44. def __call__(self, t: Optional[xr.DataArray], *, n_bands: int):
  45. """Get data from tile, zeropad if necessary"""
  46. # default: all-zero in case no mask file exists
  47. if t is None:
  48. data = np.zeros((n_bands, self.source_dim, self.source_dim), dtype=np.uint8)
  49. else:
  50. data = np.zeros((n_bands, self.source_dim, self.source_dim), dtype=t.dtype)
  51. if (len(t.x) * len(t.y)) != (self.source_dim * self.source_dim):
  52. data[:, 0 : 0 + t.shape[1], 0 : 0 + t.shape[2]] = t.values
  53. else:
  54. data = t.values
  55. return make_blocks_vectorized(data, self.tile_size)
  56. def _split_tile(
  57. image: Path,
  58. mask: Path,
  59. lu: Path,
  60. *,
  61. source_dim: int,
  62. tile_size: int,
  63. format: str,
  64. valid_subtiles: Optional[Iterable[str]] = None,
  65. ) -> List[Tuple[str, bytes, bytes]]:
  66. """Helper func for split_tiles"""
  67. extract = Extractor(tile_size=tile_size, source_dim=source_dim)
  68. n_bands = 4 # RGBN
  69. chunks = {"band": n_bands, "x": tile_size, "y": tile_size}
  70. with rioxarray.open_rasterio(image, chunks=chunks) as t:
  71. subtile_rgbn = extract(t, n_bands=n_bands)
  72. # process (optional) mask data
  73. if mask:
  74. chunks = {"band": n_bands, "x": tile_size, "y": tile_size}
  75. with rioxarray.open_rasterio(mask, chunks=chunks) as t:
  76. subtile_mask = extract(t, n_bands=1)
  77. else:
  78. subtile_mask = extract(None, n_bands=1)
  79. # process (optional) lu data
  80. if lu:
  81. chunks = {"band": n_bands, "x": tile_size, "y": tile_size}
  82. with rioxarray.open_rasterio(lu, chunks=chunks) as t:
  83. subtile_lu = extract(t, n_bands=1)
  84. else:
  85. # NOTE: convert to 1 for lu image (instead of 0 for masks)
  86. # TODO: check if this is the right thing to do in general
  87. subtile_lu = extract(None, n_bands=1) + 1
  88. samples = []
  89. if format == "TIFF":
  90. suffix = "tif"
  91. elif format == "PNG":
  92. suffix = "png"
  93. else:
  94. raise NotImplementedError
  95. for i in range(subtile_rgbn.shape[0]):
  96. subtile_name = f"{image.stem}_{i:03}"
  97. if np.min(subtile_rgbn[i]) != np.max(subtile_rgbn[i]):
  98. im = Image.fromarray(np.rollaxis(subtile_rgbn[i], 0, 3), "RGBA")
  99. im_mask = Image.fromarray(subtile_mask[i].squeeze())
  100. im_lu = Image.fromarray(subtile_lu[i].squeeze())
  101. im_byte_arr = io.BytesIO()
  102. im.save(im_byte_arr, format=format)
  103. im_byte_arr = im_byte_arr.getvalue()
  104. im_mask_byte_arr = io.BytesIO()
  105. im_mask.save(im_mask_byte_arr, format=format)
  106. im_mask_byte_arr = im_mask_byte_arr.getvalue()
  107. im_lu_byte_arr = io.BytesIO()
  108. im_lu.save(im_lu_byte_arr, format=format)
  109. im_lu_byte_arr = im_lu_byte_arr.getvalue()
  110. sample = {
  111. "__key__": subtile_name,
  112. f"rgbn.{suffix}": im_byte_arr,
  113. f"mask.{suffix}": im_mask_byte_arr,
  114. f"lu.{suffix}": im_lu_byte_arr,
  115. "txt": str(
  116. round(
  117. float(np.count_nonzero(subtile_mask[i]))
  118. / (tile_size * tile_size)
  119. * 100,
  120. 2,
  121. )
  122. ),
  123. }
  124. if (valid_subtiles is None) or (subtile_name in valid_subtiles):
  125. samples.append(sample)
  126. return samples
  127. def split_tiles(
  128. images, masks, lus, workers: int, shardpattern: str, **kwargs
  129. ) -> List[Any]:
  130. """Split tile into subtiles in parallel and save them to disk"""
  131. valid_subtiles = kwargs.get("valid_subtiles", None)
  132. stats = []
  133. with wds.ShardWriter(shardpattern, maxcount=SHARDSIZE) as sink:
  134. data = process_map(
  135. partial(_split_tile, **kwargs),
  136. images,
  137. masks,
  138. lus,
  139. max_workers=workers,
  140. chunksize=1,
  141. )
  142. for sample in reduce(lambda z, y: z + y, data):
  143. if sample:
  144. if valid_subtiles:
  145. if sample["__key__"] in valid_subtiles:
  146. sink.write(sample)
  147. stats.append((sample["__key__"], sample["txt"], "1"))
  148. else:
  149. if float(sample["txt"]) > 0:
  150. sink.write(sample)
  151. stats.append((sample["__key__"], sample["txt"], "1"))
  152. else:
  153. # not included in shard
  154. stats.append((sample["__key__"], sample["txt"], "0"))
  155. return stats
  156. def main():
  157. parser = argparse.ArgumentParser()
  158. parser.add_argument("image_dir", type=Path)
  159. parser.add_argument("mask_dir", type=Path)
  160. parser.add_argument("lu_dir", type=Path)
  161. parser.add_argument("outdir", type=Path)
  162. num_cores = psutil.cpu_count(logical=False)
  163. parser.add_argument(
  164. "--workers",
  165. dest="workers",
  166. type=int,
  167. default=num_cores,
  168. help="number of workers for parallel execution [def: %(default)s]",
  169. )
  170. parser.add_argument(
  171. "--source_dim",
  172. dest="source_dim",
  173. type=int,
  174. default=2048,
  175. help="size of input tiles [def: %(default)s]",
  176. )
  177. parser.add_argument(
  178. "--tile_size",
  179. dest="tile_size",
  180. type=int,
  181. default=256,
  182. help="size of final tiles that are then passed to the model [def: %(default)s]",
  183. )
  184. parser.add_argument(
  185. "--format",
  186. dest="format",
  187. type=str,
  188. default="TIFF",
  189. choices=["PNG", "TIFF"],
  190. help="target file format (PNG, TIFF) [def: %(default)s]",
  191. )
  192. parser.add_argument(
  193. "--tmp-dir",
  194. dest="tmp_dir",
  195. type=Path,
  196. default=None,
  197. help="use this location as tmp dir",
  198. )
  199. parser.add_argument(
  200. "--subdir",
  201. dest="sub_dir",
  202. default="train",
  203. help="use this location as sub_dir",
  204. )
  205. parser.add_argument(
  206. "--stats",
  207. dest="stats_file",
  208. type=Path,
  209. default=Path("stats.csv"),
  210. help="use this file to record stats",
  211. )
  212. args = parser.parse_args()
  213. args.outdir.mkdir(parents=True, exist_ok=True)
  214. Path(args.outdir / args.sub_dir).mkdir(parents=True, exist_ok=True)
  215. if args.tmp_dir:
  216. print(f"Using custom tmp dir: {args.tmp_dir}")
  217. Path(args.tmp_dir).mkdir(parents=True, exist_ok=True)
  218. if args.format == "TIFF":
  219. suffix = "tif"
  220. elif args.format == "PNG":
  221. suffix = "png"
  222. else:
  223. raise NotImplementedError
  224. SHUFFLE = True # shuffle subtile order within shards (with fixed seed)
  225. # subtile_stats = split_tiles(train_files)
  226. images = sorted(args.image_dir.glob("*.tif"))
  227. masks = sorted(args.mask_dir.glob("*.tif"))
  228. lus = sorted(args.lu_dir.glob("*.tif"))
  229. image_names = {i.name for i in images}
  230. mask_names = {i.name for i in masks}
  231. lu_names = {i.name for i in lus}
  232. # limit set of images to images that have equivalent mask tiles
  233. train_images = [
  234. i
  235. for i in images
  236. if i.name in image_names.intersection(mask_names).intersection(lu_names)
  237. ]
  238. train_masks = [
  239. i
  240. for i in masks
  241. if i.name in mask_names.intersection(image_names).intersection(lu_names)
  242. ]
  243. train_lus = [
  244. i
  245. for i in lus
  246. if i.name in lu_names.intersection(mask_names).intersection(image_names)
  247. ]
  248. train_images = sorted(train_images)
  249. train_masks = sorted(train_masks)
  250. train_lus = sorted(train_lus)
  251. # print(len(train_images))
  252. # print(len(train_masks))
  253. # exit()
  254. # print(len(train_lus))
  255. cfg = dict(
  256. source_dim=args.source_dim,
  257. tile_size=args.tile_size,
  258. format=args.format,
  259. )
  260. subtile_stats = split_tiles(
  261. train_images,
  262. train_masks,
  263. train_lus,
  264. args.workers,
  265. str(args.outdir / args.sub_dir / "train-%06d.tar"),
  266. **cfg,
  267. )
  268. with open(args.outdir / args.stats_file, "w") as fout:
  269. fout.write("tile,frac,status\n")
  270. for i, (fname, frac, status) in enumerate(subtile_stats):
  271. line = f"{fname},{frac},{status}\n"
  272. fout.write(line)
  273. # rebalance shards so we get similar distributions in all shards
  274. with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmpdir:
  275. print(f"Created a temporary directory: {tmpdir}")
  276. print("Extract source tars")
  277. # untar input
  278. for tf_name in sorted((args.outdir / args.sub_dir).glob("train-00*.tar")):
  279. with tarfile.open(tf_name) as tf:
  280. tf.extractall(tmpdir)
  281. print("Write balanced shards from deadtree samples")
  282. df = pd.read_csv(args.outdir / args.stats_file)
  283. df = df[df.status > 0]
  284. n_valid = len(df)
  285. splits = split_df(df, SHARDSIZE)
  286. # preserve last shard if more than 50% of values are present
  287. if SHARDSIZE // 2 < len(splits[-1]) < SHARDSIZE:
  288. # fill last shard with duplicates (not ideal...)
  289. n_missing = SHARDSIZE - len(splits[-1])
  290. # df_extra = splits[-1].sample(n=n_missing, random_state=42)
  291. splits[-1].extend(np.random.choice(splits[-1], size=n_missing).tolist())
  292. # drop incomplete shards
  293. splits = [x for x in splits if len(x) == SHARDSIZE]
  294. assert len(splits) > 0, "Something went wrong"
  295. for s_cnt, s in enumerate(splits):
  296. with tarfile.open(
  297. args.outdir / args.sub_dir / f"train-balanced-{s_cnt:06}.tar", "w"
  298. ) as dst:
  299. if SHUFFLE:
  300. random.shuffle(s)
  301. for i in s:
  302. dst.add(f"{tmpdir}/{i}.mask.{suffix}", f"{i}.mask.{suffix}")
  303. dst.add(f"{tmpdir}/{i}.lu.{suffix}", f"{i}.lu.{suffix}")
  304. dst.add(f"{tmpdir}/{i}.rgbn.{suffix}", f"{i}.rgbn.{suffix}")
  305. dst.add(f"{tmpdir}/{i}.txt", f"{i}.txt")
  306. # create sets for random tile dataset
  307. # use all subtiles not covered in train
  308. n_subtiles = (args.source_dim // args.tile_size) ** 2
  309. all_subtiles = []
  310. for image_name in image_names:
  311. all_subtiles.extend(
  312. [f"{Path(image_name).stem}_{c:03}" for c in range(n_subtiles)]
  313. )
  314. all_subtiles = set(all_subtiles)
  315. n_samples = n_valid * OVERSAMPLE_FACTOR
  316. random_subtiles = random.sample(
  317. tuple(all_subtiles - set([x[0] for x in subtile_stats if int(x[2]) == 1])),
  318. n_samples,
  319. )
  320. # the necessary tile to process
  321. random_tiles = sorted(list(set([x[:-4] for x in random_subtiles])))
  322. all_images = sorted(args.image_dir.glob("*.tif"))
  323. random_images = [x for x in all_images if x.stem in random_tiles]
  324. print("STATS")
  325. print(len(all_subtiles))
  326. print(len(subtile_stats))
  327. print(len(random_subtiles))
  328. print(len(random_images))
  329. cfg = dict(
  330. source_dim=args.source_dim,
  331. tile_size=args.tile_size,
  332. format=args.format,
  333. valid_subtiles=random_subtiles, # subset data with random selection of subtiles
  334. )
  335. random_images_names = {i.name for i in random_images}
  336. random_lus = [i for i in lus if i.name in random_images_names]
  337. subtile_stats_rnd = split_tiles(
  338. random_images,
  339. [None] * len(random_images),
  340. random_lus,
  341. args.workers,
  342. str(args.outdir / args.sub_dir / "train-randomsamples-%06d.tar"),
  343. **cfg,
  344. )
  345. stats_file_rnd = Path(args.stats_file.stem + "_rnd.csv")
  346. with open(args.outdir / stats_file_rnd, "w") as fout:
  347. fout.write("tile,frac,status\n")
  348. for i, (fname, frac, status) in enumerate(subtile_stats_rnd):
  349. line = f"{fname},{frac},{status}\n"
  350. fout.write(line)
  351. # also create combo dataset
  352. # source A: train-balanced, source B: randomsample
  353. # NOTE: combo dataset has double the default shardsize (2*128), samples alternate between regular and random sample
  354. train_balanced_shards = [
  355. str(x) for x in sorted((args.outdir / args.sub_dir).glob("train-balanced*"))
  356. ]
  357. train_balanced_shards_rnd = [
  358. str(x) for x in sorted((args.outdir / args.sub_dir).glob("train-random*"))
  359. ]
  360. train_balanced_shards_rnd = train_balanced_shards_rnd[: len(train_balanced_shards)]
  361. shardpattern = str(args.outdir / args.sub_dir / "train-combo-%06d.tar")
  362. with wds.ShardWriter(shardpattern, maxcount=SHARDSIZE * 2) as sink:
  363. for shardA, shardB in zip(train_balanced_shards, train_balanced_shards_rnd):
  364. for sA, sB in zip(wds.WebDataset(shardA), wds.WebDataset(shardB)):
  365. sink.write(sA)
  366. sink.write(sB)
  367. # remove everything but train & combo
  368. for filename in (args.outdir / args.sub_dir).glob("train-random*"):
  369. filename.unlink()
  370. for filename in (args.outdir / args.sub_dir).glob("train-balanced*"):
  371. filename.unlink()
  372. for filename in (args.outdir / args.sub_dir).glob("train-0*"):
  373. filename.unlink()
  374. if __name__ == "__main__":
  375. main()
Tip!

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

Comments

Loading...