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

computestats.py 5.0 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
  1. import argparse
  2. import datetime
  3. import io
  4. import itertools
  5. import json
  6. from pathlib import Path
  7. import webdataset as wds
  8. import numpy as np
  9. import pandas as pd
  10. import PIL
  11. import torchvision.transforms as transforms
  12. from deadtrees.utils.data_handling import make_blocks_vectorized
  13. from PIL import Image
  14. from torch.utils.data import DataLoader, Dataset, Subset
  15. from tqdm import tqdm
  16. transform = transforms.Compose(
  17. [
  18. transforms.ToTensor(),
  19. ]
  20. )
  21. class TifDataset(Dataset):
  22. def __init__(self, image_paths, transform=None):
  23. self.image_paths = image_paths
  24. self.transform = transform
  25. def __getitem__(self, index):
  26. image_path = self.image_paths[index]
  27. x = Image.open(image_path)
  28. if self.transform is not None:
  29. x = self.transform(x)
  30. return x
  31. def __len__(self):
  32. return len(self.image_paths)
  33. def image_decoder(data):
  34. with io.BytesIO(data) as stream:
  35. img = PIL.Image.open(stream)
  36. img.load()
  37. img = img.convert("RGBA")
  38. return np.array(img)
  39. def sample_decoder(sample, img_suffix="rgbn.tif"):
  40. """Decode data triplet (image, mask stats) from sharded datastore"""
  41. assert img_suffix in sample, "Wrong image suffix provided"
  42. sample[img_suffix] = image_decoder(sample[img_suffix])
  43. return sample
  44. def main():
  45. parser = argparse.ArgumentParser()
  46. parser.add_argument("datapath", type=Path, nargs="+")
  47. parser.add_argument(
  48. "--frac",
  49. dest="frac",
  50. type=float,
  51. default=1.0,
  52. help="fraction of tiles to consider [range: 0-1, def: %(default)s]",
  53. )
  54. args = parser.parse_args()
  55. np.random.seed(42)
  56. print("Using fixed random seed!")
  57. # constants
  58. tile_size = 256
  59. size = tile_size ** 2
  60. if isinstance(args.datapath, list):
  61. tar_files = sorted(
  62. list(itertools.chain(*[x.glob("*.tar") for x in args.datapath]))
  63. )
  64. tif_files = sorted(
  65. list(itertools.chain(*[x.glob("*.tif") for x in args.datapath]))
  66. )
  67. else:
  68. tar_files = sorted(args.datapath.glob("*.tar"))
  69. tif_files = sorted(args.datapath.glob("*.tif"))
  70. n_files = len(tif_files)
  71. SUBSET = int(round(args.frac * n_files, 0))
  72. selection = np.random.choice(range(n_files), size=SUBSET, replace=False)
  73. if len(tar_files) > len(tif_files):
  74. # webdataset
  75. dataset = (
  76. wds.WebDataset([str(x) for x in tar_files])
  77. .map(sample_decoder)
  78. .rename(image="rgbn.tif", mask="mask.tif", stats="txt")
  79. .map_dict(image=transform)
  80. .to_tuple("image")
  81. )
  82. else:
  83. # plain source tif dataset
  84. dataset = TifDataset(tif_files, transform=transform)
  85. dataset = Subset(dataset, selection)
  86. dataloader = DataLoader(dataset, batch_size=1, num_workers=1, shuffle=False)
  87. mean, std = np.zeros(4), np.zeros(4)
  88. print("\nCalculating STATS")
  89. print("\nCalculating MEAN")
  90. cnt = 0
  91. for i, data in enumerate(tqdm(dataloader)):
  92. data = data.squeeze(0).numpy()
  93. # ignore incomplete tiles for stats
  94. if data.shape[-2] != data.shape[-1]:
  95. continue
  96. # check for empty tile and skip (all values are either 0 or 1 in the first band):
  97. if np.isin(data, [0, 1]).all():
  98. continue
  99. subtiles_rgbn = make_blocks_vectorized(data, tile_size)
  100. for subtile_rgbn in subtiles_rgbn:
  101. if subtile_rgbn[0].min() != subtile_rgbn[0].max():
  102. mean += subtile_rgbn.sum((1, 2)) / size
  103. cnt += 1
  104. mean /= cnt + 1 # i + 1
  105. mean_unsqueezed = np.expand_dims(
  106. np.expand_dims(mean, 1), 2
  107. ) # mean.unsqueeze(1).unsqueeze(2)
  108. print("\nCalculating STD")
  109. cnt = 0
  110. for i, data in enumerate(tqdm(dataloader)):
  111. data = data.squeeze(0).numpy()
  112. # ignore incomplete tiles for stats
  113. if data.shape[-2] != data.shape[-1]:
  114. continue
  115. # check for empty tile and skip (all values are either 0 or 1 in the first band):
  116. if np.isin(data, [0, 1]).all():
  117. continue
  118. subtiles_rgbn = make_blocks_vectorized(data, tile_size)
  119. for subtile_rgbn in subtiles_rgbn:
  120. if subtile_rgbn[0].min() != subtile_rgbn[0].max():
  121. std += ((subtile_rgbn - mean_unsqueezed) ** 2).sum((1, 2)) / size
  122. cnt += 1
  123. std /= cnt + 1
  124. std = np.sqrt(std) # std.sqrt()
  125. df = pd.DataFrame(
  126. {
  127. "band": ["red", "green", "blue", "nir"],
  128. "mean": mean.tolist(),
  129. "std": std.tolist(),
  130. }
  131. )
  132. df = df.set_index("band")
  133. # report
  134. info = {
  135. "sources": [str(x) for x in args.datapath],
  136. "date": str(datetime.datetime.now()),
  137. "frac": args.frac,
  138. "subtiles": cnt,
  139. "results": json.loads(df.to_json(orient="index")),
  140. }
  141. # Serializing json
  142. with open(args.datapath[0].parent / "processed.images.stats.json", "w") as fout:
  143. fout.write(json.dumps(info, indent=4))
  144. if __name__ == "__main__":
  145. main()
Tip!

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

Comments

Loading...