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

segmentation_utils.py 11 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
  1. import random
  2. from PIL import Image, ImageOps, ImageFilter
  3. import collections
  4. from typing import Optional, Union, Tuple, List
  5. import math
  6. import torchvision.transforms as transforms
  7. # FIXME: REFACTOR AUGMENTATIONS, CONSIDER USING A MORE EFFICIENT LIBRARIES SUCH AS, IMGAUG, DALI ETC.
  8. image_resample = Image.BILINEAR
  9. mask_resample = Image.NEAREST
  10. class RandomFlip:
  11. """
  12. Randomly flips the image and mask (synchronously) with probability 'prob'.
  13. """
  14. def __init__(self, prob: float = 0.5):
  15. assert 0. <= prob <= 1., f"Probability value must be between 0 and 1, found {prob}"
  16. self.prob = prob
  17. def __call__(self, sample: dict):
  18. image = sample["image"]
  19. mask = sample["mask"]
  20. if random.random() < self.prob:
  21. image = image.transpose(Image.FLIP_LEFT_RIGHT)
  22. mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
  23. sample["image"] = image
  24. sample["mask"] = mask
  25. return sample
  26. class Rescale:
  27. """
  28. Rescales the image and mask (synchronously) while preserving aspect ratio.
  29. The rescaling can be done according to scale_factor, short_size or long_size.
  30. If more than one argument is given, the rescaling mode is determined by this order: scale_factor, then short_size,
  31. then long_size.
  32. Args:
  33. scale_factor: rescaling is done by multiplying input size by scale_factor:
  34. out_size = (scale_factor * w, scale_factor * h)
  35. short_size: rescaling is done by determining the scale factor by the ratio short_size / min(h, w).
  36. long_size: rescaling is done by determining the scale factor by the ratio long_size / max(h, w).
  37. """
  38. def __init__(self,
  39. scale_factor: Optional[float] = None,
  40. short_size: Optional[int] = None,
  41. long_size: Optional[int] = None):
  42. self.scale_factor = scale_factor
  43. self.short_size = short_size
  44. self.long_size = long_size
  45. self.check_valid_arguments()
  46. def __call__(self, sample: dict):
  47. image = sample["image"]
  48. mask = sample["mask"]
  49. w, h = image.size
  50. if self.scale_factor is not None:
  51. scale = self.scale_factor
  52. elif self.short_size is not None:
  53. short_size = min(w, h)
  54. scale = self.short_size / short_size
  55. else:
  56. long_size = max(w, h)
  57. scale = self.long_size / long_size
  58. out_size = int(scale * w), int(scale * h)
  59. image = image.resize(out_size, image_resample)
  60. mask = mask.resize(out_size, mask_resample)
  61. sample["image"] = image
  62. sample["mask"] = mask
  63. return sample
  64. def check_valid_arguments(self):
  65. if self.scale_factor is None and self.short_size is None and self.long_size is None:
  66. raise ValueError("Must assign one rescale argument: scale_factor, short_size or long_size")
  67. if self.scale_factor is not None and self.scale_factor <= 0:
  68. raise ValueError(f"Scale factor must be a positive number, found: {self.scale_factor}")
  69. if self.short_size is not None and self.short_size <= 0:
  70. raise ValueError(f"Short size must be a positive number, found: {self.short_size}")
  71. if self.long_size is not None and self.long_size <= 0:
  72. raise ValueError(f"Long size must be a positive number, found: {self.long_size}")
  73. class RandomRescale:
  74. """
  75. Random rescale the image and mask (synchronously) while preserving aspect ratio.
  76. Scale factor is randomly picked between scales [min, max]
  77. Args:
  78. scales: scale range tuple (min, max), if scales is a float range will be defined as (1, scales) if scales > 1,
  79. otherwise (scales, 1). must be a positive number.
  80. """
  81. def __init__(self, scales: Union[float, Tuple, List] = (0.5, 2.0)):
  82. self.scales = scales
  83. self.check_valid_arguments()
  84. def __call__(self, sample: dict):
  85. image = sample["image"]
  86. mask = sample["mask"]
  87. w, h = image.size
  88. scale = random.uniform(self.scales[0], self.scales[1])
  89. out_size = int(scale * w), int(scale * h)
  90. image = image.resize(out_size, image_resample)
  91. mask = mask.resize(out_size, mask_resample)
  92. sample["image"] = image
  93. sample["mask"] = mask
  94. return sample
  95. def check_valid_arguments(self):
  96. """
  97. Check the scale values are valid. if order is wrong, flip the order and return the right scale values.
  98. """
  99. if not isinstance(self.scales, collections.abc.Iterable):
  100. if self.scales <= 1:
  101. self.scales = (self.scales, 1)
  102. else:
  103. self.scales = (1, self.scales)
  104. if self.scales[0] < 0 or self.scales[1] < 0:
  105. raise ValueError(f"RandomRescale scale values must be positive numbers, found: {self.scales}")
  106. if self.scales[0] > self.scales[1]:
  107. self.scales = (self.scales[1], self.scales[0])
  108. return self.scales
  109. class RandomRotate:
  110. """
  111. Randomly rotates image and mask (synchronously) between 'min_deg' and 'max_deg'.
  112. """
  113. def __init__(self, min_deg: float = -10, max_deg: float = 10, fill_mask: int = 0, fill_image: Union[int, Tuple, List] = 0):
  114. self.min_deg = min_deg
  115. self.max_deg = max_deg
  116. self.fill_mask = fill_mask
  117. # grey color in RGB mode
  118. self.fill_image = (fill_image, fill_image, fill_image)
  119. self.check_valid_arguments()
  120. def __call__(self, sample: dict):
  121. image = sample["image"]
  122. mask = sample["mask"]
  123. deg = random.uniform(self.min_deg, self.max_deg)
  124. image = image.rotate(deg, resample=image_resample, fillcolor=self.fill_image)
  125. mask = mask.rotate(deg, resample=mask_resample, fillcolor=self.fill_mask)
  126. sample["image"] = image
  127. sample["mask"] = mask
  128. return sample
  129. def check_valid_arguments(self):
  130. self.fill_mask, self.fill_image = _validate_fill_values_arguments(self.fill_mask, self.fill_image)
  131. class CropImageAndMask:
  132. """
  133. Crops image and mask (synchronously).
  134. In "center" mode a center crop is performed while, in "random" mode the drop will be positioned around
  135. random coordinates.
  136. """
  137. def __init__(self, crop_size: Union[float, Tuple, List], mode: str):
  138. """
  139. :param crop_size: tuple of (width, height) for the final crop size, if is scalar size is a
  140. square (crop_size, crop_size)
  141. :param mode: how to choose the center of the crop, 'center' for the center of the input image,
  142. 'random' center the point is chosen randomally
  143. """
  144. self.crop_size = crop_size
  145. self.mode = mode
  146. self.check_valid_arguments()
  147. def __call__(self, sample: dict):
  148. image = sample["image"]
  149. mask = sample["mask"]
  150. w, h = image.size
  151. if self.mode == "random":
  152. x1 = random.randint(0, w - self.crop_size[0])
  153. y1 = random.randint(0, h - self.crop_size[1])
  154. else:
  155. x1 = int(round((w - self.crop_size[0]) / 2.))
  156. y1 = int(round((h - self.crop_size[1]) / 2.))
  157. image = image.crop((x1, y1, x1 + self.crop_size[0], y1 + self.crop_size[1]))
  158. mask = mask.crop((x1, y1, x1 + self.crop_size[0], y1 + self.crop_size[1]))
  159. sample["image"] = image
  160. sample["mask"] = mask
  161. return sample
  162. def check_valid_arguments(self):
  163. if self.mode not in ["center", "random"]:
  164. raise ValueError(f"Unsupported mode: found: {self.mode}, expected: 'center' or 'random'")
  165. if not isinstance(self.crop_size, collections.abc.Iterable):
  166. self.crop_size = (self.crop_size, self.crop_size)
  167. if self.crop_size[0] <= 0 or self.crop_size[1] <= 0:
  168. raise ValueError(f"Crop size must be positive numbers, found: {self.crop_size}")
  169. class RandomGaussianBlur:
  170. """
  171. Adds random Gaussian Blur to image with probability 'prob'.
  172. """
  173. def __init__(self, prob: float = 0.5):
  174. assert 0. <= prob <= 1., "Probability value must be between 0 and 1"
  175. self.prob = prob
  176. def __call__(self, sample: dict):
  177. image = sample["image"]
  178. mask = sample["mask"]
  179. if random.random() < self.prob:
  180. image = image.filter(ImageFilter.GaussianBlur(
  181. radius=random.random()))
  182. sample["image"] = image
  183. sample["mask"] = mask
  184. return sample
  185. class PadShortToCropSize:
  186. """
  187. Pads image to 'crop_size'.
  188. Should be called only after "Rescale" or "RandomRescale" in augmentations pipeline.
  189. """
  190. def __init__(self, crop_size: Union[float, Tuple, List], fill_mask: int = 0, fill_image: Union[int, Tuple, List] = 0):
  191. """
  192. :param crop_size: tuple of (width, height) for the final crop size, if is scalar size is a
  193. square (crop_size, crop_size)
  194. :param fill_mask: value to fill mask labels background.
  195. :param fill_image: grey value to fill image padded background.
  196. """
  197. # CHECK IF CROP SIZE IS A ITERABLE OR SCALAR
  198. self.crop_size = crop_size
  199. self.fill_mask = fill_mask
  200. self.fill_image = fill_image
  201. self.check_valid_arguments()
  202. def __call__(self, sample: dict):
  203. image = sample["image"]
  204. mask = sample["mask"]
  205. w, h = image.size
  206. # pad images from center symmetrically
  207. if w < self.crop_size[0] or h < self.crop_size[1]:
  208. padh = (self.crop_size[1] - h) / 2 if h < self.crop_size[1] else 0
  209. pad_top, pad_bottom = math.ceil(padh), math.floor(padh)
  210. padw = (self.crop_size[0] - w) / 2 if w < self.crop_size[0] else 0
  211. pad_left, pad_right = math.ceil(padw), math.floor(padw)
  212. image = ImageOps.expand(image, border=(pad_left, pad_top, pad_right, pad_bottom), fill=self.fill_image)
  213. mask = ImageOps.expand(mask, border=(pad_left, pad_top, pad_right, pad_bottom), fill=self.fill_mask)
  214. sample["image"] = image
  215. sample["mask"] = mask
  216. return sample
  217. def check_valid_arguments(self):
  218. if not isinstance(self.crop_size, collections.abc.Iterable):
  219. self.crop_size = (self.crop_size, self.crop_size)
  220. if self.crop_size[0] <= 0 or self.crop_size[1] <= 0:
  221. raise ValueError(f"Crop size must be positive numbers, found: {self.crop_size}")
  222. self.fill_mask, self.fill_image = _validate_fill_values_arguments(self.fill_mask, self.fill_image)
  223. class ColorJitterSeg(transforms.ColorJitter):
  224. def __call__(self, sample):
  225. sample["image"] = super(ColorJitterSeg, self).__call__(sample["image"])
  226. return sample
  227. def _validate_fill_values_arguments(fill_mask: int, fill_image: Union[int, Tuple, List]):
  228. if not isinstance(fill_image, collections.abc.Iterable):
  229. # If fill_image is single value, turn to grey color in RGB mode.
  230. fill_image = (fill_image, fill_image, fill_image)
  231. elif len(fill_image) != 3:
  232. raise ValueError(f"fill_image must be an RGB tuple of size equal to 3, found: {fill_image}")
  233. # assert values are integers
  234. if not isinstance(fill_mask, int) or not all(isinstance(x, int) for x in fill_image):
  235. raise ValueError(f"Fill value must be integers,"
  236. f" found: fill_image = {fill_image}, fill_mask = {fill_mask}")
  237. # assert values in range 0-255
  238. if min(fill_image) < 0 or max(fill_image) > 255 or fill_mask < 0 or fill_mask > 255:
  239. raise ValueError(f"Fill value must be a value from 0 to 255,"
  240. f" found: fill_image = {fill_image}, fill_mask = {fill_mask}")
  241. return fill_mask, fill_image
Tip!

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

Comments

Loading...