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

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

Comments

Loading...