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

#378 Feature/sg 281 add kd notebook

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-281-add_kd_notebook
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
  1. import os
  2. import cv2
  3. import numpy as np
  4. from typing import Union, Callable
  5. import torch
  6. import torch.nn.functional as F
  7. from torchvision.utils import draw_segmentation_masks
  8. # FIXME: REFACTOR AUGMENTATIONS, CONSIDER USING A MORE EFFICIENT LIBRARIES SUCH AS, IMGAUG, DALI ETC.
  9. from super_gradients.training import utils as core_utils
  10. def coco_sub_classes_inclusion_tuples_list():
  11. return [(0, 'background'), (5, 'airplane'), (2, 'bicycle'), (16, 'bird'),
  12. (9, 'boat'),
  13. (44, 'bottle'), (6, 'bus'), (3, 'car'), (17, 'cat'), (62, 'chair'),
  14. (21, 'cow'),
  15. (67, 'dining table'), (18, 'dog'), (19, 'horse'), (4, 'motorcycle'),
  16. (1, 'person'),
  17. (64, 'potted plant'), (20, 'sheep'), (63, 'couch'), (7, 'train'),
  18. (72, 'tv')]
  19. def to_one_hot(target: torch.Tensor, num_classes: int, ignore_index: int = None):
  20. """
  21. Target label to one_hot tensor. labels and ignore_index must be consecutive numbers.
  22. :param target: Class labels long tensor, with shape [N, H, W]
  23. :param num_classes: num of classes in datasets excluding ignore label, this is the output channels of the one hot
  24. result.
  25. :return: one hot tensor with shape [N, num_classes, H, W]
  26. """
  27. num_classes = num_classes if ignore_index is None else num_classes + 1
  28. one_hot = F.one_hot(target, num_classes).permute((0, 3, 1, 2))
  29. if ignore_index is not None:
  30. # remove ignore_index channel
  31. one_hot = torch.cat([one_hot[:, :ignore_index], one_hot[:, ignore_index + 1:]], dim=1)
  32. return one_hot
  33. def reverse_imagenet_preprocessing(im_tensor: torch.Tensor) -> np.ndarray:
  34. """
  35. :param im_tensor: images in a batch after preprocessing for inference, RGB, (B, C, H, W)
  36. :return: images in a batch in cv2 format, BGR, (B, H, W, C)
  37. """
  38. im_np = im_tensor.cpu().numpy()
  39. im_np = im_np[:, ::-1, :, :].transpose(0, 2, 3, 1)
  40. im_np *= np.array([[[.229, .224, .225][::-1]]])
  41. im_np += np.array([[[.485, .456, .406][::-1]]])
  42. im_np *= 255.
  43. return np.ascontiguousarray(im_np, dtype=np.uint8)
  44. class BinarySegmentationVisualization:
  45. @staticmethod
  46. def _visualize_image(image_np: np.ndarray, pred_mask: torch.Tensor, target_mask: torch.Tensor,
  47. image_scale: float, checkpoint_dir: str, image_name: str):
  48. pred_mask = pred_mask.copy()
  49. image_np = torch.from_numpy(np.moveaxis(image_np, -1, 0).astype(np.uint8))
  50. pred_mask = pred_mask[np.newaxis, :, :] > 0.5
  51. target_mask = target_mask[np.newaxis, :, :].astype(bool)
  52. tp_mask = np.logical_and(pred_mask, target_mask)
  53. fp_mask = np.logical_and(pred_mask, np.logical_not(target_mask))
  54. fn_mask = np.logical_and(np.logical_not(pred_mask), target_mask)
  55. overlay = torch.from_numpy(np.concatenate([tp_mask, fp_mask, fn_mask]))
  56. # SWITCH BETWEEN BLUE AND RED IF WE SAVE THE IMAGE ON THE DISC AS OTHERWISE WE CHANGE CHANNEL ORDERING
  57. colors = ['green', 'red', 'blue']
  58. res_image = draw_segmentation_masks(image_np, overlay, colors=colors).detach().numpy()
  59. res_image = np.concatenate([res_image[ch, :, :, np.newaxis] for ch in range(3)], 2)
  60. res_image = cv2.resize(res_image.astype(np.uint8), (0, 0), fx=image_scale, fy=image_scale,
  61. interpolation=cv2.INTER_NEAREST)
  62. if checkpoint_dir is None:
  63. return res_image
  64. else:
  65. cv2.imwrite(os.path.join(checkpoint_dir, str(image_name) + '.jpg'), res_image)
  66. @staticmethod
  67. def visualize_batch(image_tensor: torch.Tensor, pred_mask: torch.Tensor, target_mask: torch.Tensor,
  68. batch_name: Union[int, str], checkpoint_dir: str = None,
  69. undo_preprocessing_func: Callable[[torch.Tensor], np.ndarray] = reverse_imagenet_preprocessing,
  70. image_scale: float = 1.):
  71. """
  72. A helper function to visualize detections predicted by a network:
  73. saves images into a given path with a name that is {batch_name}_{imade_idx_in_the_batch}.jpg, one batch per call.
  74. Colors are generated on the fly: uniformly sampled from color wheel to support all given classes.
  75. :param image_tensor: rgb images, (B, H, W, 3)
  76. :param pred_boxes: boxes after NMS for each image in a batch, each (Num_boxes, 6),
  77. values on dim 1 are: x1, y1, x2, y2, confidence, class
  78. :param target_boxes: (Num_targets, 6), values on dim 1 are: image id in a batch, class, x y w h
  79. (coordinates scaled to [0, 1])
  80. :param batch_name: id of the current batch to use for image naming
  81. :param checkpoint_dir: a path where images with boxes will be saved. if None, the result images will
  82. be returns as a list of numpy image arrays
  83. :param undo_preprocessing_func: a function to convert preprocessed images tensor into a batch of cv2-like images
  84. :param image_scale: scale factor for output image
  85. """
  86. image_np = undo_preprocessing_func(image_tensor.detach())
  87. pred_mask = torch.sigmoid(pred_mask[:, 0, :, :]) # comment out
  88. out_images = []
  89. for i in range(image_np.shape[0]):
  90. preds = pred_mask[i].detach().cpu().numpy()
  91. targets = target_mask[i].detach().cpu().numpy()
  92. image_name = '_'.join([str(batch_name), str(i)])
  93. res_image = BinarySegmentationVisualization._visualize_image(image_np[i], preds, targets, image_scale,
  94. checkpoint_dir, image_name)
  95. if res_image is not None:
  96. out_images.append(res_image)
  97. return out_images
  98. def visualize_batches(dataloader, module, visualization_path, num_batches=1, undo_preprocessing_func=None):
  99. os.makedirs(visualization_path, exist_ok=True)
  100. for batch_i, (imgs, targets) in enumerate(dataloader):
  101. if batch_i == num_batches:
  102. return
  103. imgs = core_utils.tensor_container_to_device(imgs, torch.device('cuda:0'))
  104. targets = core_utils.tensor_container_to_device(targets, torch.device('cuda:0'))
  105. pred_mask = module(imgs)
  106. # Visualize the batch
  107. if undo_preprocessing_func:
  108. BinarySegmentationVisualization.visualize_batch(imgs, pred_mask, targets, batch_i, visualization_path,
  109. undo_preprocessing_func=undo_preprocessing_func)
  110. else:
  111. BinarySegmentationVisualization.visualize_batch(imgs, pred_mask, targets, batch_i, visualization_path)
  112. def one_hot_to_binary_edge(x: torch.Tensor,
  113. kernel_size: int,
  114. flatten_channels: bool = True) -> torch.Tensor:
  115. """
  116. Utils function to create edge feature maps.
  117. :param x: input tensor, must be one_hot tensor with shape [B, C, H, W]
  118. :param kernel_size: kernel size of dilation erosion convolutions. The result edge widths depends on this argument as
  119. follows: `edge_width = kernel - 1`
  120. :param flatten_channels: Whether to apply logical_or across channels dimension, if at least one pixel class is
  121. considered as edge pixel flatten value is 1. If set as `False` the output tensor shape is [B, C, H, W], else
  122. [B, 1, H, W]. Default is `True`.
  123. :return: one_hot edge torch.Tensor.
  124. """
  125. if kernel_size < 0 or kernel_size % 2 == 0:
  126. raise ValueError(f"kernel size must be an odd positive values, such as [1, 3, 5, ..], found: {kernel_size}")
  127. _kernel = torch.ones(x.size(1), 1, kernel_size, kernel_size, dtype=torch.float32, device=x.device)
  128. padding = (kernel_size - 1) // 2
  129. # Use replicate padding to prevent class shifting and edge formation at the image boundaries.
  130. padded_x = F.pad(x.float(), mode="replicate", pad=[padding] * 4)
  131. # The binary edges feature map is created by subtracting dilated features from erosed features.
  132. # First the positive one value masks are expanded (dilation) by applying a sliding window filter of one values.
  133. # The resulted output is then clamped to binary format to [0, 1], this way the one-hot boundaries are expanded by
  134. # (kernel_size - 1) / 2.
  135. dilation = torch.clamp(
  136. F.conv2d(padded_x, _kernel, groups=x.size(1)),
  137. 0, 1
  138. )
  139. # Similar to dilation, erosion (can be seen as inverse of dilation) is applied to contract the one-hot features by
  140. # applying a dilation operation on the inverse of the one-hot features.
  141. erosion = 1 - torch.clamp(
  142. F.conv2d(1 - padded_x, _kernel, groups=x.size(1)),
  143. 0, 1
  144. )
  145. # Finally the edge features are the result of subtracting dilation by erosion.
  146. # i.e for a simple 1D one-hot input: [0, 0, 0, 1, 1, 1, 0, 0, 0], using sliding kernel with size 3: [1, 1, 1]
  147. # Dilated features: [0, 0, 1, 1, 1, 1, 1, 0, 0]
  148. # Erosed inverse features: [0, 0, 0, 0, 1, 0, 0, 0, 0]
  149. # Edge features: dilation - erosion: [0, 0, 1, 1, 0, 1, 1, 0, 0]
  150. edge = dilation - erosion
  151. if flatten_channels:
  152. # use max operator across channels. Equivalent to logical or for input with binary values [0, 1].
  153. edge = edge.max(dim=1, keepdim=True)[0]
  154. return edge
  155. def target_to_binary_edge(target: torch.Tensor,
  156. num_classes: int,
  157. kernel_size: int,
  158. ignore_index: int = None,
  159. flatten_channels: bool = True) -> torch.Tensor:
  160. """
  161. Utils function to create edge feature maps from target.
  162. :param target: Class labels long tensor, with shape [N, H, W]
  163. :param num_classes: num of classes in datasets excluding ignore label, this is the output channels of the one hot
  164. result.
  165. :param kernel_size: kernel size of dilation erosion convolutions. The result edge widths depends on this argument as
  166. follows: `edge_width = kernel - 1`
  167. :param flatten_channels: Whether to apply logical or across channels dimension, if at least one pixel class is
  168. considered as edge pixel flatten value is 1. If set as `False` the output tensor shape is [B, C, H, W], else
  169. [B, 1, H, W]. Default is `True`.
  170. :return: one_hot edge torch.Tensor.
  171. """
  172. one_hot = to_one_hot(target, num_classes=num_classes, ignore_index=ignore_index)
  173. return one_hot_to_binary_edge(one_hot, kernel_size=kernel_size, flatten_channels=flatten_channels)
Discard
Tip!

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