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

albumentations_test.py 6.1 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
  1. import unittest
  2. from pathlib import Path
  3. from super_gradients.training.datasets import Cifar10, Cifar100, ImageNetDataset, COCODetectionDataset, CoCoSegmentationDataSet
  4. from albumentations import Compose, HorizontalFlip, InvertImg
  5. import torch
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. from matplotlib.colors import ListedColormap
  9. def visualize_image(image):
  10. """
  11. Visualize the input image.
  12. :param image: torch.Tensor representing the input image with values between 0 and 1. Shape: (C, H, W).
  13. """
  14. # Convert torch tensor to numpy array
  15. image_np = image.permute(1, 2, 0).cpu().numpy() # Change shape from (C, H, W) to (H, W, C)
  16. # Display the image
  17. plt.imshow(image_np)
  18. plt.axis("off")
  19. plt.show()
  20. def visualize_mask(mask, num_classes=None, class_colors=None):
  21. """
  22. Visualize the segmentation mask.
  23. :param mask: torch.Tensor representing the segmentation mask with class indices. Shape: (H, W).
  24. :param num_classes: Number of classes in the segmentation mask.
  25. :param class_colors: A dictionary mapping class indices to RGB color values.
  26. """
  27. # Convert torch tensor to numpy array
  28. mask_np = mask.cpu().numpy()
  29. # Determine the number of classes
  30. if num_classes is None:
  31. num_classes = int(torch.max(mask) + 1)
  32. # Define default class colors if not provided
  33. if class_colors is None:
  34. class_colors = {i: plt.cm.tab10(i)[:-1] for i in range(num_classes)} # Exclude the alpha channel
  35. # Create a colormap for visualization
  36. colormap = ListedColormap([class_colors[i] for i in range(num_classes)])
  37. # Display the mask
  38. plt.imshow(mask_np, cmap=colormap)
  39. plt.colorbar(ticks=range(num_classes))
  40. plt.axis("off")
  41. plt.show()
  42. class AlbumentationsIntegrationTest(unittest.TestCase):
  43. def _apply_aug(self, img_no_aug):
  44. pipe = Compose(transforms=[HorizontalFlip(p=1.0), InvertImg(p=1.0)])
  45. img_no_aug_transformed = pipe(image=np.array(img_no_aug))["image"]
  46. return img_no_aug_transformed
  47. def test_cifar10_albumentations_integration(self):
  48. ds_no_aug = Cifar10(root="./data/cifar10", train=True, download=True)
  49. img_no_aug, _ = ds_no_aug.__getitem__(0)
  50. ds = Cifar10(
  51. root="./data/cifar10",
  52. train=True,
  53. download=True,
  54. transforms={"Albumentations": {"Compose": {"transforms": [{"HorizontalFlip": {"p": 1.0}}, {"InvertImg": {"p": 1.0}}]}}},
  55. )
  56. img_aug, _ = ds.__getitem__(0)
  57. img_no_aug_transformed = self._apply_aug(img_no_aug)
  58. self.assertTrue(np.allclose(img_no_aug_transformed, img_aug))
  59. def test_cifar100_albumentations_integration(self):
  60. ds_no_aug = Cifar100(root="./data/cifar100", train=True, download=True)
  61. img_no_aug, _ = ds_no_aug.__getitem__(0)
  62. ds = Cifar100(
  63. root="./data/cifar100",
  64. train=True,
  65. download=True,
  66. transforms={"Albumentations": {"Compose": {"transforms": [{"HorizontalFlip": {"p": 1}}, {"InvertImg": {"p": 1.0}}]}}},
  67. )
  68. img_aug, _ = ds.__getitem__(0)
  69. img_no_aug_transformed = self._apply_aug(img_no_aug)
  70. self.assertTrue(np.allclose(img_no_aug_transformed, img_aug))
  71. def test_imagenet_albumentations_integration(self):
  72. ds_no_aug = ImageNetDataset(root="/data/Imagenet/val")
  73. img_no_aug, _ = ds_no_aug.__getitem__(0)
  74. ds = ImageNetDataset(
  75. root="/data/Imagenet/val", transforms={"Albumentations": {"Compose": {"transforms": [{"HorizontalFlip": {"p": 1}}, {"InvertImg": {"p": 1.0}}]}}}
  76. )
  77. img_aug, _ = ds.__getitem__(0)
  78. img_no_aug_transformed = self._apply_aug(img_no_aug)
  79. self.assertTrue(np.allclose(img_no_aug_transformed, img_aug))
  80. def test_coco_albumentations_integration(self):
  81. mini_coco_data_dir = str(Path(__file__).parent.parent / "data" / "tinycoco")
  82. train_dataset_params = {
  83. "data_dir": mini_coco_data_dir,
  84. "subdir": "images/train2017",
  85. "json_file": "instances_train2017.json",
  86. "cache": False,
  87. "input_dim": [512, 512],
  88. "transforms": [
  89. {"DetectionMosaic": {"input_dim": [640, 640], "prob": 1.0}},
  90. {
  91. "Albumentations": {
  92. "Compose": {
  93. "transforms": [{"HorizontalFlip": {"p": 0.5}}, {"RandomBrightnessContrast": {"p": 0.5}}],
  94. "bbox_params": {"min_area": 1, "min_visibility": 0, "min_width": 0, "min_height": 0, "check_each_transform": True},
  95. },
  96. }
  97. },
  98. {
  99. "DetectionMixup": {
  100. "input_dim": [640, 640],
  101. "mixup_scale": [0.5, 1.5],
  102. # random rescale range for the additional sample in mixup
  103. "prob": 1.0, # probability to apply per-sample mixup
  104. "flip_prob": 0.5,
  105. }
  106. },
  107. ],
  108. }
  109. ds = COCODetectionDataset(**train_dataset_params)
  110. ds.plot()
  111. def test_coco_segmentation_albumentations_intergration(self):
  112. mini_coco_data_dir = str(Path(__file__).parent.parent / "data" / "tinycoco")
  113. ds = CoCoSegmentationDataSet(
  114. root_dir=mini_coco_data_dir,
  115. list_file="instances_val2017.json",
  116. samples_sub_directory="images/val2017",
  117. targets_sub_directory="annotations",
  118. transforms=[
  119. {"SegRescale": {"short_size": 512}},
  120. {
  121. "SegCropImageAndMask": {"crop_size": 256, "mode": "center"},
  122. },
  123. {
  124. "Albumentations": {
  125. "Compose": {"transforms": [{"HorizontalFlip": {"p": 0.5}}, {"RandomBrightnessContrast": {"p": 0.5}}]},
  126. }
  127. },
  128. "SegToTensor",
  129. ],
  130. )
  131. image, mask = ds[3]
  132. visualize_image(image)
  133. visualize_mask(mask, num_classes=len(ds.classes))
  134. if __name__ == "__main__":
  135. unittest.main()
Tip!

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

Comments

Loading...