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

datasets_utils.py 23 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
  1. import copy
  2. import os
  3. from abc import ABC, abstractmethod
  4. from multiprocessing import Value, Lock
  5. import random
  6. import numpy as np
  7. import torch.nn.functional as F
  8. import torchvision
  9. from PIL import Image
  10. import torch
  11. from super_gradients.training.datasets.detection_datasets.detection_dataset import DetectionDataSet
  12. from super_gradients.common.abstractions.abstract_logger import get_logger
  13. from deprecated import deprecated
  14. from matplotlib.patches import Rectangle
  15. from torch.utils.tensorboard import SummaryWriter
  16. from torchvision.datasets import ImageFolder
  17. from super_gradients.training.datasets.auto_augment import rand_augment_transform
  18. from torchvision.transforms import transforms, InterpolationMode, RandomResizedCrop
  19. from tqdm import tqdm
  20. from super_gradients.training.utils.utils import AverageMeter
  21. from super_gradients.training.utils.detection_utils import DetectionVisualization
  22. import matplotlib.pyplot as plt
  23. def get_mean_and_std_torch(data_dir=None, dataloader=None, num_workers=4, RandomResizeSize=224):
  24. """
  25. A function for getting the mean and std of large datasets using pytorch dataloader and gpu functionality.
  26. :param data_dir: String, path to none-library dataset folder. For example "/data/Imagenette" or "/data/TinyImagenet"
  27. :param dataloader: a torch DataLoader, as it would feed the data into the trainer (including transforms etc).
  28. :param RandomResizeSize: Int, the size of the RandomResizeCrop as it appears in the DataInterface (for example, for Imagenet,
  29. this value should be 224).
  30. :return: 2 lists,mean and std, each one of len 3 (1 for each channel)
  31. """
  32. assert data_dir is None or dataloader is None, 'Please provide either path to data folder or DataLoader, not both.'
  33. if dataloader is None:
  34. traindir = os.path.join(os.path.abspath(data_dir), 'train')
  35. trainset = ImageFolder(traindir, transforms.Compose([transforms.RandomResizedCrop(RandomResizeSize),
  36. transforms.RandomHorizontalFlip(),
  37. transforms.ToTensor()]))
  38. dataloader = torch.utils.data.DataLoader(trainset, batch_size=1, num_workers=num_workers)
  39. print(f'Calculating on {len(dataloader.dataset.targets)} Training Samples')
  40. device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
  41. h, w = 0, 0
  42. for batch_idx, (inputs, targets) in enumerate(dataloader):
  43. inputs = inputs.to(device)
  44. if batch_idx == 0:
  45. h, w = inputs.size(2), inputs.size(3)
  46. print(f'Min: {inputs.min()}, Max: {inputs.max()}')
  47. chsum = inputs.sum(dim=(0, 2, 3), keepdim=True)
  48. else:
  49. chsum += inputs.sum(dim=(0, 2, 3), keepdim=True)
  50. mean = chsum / len(trainset) / h / w
  51. print(f'mean: {mean.view(-1)}')
  52. chsum = None
  53. for batch_idx, (inputs, targets) in enumerate(dataloader):
  54. inputs = inputs.to(device)
  55. if batch_idx == 0:
  56. chsum = (inputs - mean).pow(2).sum(dim=(0, 2, 3), keepdim=True)
  57. else:
  58. chsum += (inputs - mean).pow(2).sum(dim=(0, 2, 3), keepdim=True)
  59. std = torch.sqrt(chsum / (len(trainset) * h * w - 1))
  60. print(f'std: {std.view(-1)}')
  61. return mean.view(-1).cpu().numpy().tolist(), std.view(-1).cpu().numpy().tolist()
  62. @deprecated(reason='Use get_mean_and_std_torch() instead. It is faster and more accurate')
  63. def get_mean_and_std(dataset):
  64. '''Compute the mean and std value of dataset.'''
  65. dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=1)
  66. mean = torch.zeros(3)
  67. std = torch.zeros(3)
  68. print('==> Computing mean and std..')
  69. j = 0
  70. for inputs, targets in dataloader:
  71. if j % 10 == 0:
  72. print(j)
  73. j += 1
  74. for i in range(3):
  75. mean[i] += inputs[:, i, :, :].mean()
  76. std[i] += inputs[:, i, :, :].std()
  77. mean.div_(len(dataset))
  78. std.div_(len(dataset))
  79. return mean, std
  80. class AbstractCollateFunction(ABC):
  81. """
  82. A collate function (for torch DataLoader)
  83. """
  84. @abstractmethod
  85. def __call__(self, batch):
  86. pass
  87. class ComposedCollateFunction(AbstractCollateFunction):
  88. """
  89. A function (for torch DataLoader) which executes a sequence of sub collate functions
  90. """
  91. def __init__(self, functions: list):
  92. self.functions = functions
  93. def __call__(self, batch):
  94. for f in self.functions:
  95. batch = f(batch)
  96. return batch
  97. class AtomicInteger:
  98. def __init__(self, value: int = 0):
  99. self._value = Value('i', value)
  100. def __set__(self, instance, value):
  101. self._value.value = value
  102. def __get__(self, instance, owner):
  103. return self._value.value
  104. class MultiScaleCollateFunction(AbstractCollateFunction):
  105. """
  106. a collate function to implement multi-scale data augmentation
  107. according to https://arxiv.org/pdf/1612.08242.pdf
  108. """
  109. _counter = AtomicInteger(0)
  110. _current_size = AtomicInteger(0)
  111. _lock = Lock()
  112. def __init__(self, target_size: int = None, min_image_size: int = None, max_image_size: int = None,
  113. image_size_steps: int = 32,
  114. change_frequency: int = 10):
  115. """
  116. set parameters for the multi-scale collate function
  117. the possible image sizes are in range [min_image_size, max_image_size] in steps of image_size_steps
  118. a new size will be randomly selected every change_frequency calls to the collate_fn()
  119. :param target_size: scales will be [0.66 * target_size, 1.5 * target_size]
  120. :param min_image_size: the minimum size to scale down to (in pixels)
  121. :param max_image_size: the maximum size to scale up to (in pixels)
  122. :param image_size_steps: typically, the stride of the net, which defines the possible image
  123. size multiplications
  124. :param change_frequency:
  125. """
  126. assert target_size is not None or (max_image_size is not None and min_image_size is not None), \
  127. 'either target_size or min_image_size and max_image_size has to be set'
  128. assert target_size is None or max_image_size is None, 'target_size and max_image_size cannot be both defined'
  129. if target_size is not None:
  130. min_image_size = int(0.66 * target_size - ((0.66 * target_size) % image_size_steps) + image_size_steps)
  131. max_image_size = int(1.5 * target_size - ((1.5 * target_size) % image_size_steps))
  132. print('Using multi-scale %g - %g' % (min_image_size, max_image_size))
  133. self.sizes = np.arange(min_image_size, max_image_size + image_size_steps, image_size_steps)
  134. self.image_size_steps = image_size_steps
  135. self.frequency = change_frequency
  136. self._current_size = random.choice(self.sizes)
  137. def __call__(self, batch):
  138. with self._lock:
  139. # Important: this implementation was tailored for a specific input. it assumes the batch is a tuple where
  140. # the images are the first item
  141. assert isinstance(batch, tuple), 'this collate function expects the input to be a tuple (images, labels)'
  142. images = batch[0]
  143. if self._counter % self.frequency == 0:
  144. self._current_size = random.choice(self.sizes)
  145. self._counter += 1
  146. assert images.shape[2] % self.image_size_steps == 0 and images.shape[3] % self.image_size_steps == 0, \
  147. 'images sized not divisible by %d. (resize images before calling multi_scale)' % self.image_size_steps
  148. if self._current_size != max(images.shape[2:]):
  149. ratio = float(self._current_size) / max(images.shape[2:])
  150. new_size = (int(round(images.shape[2] * ratio)), int(round(images.shape[3] * ratio)))
  151. images = F.interpolate(images, size=new_size, mode='bilinear', align_corners=False)
  152. return images, batch[1]
  153. _pil_interpolation_to_str = {
  154. Image.NEAREST: 'PIL.Image.NEAREST',
  155. Image.BILINEAR: 'PIL.Image.BILINEAR',
  156. Image.BICUBIC: 'PIL.Image.BICUBIC',
  157. Image.LANCZOS: 'PIL.Image.LANCZOS',
  158. Image.HAMMING: 'PIL.Image.HAMMING',
  159. Image.BOX: 'PIL.Image.BOX',
  160. }
  161. def _pil_interp(method):
  162. if method == 'bicubic':
  163. return InterpolationMode.BICUBIC
  164. elif method == 'lanczos':
  165. return InterpolationMode.LANCZOS
  166. elif method == 'hamming':
  167. return InterpolationMode.HAMMING
  168. elif method == 'nearest':
  169. return InterpolationMode.NEAREST
  170. elif method == 'bilinear':
  171. return InterpolationMode.BILINEAR
  172. elif method == 'box':
  173. return InterpolationMode.BOX
  174. else:
  175. raise ValueError("interpolation type must be one of ['bilinear', 'bicubic', 'lanczos', 'hamming', "
  176. "'nearest', 'box'] for explicit interpolation type, or 'random' for random")
  177. _RANDOM_INTERPOLATION = (InterpolationMode.BILINEAR, InterpolationMode.BICUBIC)
  178. class RandomResizedCropAndInterpolation(RandomResizedCrop):
  179. """
  180. Crop the given PIL Image to random size and aspect ratio with explicitly chosen or random interpolation.
  181. A crop of random size (default: of 0.08 to 1.0) of the original size and a random
  182. aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
  183. is finally resized to given size.
  184. This is popularly used to train the Inception networks.
  185. Args:
  186. size: expected output size of each edge
  187. scale: range of size of the origin size cropped
  188. ratio: range of aspect ratio of the origin aspect ratio cropped
  189. interpolation: Default: PIL.Image.BILINEAR
  190. """
  191. def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.),
  192. interpolation='default'):
  193. super(RandomResizedCropAndInterpolation, self).__init__(size=size, scale=scale, ratio=ratio, interpolation=interpolation)
  194. if interpolation == 'random':
  195. self.interpolation = _RANDOM_INTERPOLATION
  196. elif interpolation == 'default':
  197. self.interpolation = InterpolationMode.BILINEAR
  198. else:
  199. self.interpolation = _pil_interp(interpolation)
  200. def forward(self, img):
  201. """
  202. Args:
  203. img (PIL Image): Image to be cropped and resized.
  204. Returns:
  205. PIL Image: Randomly cropped and resized image.
  206. """
  207. i, j, h, w = self.get_params(img, self.scale, self.ratio)
  208. if isinstance(self.interpolation, (tuple, list)):
  209. interpolation = random.choice(self.interpolation)
  210. else:
  211. interpolation = self.interpolation
  212. return torchvision.transforms.functional.resized_crop(img, i, j, h, w, self.size, interpolation)
  213. def __repr__(self):
  214. if isinstance(self.interpolation, (tuple, list)):
  215. interpolate_str = ' '.join([_pil_interpolation_to_str[x] for x in self.interpolation])
  216. else:
  217. interpolate_str = _pil_interpolation_to_str[self.interpolation]
  218. format_string = self.__class__.__name__ + '(size={0}'.format(self.size)
  219. format_string += ', scale={0}'.format(tuple(round(s, 4) for s in self.scale))
  220. format_string += ', ratio={0}'.format(tuple(round(r, 4) for r in self.ratio))
  221. format_string += ', interpolation={0})'.format(interpolate_str)
  222. return format_string
  223. STAT_LOGGER_FONT_SIZE = 15
  224. class DatasetStatisticsTensorboardLogger:
  225. logger = get_logger(__name__)
  226. DEFAULT_SUMMARY_PARAMS = {
  227. 'sample_images': 32, # by default, 32 images will be sampled from each dataset
  228. 'plot_class_distribution': True,
  229. 'plot_box_size_distribution': True,
  230. 'plot_anchors_coverage': True,
  231. 'max_batches': 30
  232. }
  233. def __init__(self, writer: SummaryWriter, summary_params: dict = DEFAULT_SUMMARY_PARAMS):
  234. self.writer = writer
  235. self.summary_params = {**DatasetStatisticsTensorboardLogger.DEFAULT_SUMMARY_PARAMS, **summary_params}
  236. def analyze(self, data_loader: torch.utils.data.DataLoader, dataset_params: dict, title: str, anchors: list = None):
  237. """
  238. :param data_loader: the dataset data loader
  239. :param dataset_params: the dataset parameters
  240. :param title: the title for this dataset (i.e. Coco 2017 test set)
  241. :param anchors: the list of anchors used by the model. applicable only for detection datasets
  242. """
  243. if isinstance(data_loader.dataset, DetectionDataSet):
  244. self._analyze_detection(data_loader=data_loader, dataset_params=dataset_params, title=title, anchors=anchors)
  245. else:
  246. DatasetStatisticsTensorboardLogger.logger.warning('only DetectionDataSet are currently supported')
  247. def _analyze_detection(self, data_loader, dataset_params, title, anchors=None):
  248. """
  249. Analyze a detection dataset
  250. :param data_loader: the dataset data loader
  251. :param dataset_params: the dataset parameters
  252. :param title: the title for this dataset (i.e. Coco 2017 test set)
  253. :param anchors: the list of anchors used by the model. if not provided, anchors coverage will not be analyzed
  254. """
  255. try:
  256. color_mean = AverageMeter()
  257. color_std = AverageMeter()
  258. all_labels = []
  259. for i, (images, labels) in enumerate(tqdm(data_loader)):
  260. if i >= self.summary_params['max_batches'] > 0:
  261. break
  262. if i == 0:
  263. if images.shape[0] > self.summary_params['sample_images']:
  264. samples = images[:self.summary_params['sample_images']]
  265. else:
  266. samples = images
  267. pred = [torch.zeros(size=(0, 6)) for _ in range(len(samples))]
  268. class_names = data_loader.dataset.all_classes_list
  269. result_images = DetectionVisualization.visualize_batch(image_tensor=samples, pred_boxes=pred,
  270. target_boxes=copy.deepcopy(labels),
  271. batch_name=title, class_names=class_names,
  272. box_thickness=1,
  273. gt_alpha=1.0)
  274. self.writer.add_images(tag=f'{title} sample images', img_tensor=np.stack(result_images)
  275. .transpose([0, 3, 1, 2])[:, ::-1, :, :])
  276. all_labels.append(labels)
  277. color_mean.update(torch.mean(images, dim=[0, 2, 3]), 1)
  278. color_std.update(torch.std(images, dim=[0, 2, 3]), 1)
  279. all_labels = torch.cat(all_labels, dim=0)[:, 1:].numpy()
  280. if self.summary_params['plot_class_distribution']:
  281. self._analyze_class_distribution(labels=all_labels, num_classes=dataset_params.num_classes, title=title)
  282. if self.summary_params['plot_box_size_distribution']:
  283. self._analyze_object_size_distribution(labels=all_labels, title=title)
  284. summary = ''
  285. summary += f'dataset size: {len(data_loader)} \n'
  286. summary += f'color mean: {color_mean.average} \n'
  287. summary += f'color std: {color_std.average} \n'
  288. if anchors is not None:
  289. coverage = self._analyze_anchors_coverage(anchors=anchors, image_size=dataset_params.train_image_size,
  290. title=title, labels=all_labels)
  291. summary += f'anchors: {anchors} \n'
  292. summary += f'anchors coverage: {coverage} \n'
  293. self.writer.add_text(tag=f'{title} Statistics', text_string=summary)
  294. self.writer.flush()
  295. except Exception as e:
  296. # any exception is caught here. we dont want the DatasetStatisticsLogger to crash any training
  297. DatasetStatisticsTensorboardLogger.logger.error(f'dataset analysis failed: {e}')
  298. def _analyze_class_distribution(self, labels: list, num_classes: int, title: str):
  299. hist, edges = np.histogram(labels[:, 0], num_classes)
  300. f = plt.figure(figsize=[10, 8])
  301. plt.bar(range(num_classes), hist, width=0.5, color='#0504aa', alpha=0.7)
  302. plt.xlim(-1, num_classes)
  303. plt.grid(axis='y', alpha=0.75)
  304. plt.xlabel('Value', fontsize=STAT_LOGGER_FONT_SIZE)
  305. plt.ylabel('Frequency', fontsize=STAT_LOGGER_FONT_SIZE)
  306. plt.xticks(fontsize=STAT_LOGGER_FONT_SIZE)
  307. plt.yticks(fontsize=STAT_LOGGER_FONT_SIZE)
  308. plt.title(f'{title} class distribution', fontsize=STAT_LOGGER_FONT_SIZE)
  309. self.writer.add_figure(f"{title} class distribution", figure=f)
  310. text_dist = ''
  311. for i, val in enumerate(hist):
  312. text_dist += f'[{i}]: {val}, '
  313. self.writer.add_text(tag=f"{title} class distribution", text_string=text_dist)
  314. def _analyze_object_size_distribution(self, labels: list, title: str):
  315. """
  316. This function will add two plots to the tensorboard.
  317. one is a 2D histogram and the other is a scatter plot. in both cases the X axis is the object width and Y axis
  318. is the object width (both normalized by image size)
  319. :param labels: all the labels of the dataset of the shape [class_label, x_center, y_center, w, h]
  320. :param title: the dataset title
  321. """
  322. # histogram plot
  323. hist, xedges, yedges = np.histogram2d(labels[:, 4], labels[:, 3], 50) # x and y are deliberately switched
  324. fig = plt.figure(figsize=(10, 6))
  325. fig.suptitle(f'{title} boxes w/h distribution')
  326. ax = fig.add_subplot(121)
  327. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  328. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  329. plt.imshow(np.log(hist + 1), interpolation='nearest', origin='lower',
  330. extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
  331. # scatter plot
  332. if len(labels) > 10000:
  333. # we randomly sample just 10000 objects so that the scatter plot will not get too dense
  334. labels = labels[np.random.randint(0, len(labels) - 1, 10000)]
  335. ax = fig.add_subplot(122)
  336. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  337. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  338. plt.scatter(labels[:, 3], labels[:, 4], marker='.')
  339. self.writer.add_figure(tag=f'{title} boxes w/h distribution', figure=fig)
  340. @staticmethod
  341. def _get_rect(w, h):
  342. min_w = w / 4.0
  343. min_h = h / 4.0
  344. return Rectangle((min_w, min_h), w * 4 - min_w, h * 4 - min_h, linewidth=1, edgecolor='b', facecolor='none')
  345. @staticmethod
  346. def _get_score(anchors: np.ndarray, points: np.ndarray, image_size: int):
  347. """
  348. Calculate the ratio (and 1/ratio) between each anchor width and height and each point (representing a possible
  349. object width and height).
  350. i.e. for an anchor with w=10,h=20 the point w=11,h=25 will have the ratios 11/10=1.1 and 25/20=1.25
  351. or 10/11=0.91 and 20/25=0.8 respectively
  352. :param anchors: array of anchors of the shape [2,N]
  353. :param points: array of points of the shape [2,M]
  354. :param image_size the size of the input image
  355. :returns: an array of size [image_size - 1, image_size - 1] where each cell i,j represent the minimum ratio
  356. for that cell (point) from all anchors
  357. """
  358. ratio = anchors[:, :, None] / points[:, ]
  359. inv_ratio = 1 / ratio
  360. min_ratio = 1 - np.minimum(ratio, inv_ratio)
  361. min_ratio = np.max(min_ratio, axis=1)
  362. to_closest_anchor = np.min(min_ratio, axis=0)
  363. to_closest_anchor[to_closest_anchor > 0.75] = 2
  364. return to_closest_anchor.reshape(image_size - 1, -1)
  365. def _analyze_anchors_coverage(self, anchors: list, image_size: int, labels: list, title: str):
  366. """
  367. This function will add anchors coverage plots to the tensorboard.
  368. :param anchors: a list of anchors
  369. :param image_size: the input image size for this training
  370. :param labels: all the labels of the dataset of the shape [class_label, x_center, y_center, w, h]
  371. :param title: the dataset title
  372. """
  373. fig = plt.figure(figsize=(12, 5))
  374. fig.suptitle(f'{title} anchors coverage')
  375. # box style plot
  376. ax = fig.add_subplot(121)
  377. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  378. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  379. ax.set_xlim([0, image_size])
  380. ax.set_ylim([0, image_size])
  381. anchors = np.array(anchors).reshape(-1, 2)
  382. for i in range(len(anchors)):
  383. rect = self._get_rect(anchors[i][0], anchors[i][1])
  384. rect.set_alpha(0.3)
  385. rect.set_facecolor([random.random(), random.random(), random.random(), 0.3])
  386. ax.add_patch(rect)
  387. # distance from anchor plot
  388. ax = fig.add_subplot(122)
  389. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  390. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  391. x = np.arange(1, image_size, 1)
  392. y = np.arange(1, image_size, 1)
  393. xx, yy = np.meshgrid(x, y, sparse=False)
  394. points = np.concatenate([xx.reshape(1, -1), yy.reshape(1, -1)])
  395. color = self._get_score(anchors, points, image_size)
  396. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  397. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  398. plt.imshow(color, interpolation='nearest', origin='lower',
  399. extent=[0, image_size, 0, image_size])
  400. # calculate the coverage for the dataset labels
  401. cover_masks = []
  402. for i in range(len(anchors)):
  403. w_max = (anchors[i][0] / image_size) * 4
  404. w_min = (anchors[i][0] / image_size) * 0.25
  405. h_max = (anchors[i][1] / image_size) * 4
  406. h_min = (anchors[i][1] / image_size) * 0.25
  407. cover_masks.append(np.logical_and(
  408. np.logical_and(np.logical_and(labels[:, 3] < w_max, labels[:, 3] > w_min), labels[:, 4] < h_max),
  409. labels[:, 4] > h_min))
  410. cover_masks = np.stack(cover_masks)
  411. coverage = np.count_nonzero(np.any(cover_masks, axis=0)) / len(labels)
  412. self.writer.add_figure(tag=f'{title} anchors coverage', figure=fig)
  413. return coverage
  414. def get_color_augmentation(rand_augment_config_string: str, color_jitter: tuple, crop_size=224, img_mean=[0.485, 0.456, 0.406]):
  415. """
  416. Returns color augmentation class. As these augmentation cannot work on top one another, only one is returned according to rand_augment_config_string
  417. :param rand_augment_config_string: string which defines the auto augment configurations. If none, color jitter will be returned. For possibile values see auto_augment.py
  418. :param color_jitter: tuple for color jitter value.
  419. :param crop_size: relevant only for auto augment
  420. :param img_mean: relevant only for auto augment
  421. :return: RandAugment transform or ColorJitter
  422. """
  423. if rand_augment_config_string:
  424. auto_augment_params = dict(translate_const=int(crop_size * 0.45),
  425. img_mean=tuple([min(255, round(255 * x)) for x in img_mean]))
  426. color_augmentation = rand_augment_transform(rand_augment_config_string, auto_augment_params)
  427. else: # RandAugment includes colorjitter like augmentations, both cannot be applied together.
  428. color_augmentation = transforms.ColorJitter(*color_jitter)
  429. return color_augmentation
Tip!

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

Comments

Loading...