Marcus Vinicius Zerbini Canhaço commited on
Commit
810f531
·
1 Parent(s): 577120c

feat: atualização do detector com otimizações para GPU T4

Browse files
Files changed (1) hide show
  1. src/domain/detectors/gpu.py +84 -1
src/domain/detectors/gpu.py CHANGED
@@ -108,6 +108,8 @@ class WeaponDetectorGPU(BaseDetector):
108
  "label": self.text_queries[label]
109
  })
110
 
 
 
111
  return detections
112
 
113
  except Exception as e:
@@ -151,4 +153,85 @@ class WeaponDetectorGPU(BaseDetector):
151
 
152
  except Exception as e:
153
  logger.error(f"Erro ao processar vídeo: {str(e)}")
154
- return video_path, metrics
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  "label": self.text_queries[label]
109
  })
110
 
111
+ # Aplicar NMS nas detecções
112
+ detections = self._apply_nms(detections)
113
  return detections
114
 
115
  except Exception as e:
 
153
 
154
  except Exception as e:
155
  logger.error(f"Erro ao processar vídeo: {str(e)}")
156
+ return video_path, metrics
157
+
158
+ def _preprocess_image(self, image: Image.Image) -> Image.Image:
159
+ """Pré-processa a imagem para o formato esperado pelo modelo."""
160
+ try:
161
+ # Converter para RGB se necessário
162
+ if image.mode != 'RGB':
163
+ image = image.convert('RGB')
164
+
165
+ # Redimensionar mantendo proporção
166
+ target_size = (self.default_resolution, self.default_resolution)
167
+ if image.size != target_size:
168
+ ratio = min(target_size[0] / image.size[0], target_size[1] / image.size[1])
169
+ new_size = tuple(int(dim * ratio) for dim in image.size)
170
+ image = image.resize(new_size, Image.Resampling.LANCZOS)
171
+
172
+ # Adicionar padding se necessário
173
+ if new_size != target_size:
174
+ new_image = Image.new('RGB', target_size, (0, 0, 0))
175
+ paste_x = (target_size[0] - new_size[0]) // 2
176
+ paste_y = (target_size[1] - new_size[1]) // 2
177
+ new_image.paste(image, (paste_x, paste_y))
178
+ image = new_image
179
+
180
+ return image
181
+ except Exception as e:
182
+ logger.error(f"Erro no pré-processamento: {str(e)}")
183
+ return image
184
+
185
+ def _apply_nms(self, detections: list, iou_threshold: float = 0.5) -> list:
186
+ """Aplica Non-Maximum Suppression nas detecções."""
187
+ try:
188
+ if not detections or len(detections) <= 1:
189
+ return detections
190
+
191
+ # Extrair scores e boxes
192
+ scores = torch.tensor([d["confidence"] for d in detections])
193
+ boxes = torch.tensor([[d["box"][0], d["box"][1], d["box"][2], d["box"][3]]
194
+ for d in detections])
195
+
196
+ # Ordenar por score
197
+ _, order = scores.sort(descending=True)
198
+ keep = []
199
+
200
+ while order.numel() > 0:
201
+ if order.numel() == 1:
202
+ keep.append(order.item())
203
+ break
204
+
205
+ i = order[0]
206
+ keep.append(i.item())
207
+
208
+ # Calcular IoU com os boxes restantes
209
+ box1 = boxes[i]
210
+ box2 = boxes[order[1:]]
211
+
212
+ # Calcular interseção
213
+ left = torch.max(box1[0], box2[:, 0])
214
+ top = torch.max(box1[1], box2[:, 1])
215
+ right = torch.min(box1[2], box2[:, 2])
216
+ bottom = torch.min(box1[3], box2[:, 3])
217
+
218
+ width = torch.clamp(right - left, min=0)
219
+ height = torch.clamp(bottom - top, min=0)
220
+ inter = width * height
221
+
222
+ # Calcular união
223
+ area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
224
+ area2 = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1])
225
+ union = area1 + area2 - inter
226
+
227
+ # Calcular IoU
228
+ iou = inter / union
229
+ mask = iou <= iou_threshold
230
+ order = order[1:][mask]
231
+
232
+ # Retornar detecções filtradas
233
+ return [detections[i] for i in keep]
234
+
235
+ except Exception as e:
236
+ logger.error(f"Erro ao aplicar NMS: {str(e)}")
237
+ return detections