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

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

Comments

Loading...