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

#970 Update YoloNASQuickstart.md

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/SG-000_fix_readme_yolonas_snippets
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
  1. from abc import ABC, abstractmethod
  2. from typing import List, Optional, Tuple, Union, Iterable
  3. from contextlib import contextmanager
  4. from tqdm import tqdm
  5. import numpy as np
  6. import torch
  7. from super_gradients.training.utils.utils import generate_batch
  8. from super_gradients.training.utils.media.video import load_video, includes_video_extension
  9. from super_gradients.training.utils.media.image import ImageSource, check_image_typing
  10. from super_gradients.training.utils.media.stream import WebcamStreaming
  11. from super_gradients.training.utils.detection_utils import DetectionPostPredictionCallback
  12. from super_gradients.training.models.sg_module import SgModule
  13. from super_gradients.training.models.prediction_results import (
  14. ImagesDetectionPrediction,
  15. VideoDetectionPrediction,
  16. ImagePrediction,
  17. ImageDetectionPrediction,
  18. ImagesPredictions,
  19. VideoPredictions,
  20. )
  21. from super_gradients.training.models.predictions import Prediction, DetectionPrediction
  22. from super_gradients.training.processing.processing import Processing, ComposeProcessing
  23. from super_gradients.common.abstractions.abstract_logger import get_logger
  24. logger = get_logger(__name__)
  25. @contextmanager
  26. def eval_mode(model: SgModule) -> None:
  27. """Set a model in evaluation mode and deactivate gradient computation, undo at the end.
  28. :param model: The model to set in evaluation mode.
  29. """
  30. _starting_mode = model.training
  31. model.eval()
  32. with torch.no_grad():
  33. yield
  34. model.train(mode=_starting_mode)
  35. class Pipeline(ABC):
  36. """An abstract base class representing a processing pipeline for a specific task.
  37. The pipeline includes loading images, preprocessing, prediction, and postprocessing.
  38. :param model: The model used for making predictions.
  39. :param image_processor: A single image processor or a list of image processors for preprocessing and postprocessing the images.
  40. :param device: The device on which the model will be run. If None, will run on current model device. Use "cuda" for GPU support.
  41. """
  42. def __init__(self, model: SgModule, image_processor: Union[Processing, List[Processing]], class_names: List[str], device: Optional[str] = None):
  43. super().__init__()
  44. self.device = device or next(model.parameters()).device
  45. self.model = model.to(self.device)
  46. self.class_names = class_names
  47. if isinstance(image_processor, list):
  48. image_processor = ComposeProcessing(image_processor)
  49. self.image_processor = image_processor
  50. def __call__(self, inputs: Union[str, ImageSource, List[ImageSource]], batch_size: Optional[int] = 32) -> ImagesPredictions:
  51. """Predict an image or a list of images.
  52. Supported types include:
  53. - str: A string representing either a video, an image or an URL.
  54. - numpy.ndarray: A numpy array representing the image
  55. - torch.Tensor: A PyTorch tensor representing the image
  56. - PIL.Image.Image: A PIL Image object
  57. - List: A list of images of any of the above image types (list of videos not supported).
  58. :param inputs: inputs to the model, which can be any of the above-mentioned types.
  59. :param batch_size: Number of images to be processed at the same time.
  60. :return: Results of the prediction.
  61. """
  62. if includes_video_extension(inputs):
  63. return self.predict_video(inputs, batch_size)
  64. elif check_image_typing(inputs):
  65. return self.predict_images(inputs, batch_size)
  66. else:
  67. raise ValueError(f"Input {inputs} not supported for prediction.")
  68. def predict_images(self, images: Union[ImageSource, List[ImageSource]], batch_size: Optional[int] = 32) -> ImagesPredictions:
  69. """Predict an image or a list of images.
  70. :param images: Images to predict.
  71. :param batch_size: The size of each batch.
  72. :return: Results of the prediction.
  73. """
  74. from super_gradients.training.utils.media.image import load_images
  75. images = load_images(images)
  76. result_generator = self._generate_prediction_result(images=images, batch_size=batch_size)
  77. return self._combine_image_prediction_to_images(result_generator, n_images=len(images))
  78. def predict_video(self, video_path: str, batch_size: Optional[int] = 32) -> VideoPredictions:
  79. """Predict on a video file, by processing the frames in batches.
  80. :param video_path: Path to the video file.
  81. :param batch_size: The size of each batch.
  82. :return: Results of the prediction.
  83. """
  84. video_frames, fps = load_video(file_path=video_path)
  85. result_generator = self._generate_prediction_result(images=video_frames, batch_size=batch_size)
  86. return self._combine_image_prediction_to_video(result_generator, fps=fps, n_images=len(video_frames))
  87. def predict_webcam(self) -> None:
  88. """Predict using webcam"""
  89. def _draw_predictions(frame: np.ndarray) -> np.ndarray:
  90. """Draw the predictions on a single frame from the stream."""
  91. frame_prediction = next(iter(self._generate_prediction_result(images=[frame])))
  92. return frame_prediction.draw()
  93. video_streaming = WebcamStreaming(frame_processing_fn=_draw_predictions, fps_update_frequency=1)
  94. video_streaming.run()
  95. def _generate_prediction_result(self, images: Iterable[np.ndarray], batch_size: Optional[int] = None) -> Iterable[ImagePrediction]:
  96. """Run the pipeline on the images as single batch or through multiple batches.
  97. NOTE: A core motivation to have this function as a generator is that it can be used in a lazy way (if images is generator itself),
  98. i.e. without having to load all the images into memory.
  99. :param images: Iterable of numpy arrays representing images.
  100. :param batch_size: The size of each batch.
  101. :return: Iterable of Results object, each containing the results of the prediction and the image.
  102. """
  103. if batch_size is None:
  104. yield from self._generate_prediction_result_single_batch(images)
  105. else:
  106. for batch_images in generate_batch(images, batch_size):
  107. yield from self._generate_prediction_result_single_batch(batch_images)
  108. def _generate_prediction_result_single_batch(self, images: Iterable[np.ndarray]) -> Iterable[ImagePrediction]:
  109. """Run the pipeline on images. The pipeline is made of 4 steps:
  110. 1. Load images - Loading the images into a list of numpy arrays.
  111. 2. Preprocess - Encode the image in the shape/format expected by the model
  112. 3. Predict - Run the model on the preprocessed image
  113. 4. Postprocess - Decode the output of the model so that the predictions are in the shape/format of original image.
  114. :param images: Iterable of numpy arrays representing images.
  115. :return: Iterable of Results object, each containing the results of the prediction and the image.
  116. """
  117. images = list(images) # We need to load all the images into memory, and to reuse it afterwards.
  118. self.model = self.model.to(self.device) # Make sure the model is on the correct device, as it might have been moved after init
  119. # Preprocess
  120. preprocessed_images, processing_metadatas = [], []
  121. for image in images:
  122. preprocessed_image, processing_metadata = self.image_processor.preprocess_image(image=image.copy())
  123. preprocessed_images.append(preprocessed_image)
  124. processing_metadatas.append(processing_metadata)
  125. # Predict
  126. with eval_mode(self.model):
  127. torch_inputs = torch.Tensor(np.array(preprocessed_images)).to(self.device)
  128. model_output = self.model(torch_inputs)
  129. predictions = self._decode_model_output(model_output, model_input=torch_inputs)
  130. # Postprocess
  131. postprocessed_predictions = []
  132. for image, prediction, processing_metadata in zip(images, predictions, processing_metadatas):
  133. prediction = self.image_processor.postprocess_predictions(predictions=prediction, metadata=processing_metadata)
  134. postprocessed_predictions.append(prediction)
  135. # Yield results one by one
  136. for image, prediction in zip(images, postprocessed_predictions):
  137. yield self._instantiate_image_prediction(image=image, prediction=prediction)
  138. @abstractmethod
  139. def _decode_model_output(self, model_output: Union[List, Tuple, torch.Tensor], model_input: np.ndarray) -> List[Prediction]:
  140. """Decode the model outputs, move each prediction to numpy and store it in a Prediction object.
  141. :param model_output: Direct output of the model, without any post-processing.
  142. :param model_input: Model input (i.e. images after preprocessing).
  143. :return: Model predictions, without any post-processing.
  144. """
  145. raise NotImplementedError
  146. @abstractmethod
  147. def _instantiate_image_prediction(self, image: np.ndarray, prediction: Prediction) -> ImagePrediction:
  148. """Instantiate an object wrapping an image and the pipeline's prediction.
  149. :param image: Image to predict.
  150. :param prediction: Model prediction on that image.
  151. :return: Object wrapping an image and the pipeline's prediction.
  152. """
  153. raise NotImplementedError
  154. @abstractmethod
  155. def _combine_image_prediction_to_images(self, images_prediction_lst: Iterable[ImagePrediction], n_images: Optional[int] = None) -> ImagesPredictions:
  156. """Instantiate an object wrapping the list of images and the pipeline's predictions on them.
  157. :param images_prediction_lst: List of image predictions.
  158. :param n_images: (Optional) Number of images in the list. This used for tqdm progress bar to work with iterables, but is not required.
  159. :return: Object wrapping the list of image predictions.
  160. """
  161. raise NotImplementedError
  162. @abstractmethod
  163. def _combine_image_prediction_to_video(
  164. self, images_prediction_lst: Iterable[ImagePrediction], fps: float, n_images: Optional[int] = None
  165. ) -> VideoPredictions:
  166. """Instantiate an object holding the video frames and the pipeline's predictions on it.
  167. :param images_prediction_lst: List of image predictions.
  168. :param fps: Frames per second.
  169. :param n_images: (Optional) Number of images in the list. This used for tqdm progress bar to work with iterables, but is not required.
  170. :return: Object wrapping the list of image predictions as a Video.
  171. """
  172. raise NotImplementedError
  173. class DetectionPipeline(Pipeline):
  174. """Pipeline specifically designed for object detection tasks.
  175. The pipeline includes loading images, preprocessing, prediction, and postprocessing.
  176. :param model: The object detection model (instance of SgModule) used for making predictions.
  177. :param class_names: List of class names corresponding to the model's output classes.
  178. :param post_prediction_callback: Callback function to process raw predictions from the model.
  179. :param image_processor: Single image processor or a list of image processors for preprocessing and postprocessing the images.
  180. :param device: The device on which the model will be run. If None, will run on current model device. Use "cuda" for GPU support.
  181. """
  182. def __init__(
  183. self,
  184. model: SgModule,
  185. class_names: List[str],
  186. post_prediction_callback: DetectionPostPredictionCallback,
  187. device: Optional[str] = None,
  188. image_processor: Optional[Processing] = None,
  189. ):
  190. super().__init__(model=model, device=device, image_processor=image_processor, class_names=class_names)
  191. self.post_prediction_callback = post_prediction_callback
  192. def _decode_model_output(self, model_output: Union[List, Tuple, torch.Tensor], model_input: np.ndarray) -> List[DetectionPrediction]:
  193. """Decode the model output, by applying post prediction callback. This includes NMS.
  194. :param model_output: Direct output of the model, without any post-processing.
  195. :param model_input: Model input (i.e. images after preprocessing).
  196. :return: Predicted Bboxes.
  197. """
  198. post_nms_predictions = self.post_prediction_callback(model_output, device=self.device)
  199. predictions = []
  200. for prediction, image in zip(post_nms_predictions, model_input):
  201. prediction = prediction if prediction is not None else torch.zeros((0, 6), dtype=torch.float32)
  202. prediction = prediction.detach().cpu().numpy()
  203. predictions.append(
  204. DetectionPrediction(
  205. bboxes=prediction[:, :4],
  206. confidence=prediction[:, 4],
  207. labels=prediction[:, 5],
  208. bbox_format="xyxy",
  209. image_shape=image.shape,
  210. )
  211. )
  212. return predictions
  213. def _instantiate_image_prediction(self, image: np.ndarray, prediction: DetectionPrediction) -> ImagePrediction:
  214. return ImageDetectionPrediction(image=image, prediction=prediction, class_names=self.class_names)
  215. def _combine_image_prediction_to_images(
  216. self, images_predictions: Iterable[ImageDetectionPrediction], n_images: Optional[int] = None
  217. ) -> ImagesDetectionPrediction:
  218. if n_images is not None and n_images == 1:
  219. # Do not show tqdm progress bar if there is only one image
  220. images_predictions = [next(iter(images_predictions))]
  221. else:
  222. images_predictions = [image_predictions for image_predictions in tqdm(images_predictions, total=n_images, desc="Predicting Images")]
  223. return ImagesDetectionPrediction(_images_prediction_lst=images_predictions)
  224. def _combine_image_prediction_to_video(
  225. self, images_predictions: Iterable[ImageDetectionPrediction], fps: float, n_images: Optional[int] = None
  226. ) -> VideoDetectionPrediction:
  227. images_predictions = [image_predictions for image_predictions in tqdm(images_predictions, total=n_images, desc="Predicting Video")]
  228. return VideoDetectionPrediction(_images_prediction_lst=images_predictions, fps=fps)
Discard
Tip!

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