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 13 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
  1. import os
  2. import unittest
  3. from pathlib import Path
  4. import torch
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. from matplotlib.colors import ListedColormap
  8. from albumentations import Compose, HorizontalFlip, InvertImg
  9. from super_gradients.training.datasets import Cifar10, Cifar100, ImageNetDataset, COCODetectionDataset, CoCoSegmentationDataSet, COCOPoseEstimationDataset
  10. from super_gradients.training.utils.visualization.pose_estimation import PoseVisualization
  11. from super_gradients.training.datasets.data_formats.bbox_formats.xywh import xywh_to_xyxy
  12. from super_gradients.training.datasets.depth_estimation_datasets import NYUv2DepthEstimationDataset
  13. def visualize_image(image):
  14. """
  15. Visualize the input image.
  16. :param image: torch.Tensor representing the input image with values between 0 and 1. Shape: (C, H, W).
  17. """
  18. # Convert torch tensor to numpy array
  19. if isinstance(image, torch.Tensor):
  20. image = image.permute(1, 2, 0).cpu().numpy() # Change shape from (C, H, W) to (H, W, C)
  21. # Display the image
  22. plt.imshow(image)
  23. plt.axis("off")
  24. plt.show()
  25. def visualize_mask(mask, num_classes=None, class_colors=None):
  26. """
  27. Visualize the segmentation mask.
  28. :param mask: torch.Tensor representing the segmentation mask with class indices. Shape: (H, W).
  29. :param num_classes: Number of classes in the segmentation mask.
  30. :param class_colors: A dictionary mapping class indices to RGB color values.
  31. """
  32. # Convert torch tensor to numpy array
  33. mask_np = mask.cpu().numpy()
  34. # Determine the number of classes
  35. if num_classes is None:
  36. num_classes = int(torch.max(mask) + 1)
  37. # Define default class colors if not provided
  38. if class_colors is None:
  39. class_colors = {i: plt.cm.tab10(i)[:-1] for i in range(num_classes)} # Exclude the alpha channel
  40. # Create a colormap for visualization
  41. colormap = ListedColormap([class_colors[i] for i in range(num_classes)])
  42. # Display the mask
  43. plt.imshow(mask_np, cmap=colormap)
  44. plt.colorbar(ticks=range(num_classes))
  45. plt.axis("off")
  46. plt.show()
  47. class AlbumentationsIntegrationTest(unittest.TestCase):
  48. def _apply_aug(self, img_no_aug):
  49. pipe = Compose(transforms=[HorizontalFlip(p=1.0), InvertImg(p=1.0)])
  50. img_no_aug_transformed = pipe(image=np.array(img_no_aug))["image"]
  51. return img_no_aug_transformed
  52. def test_cifar10_albumentations_integration(self):
  53. ds_no_aug = Cifar10(root="./data/cifar10", train=True, download=True)
  54. img_no_aug, _ = ds_no_aug.__getitem__(0)
  55. ds = Cifar10(
  56. root="./data/cifar10",
  57. train=True,
  58. download=True,
  59. transforms={"Albumentations": {"Compose": {"transforms": [{"HorizontalFlip": {"p": 1.0}}, {"InvertImg": {"p": 1.0}}]}}},
  60. )
  61. img_aug, _ = ds.__getitem__(0)
  62. img_no_aug_transformed = self._apply_aug(img_no_aug)
  63. self.assertTrue(np.allclose(img_no_aug_transformed, img_aug))
  64. def test_cifar100_albumentations_integration(self):
  65. ds_no_aug = Cifar100(root="./data/cifar100", train=True, download=True)
  66. img_no_aug, _ = ds_no_aug.__getitem__(0)
  67. ds = Cifar100(
  68. root="./data/cifar100",
  69. train=True,
  70. download=True,
  71. transforms={"Albumentations": {"Compose": {"transforms": [{"HorizontalFlip": {"p": 1}}, {"InvertImg": {"p": 1.0}}]}}},
  72. )
  73. img_aug, _ = ds.__getitem__(0)
  74. img_no_aug_transformed = self._apply_aug(img_no_aug)
  75. self.assertTrue(np.allclose(img_no_aug_transformed, img_aug))
  76. def test_imagenet_albumentations_integration(self):
  77. ds_no_aug = ImageNetDataset(root="/data/Imagenet/val")
  78. img_no_aug, _ = ds_no_aug.__getitem__(0)
  79. ds = ImageNetDataset(
  80. root="/data/Imagenet/val", transforms={"Albumentations": {"Compose": {"transforms": [{"HorizontalFlip": {"p": 1}}, {"InvertImg": {"p": 1.0}}]}}}
  81. )
  82. img_aug, _ = ds.__getitem__(0)
  83. img_no_aug_transformed = self._apply_aug(img_no_aug)
  84. self.assertTrue(np.allclose(img_no_aug_transformed, img_aug))
  85. def test_coco_albumentations_integration(self):
  86. mini_coco_data_dir = str(Path(__file__).parent.parent / "data" / "tinycoco")
  87. train_dataset_params = {
  88. "data_dir": mini_coco_data_dir,
  89. "subdir": "images/train2017",
  90. "json_file": "instances_train2017.json",
  91. "cache": False,
  92. "input_dim": [512, 512],
  93. "transforms": [
  94. {"DetectionMosaic": {"input_dim": [640, 640], "prob": 1.0}},
  95. {
  96. "Albumentations": {
  97. "Compose": {
  98. "transforms": [{"HorizontalFlip": {"p": 0.5}}, {"RandomBrightnessContrast": {"p": 0.5}}],
  99. "bbox_params": {"min_area": 1, "min_visibility": 0, "min_width": 0, "min_height": 0, "check_each_transform": True},
  100. },
  101. }
  102. },
  103. {
  104. "DetectionMixup": {
  105. "input_dim": [640, 640],
  106. "mixup_scale": [0.5, 1.5],
  107. # random rescale range for the additional sample in mixup
  108. "prob": 1.0, # probability to apply per-sample mixup
  109. "flip_prob": 0.5,
  110. }
  111. },
  112. ],
  113. }
  114. ds = COCODetectionDataset(**train_dataset_params)
  115. ds.plot()
  116. def test_coco_segmentation_albumentations_intergration(self):
  117. mini_coco_data_dir = str(Path(__file__).parent.parent / "data" / "tinycoco")
  118. ds = CoCoSegmentationDataSet(
  119. root_dir=mini_coco_data_dir,
  120. list_file="instances_val2017.json",
  121. samples_sub_directory="images/val2017",
  122. targets_sub_directory="annotations",
  123. transforms=[
  124. {"SegRescale": {"short_size": 512}},
  125. {
  126. "SegCropImageAndMask": {"crop_size": 256, "mode": "center"},
  127. },
  128. {
  129. "Albumentations": {
  130. "Compose": {"transforms": [{"HorizontalFlip": {"p": 0.5}}, {"RandomBrightnessContrast": {"p": 0.5}}]},
  131. }
  132. },
  133. "SegConvertToTensor",
  134. ],
  135. )
  136. image, mask = ds[3]
  137. visualize_image(image)
  138. visualize_mask(mask, num_classes=len(ds.classes))
  139. def test_depth_estimation_albumentations_integration(self):
  140. mini_nyuv2_data_dir = str(Path(__file__).parent.parent / "data" / "nyu2_mini_test")
  141. mini_nyuv2_df_path = os.path.join(mini_nyuv2_data_dir, "nyu2_mini_test.csv")
  142. transforms = [
  143. {
  144. "Albumentations": {
  145. "Compose": {"transforms": [{"Rotate": {"p": 1.0, "limit": 15}}, {"RandomBrightnessContrast": {"p": 1.0}}]},
  146. }
  147. }
  148. ]
  149. dataset = NYUv2DepthEstimationDataset(root=mini_nyuv2_data_dir, df_path=mini_nyuv2_df_path, transforms=transforms)
  150. dataset.plot(max_samples_per_plot=8)
  151. def test_coco_pose_albumentations_intergration(self):
  152. mini_coco_data_dir = str(Path(__file__).parent.parent / "data" / "pose_minicoco")
  153. edge_links = [
  154. [0, 1],
  155. [0, 2],
  156. [1, 2],
  157. [1, 3],
  158. [2, 4],
  159. [3, 5],
  160. [4, 6],
  161. [5, 6],
  162. [5, 7],
  163. [5, 11],
  164. [6, 8],
  165. [6, 12],
  166. [7, 9],
  167. [8, 10],
  168. [11, 12],
  169. [11, 13],
  170. [12, 14],
  171. [13, 15],
  172. [14, 16],
  173. ]
  174. edge_colors = [
  175. [214, 39, 40], # Nose -> LeftEye
  176. [148, 103, 189], # Nose -> RightEye
  177. [44, 160, 44], # LeftEye -> RightEye
  178. [140, 86, 75], # LeftEye -> LeftEar
  179. [227, 119, 194], # RightEye -> RightEar
  180. [127, 127, 127], # LeftEar -> LeftShoulder
  181. [188, 189, 34], # RightEar -> RightShoulder
  182. [127, 127, 127], # Shoulders
  183. [188, 189, 34], # LeftShoulder -> LeftElbow
  184. [140, 86, 75], # LeftTorso
  185. [23, 190, 207], # RightShoulder -> RightElbow
  186. [227, 119, 194], # RightTorso
  187. [31, 119, 180], # LeftElbow -> LeftArm
  188. [255, 127, 14], # RightElbow -> RightArm
  189. [148, 103, 189], # Waist
  190. [255, 127, 14], # Left Hip -> Left Knee
  191. [214, 39, 40], # Right Hip -> Right Knee
  192. [31, 119, 180], # Left Knee -> Left Ankle
  193. [44, 160, 44], # Right Knee -> Right Ankle
  194. ]
  195. keypoint_colors = [
  196. [148, 103, 189],
  197. [31, 119, 180],
  198. [148, 103, 189],
  199. [31, 119, 180],
  200. [148, 103, 189],
  201. [31, 119, 180],
  202. [148, 103, 189],
  203. [31, 119, 180],
  204. [148, 103, 189],
  205. [31, 119, 180],
  206. [148, 103, 189],
  207. [31, 119, 180],
  208. [148, 103, 189],
  209. [31, 119, 180],
  210. [148, 103, 189],
  211. [31, 119, 180],
  212. [148, 103, 189],
  213. ]
  214. from super_gradients.training.transforms import KeypointsRescale, KeypointsPadIfNeeded
  215. transforms = [
  216. KeypointsRescale(height=320, width=640),
  217. {
  218. "Albumentations": {
  219. "Compose": {
  220. "transforms": [{"RandomBrightnessContrast": {"p": 1}}, {"RandomCrop": dict(width=300, height=320)}],
  221. "bbox_params": {
  222. "min_area": 1,
  223. "min_visibility": 0,
  224. "min_width": 0,
  225. "min_height": 0,
  226. "check_each_transform": True,
  227. },
  228. "keypoint_params": {},
  229. },
  230. }
  231. },
  232. KeypointsPadIfNeeded(min_height=350, min_width=350, image_pad_value=0, mask_pad_value=0, padding_mode="center"),
  233. ]
  234. ds = COCOPoseEstimationDataset(
  235. data_dir=mini_coco_data_dir,
  236. images_dir="images/val2017",
  237. json_file="annotations/person_keypoints_val2017.json",
  238. include_empty_samples=True,
  239. edge_links=edge_links,
  240. edge_colors=edge_colors,
  241. keypoint_colors=keypoint_colors,
  242. transforms=transforms,
  243. )
  244. sample = next(iter(ds))
  245. bboxes_xyxy = xywh_to_xyxy(bboxes=np.array(sample.bboxes_xywh), image_shape=sample.image.shape)
  246. image_with_keypoints = PoseVisualization.draw_poses(
  247. image=np.array(sample.image),
  248. poses=sample.joints,
  249. boxes=bboxes_xyxy,
  250. scores=None,
  251. is_crowd=sample.is_crowd,
  252. edge_links=edge_links,
  253. edge_colors=edge_colors,
  254. keypoint_colors=keypoint_colors,
  255. show_keypoint_confidence=False,
  256. joint_thickness=None,
  257. box_thickness=None,
  258. keypoint_radius=None,
  259. )
  260. visualize_image(image=image_with_keypoints)
  261. # Make sure we raise an error when using unsupported transforms
  262. with self.assertRaises(TypeError):
  263. transforms = [
  264. KeypointsRescale(height=320, width=640),
  265. {
  266. "Albumentations": {
  267. "Compose": {
  268. "transforms": [{"HorizontalFlip": {"p": 1}}],
  269. "bbox_params": {
  270. "min_area": 1,
  271. "min_visibility": 0,
  272. "min_width": 0,
  273. "min_height": 0,
  274. "check_each_transform": True,
  275. },
  276. "keypoint_params": {},
  277. },
  278. }
  279. },
  280. KeypointsPadIfNeeded(min_height=350, min_width=350, image_pad_value=0, mask_pad_value=0, padding_mode="center"),
  281. ]
  282. unsupported_ds = COCOPoseEstimationDataset(
  283. data_dir=mini_coco_data_dir,
  284. images_dir="images/val2017",
  285. json_file="annotations/person_keypoints_val2017.json",
  286. include_empty_samples=True,
  287. edge_links=edge_links,
  288. edge_colors=edge_colors,
  289. keypoint_colors=keypoint_colors,
  290. transforms=transforms,
  291. )
  292. _ = next(iter(unsupported_ds))
  293. if __name__ == "__main__":
  294. unittest.main()
Tip!

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

Comments

Loading...