Hey fix my code it inst detecting anymore here is the old one and the new one pleas fix…
- User
Hey fix my code it inst detecting anymore here is the old one and the new one pleas fix the new one and all this is in one python file and keep all features as other threads hevely rely on this:
New one: class YOLOEnsemble: _instance = None _lock = threading.Lock()
def __init__(self, models_config, class_names=None): """ models_config: List of tuples (model_path, imgsz) class_names: dict mapping class indices to names, e.g., {0: 'person'} """ self.models = [] # [{'session':..., 'input_name':..., 'imgsz':...}, ...] self.names = class_names if class_names else {0: 'person'} self.cache_lock = threading.Lock() self._load_models(models_config) def _load_models(self, models_config): """Load ONNX models with DirectML execution provider.""" for model_path, imgsz in models_config: try: onnx_path = model_path if model_path.endswith(".onnx") else model_path.replace('.pt', '.onnx') providers = ['DmlExecutionProvider'] sess_options = ort.SessionOptions() sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL session = ort.InferenceSession(onnx_path, sess_options, providers=providers) input_name = session.get_inputs()[0].name self.models.append({ 'session': session, 'input_name': input_name, 'imgsz': imgsz }) logging.info(f"Loaded ONNX model with DirectML: {onnx_path} (imgsz={imgsz})") except Exception as e: logging.error(f"Failed to load ONNX model {model_path}: {e}") def preprocess(self, frame, imgsz): """ Preprocess input image: - Resize to (imgsz, imgsz) - Normalize to [0,1] - Convert HWC to CHW - Add batch dimension """ resized = cv2.resize(frame, (imgsz, imgsz), interpolation=cv2.INTER_LINEAR) img = resized.astype(np.float32) / 255.0 img = np.transpose(img, (2, 0, 1)) img = np.expand_dims(img, axis=0) img = np.ascontiguousarray(img) return img def fast_nms(self, boxes, scores, iou_threshold=0.25): """ Performs non-maximum suppression (NMS) on boxes given scores, returns indices to keep. """ if len(boxes) == 0: return [] boxes = np.array(boxes, dtype=np.float32) scores = np.array(scores, dtype=np.float32) indices = np.argsort(scores)[::-1] keep = [] while indices.size > 0: current = indices[0] keep.append(current) if indices.size == 1: break remaining = indices[1:] current_box = boxes[current] remaining_boxes = boxes[remaining] iou = self._fast_iou(current_box, remaining_boxes) indices = remaining[iou <= iou_threshold] return keep def _fast_iou(self, box, boxes): """ Vectorized IoU calculation between one box and multiple boxes. """ x1 = np.maximum(box[0], boxes[:, 0]) y1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[2], boxes[:, 2]) y2 = np.minimum(box[3], boxes[:, 3]) inter_area = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1) box_area = (box[2] - box[0]) * (box[3] - box[1]) boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) union = box_area + boxes_area - inter_area return inter_area / np.maximum(union, 1e-10) def postprocess(self, outputs, conf_thres=0.3, iou_threshold=0.25, max_det=40): """ Postprocess raw ONNX outputs. Expected output shape: (batch_size=1, N, 6) [x1, y1, x2, y2, confidence, class_id] Returns: boxes: (M, 4) numpy array of bbox coordinates scores: (M,) numpy array of confidences classes: (M,) numpy array of class indices """ preds = outputs[0] # Usually outputs is a list: [output_tensor] preds = np.squeeze(preds, axis=0) # (N, 6) if preds.shape[0] == 0: return np.empty((0, 4)), np.empty((0,)), np.empty((0,), dtype=np.int32) # Filter by confidence threshold conf_mask = preds[:, 4] > conf_thres preds = preds[conf_mask] if preds.shape[0] == 0: return np.empty((0, 4)), np.empty((0,)), np.empty((0,), dtype=np.int32) boxes = preds[:, :4] scores = preds[:, 4] classes = preds[:, 5].astype(np.int32) # Apply NMS keep = self.fast_nms(boxes, scores, iou_threshold) if len(keep) > max_det: keep = keep[:max_det] return boxes[keep], scores[keep], classes[keep] def predict(self, frame, conf_thres=0.3): """ Perform inference on input frame with all ensemble models. Returns a list of DummyResults compatible with detection thread. Each DummyResults contains: - boxes.xyxy (torch.FloatTensor) - boxes.conf (torch.FloatTensor) - boxes.cls (torch.FloatTensor) - scale_x, scale_y, original_width, original_height """ all_results = [] original_height, original_width = frame.shape[:2] for model_info in self.models: session = model_info['session'] input_name = model_info['input_name'] imgsz = model_info['imgsz'] # Prepare input tensor for ONNX input_tensor = self.preprocess(frame, imgsz) try: # ONNX Runtime inference outputs = session.run(None, {input_name: input_tensor}) boxes, scores, classes = self.postprocess( outputs, conf_thres=conf_thres, iou_threshold=0.25, max_det=40 ) if boxes.shape[0] == 0: continue # Scale boxes from [imgsz,imgsz] back to original image size scale_x = original_width / imgsz scale_y = original_height / imgsz boxes[:, [0, 2]] *= scale_x boxes[:, [1, 3]] *= scale_y # Convert to torch tensors for compatibility with detection thread boxes_torch = torch.from_numpy(boxes).float() scores_torch = torch.from_numpy(scores).float() classes_torch = torch.from_numpy(classes).float() class DummyBoxes: def __init__(self, xyxy, conf, cls): self.xyxy = xyxy self.conf = conf self.cls = cls class DummyResults: def __init__(self, boxes, scale_x, scale_y, ow, oh): self.boxes = boxes self.scale_x = scale_x self.scale_y = scale_y self.original_width = ow self.original_height = oh dummy_boxes = DummyBoxes(boxes_torch, scores_torch, classes_torch) dummy_results = DummyResults(dummy_boxes, scale_x, scale_y, original_width, original_height) all_results.append(dummy_results) except Exception as e: logging.warning(f"ONNX DirectML inference failed: {e}") continue return all_results @classmethod def get_instance(cls, models_config, class_names=None): with cls._lock: if cls._instance is None: cls._instance = YOLOEnsemble(models_config, class_names) return cls._instance - Assistant
- User
can you give me the entire fixed clases and keep all features and this is made to run on AMD Gpu Windows i just want the new one to work again
- Assistant
- User
you said this at the top: # Assumed external tracker Sort implementation is imported elsewhere:
from sort import Sort (make sure you have it included)
def clamp(value, min_val, max_val): return min_val if value < min_val else max_val if value > max_val else value
I dont know what that mean i have sort as a file near my python file and this is the import import sort from sort import Sort
- Assistant
Thanks for clarifying! The message about
Sortmeant: your detection/tracking code uses aSorttracker class, which typically comes from a separate Python file or package (oftensort.py).
Since you have:
import sort from sort import Sortand your
sort.pyis next to your main Python script, you are good — your tracker code is properly imported.Just make sure:
- The
sort.pyfile is in the same directory as your main Python file. - The
Sortclass insidesort.pyis defined as expected.
No changes needed there.
Why did I mention it?
- The
- User
Oh ok and what does this mean then? def clamp(value, min_val, max_val): return min_val if value < min_val else max_val if value > max_val else value
- Assistant
Great question!
What does this function do?
def clamp(value, min_val, max_val): return min_val if value < min_val else max_val if value > max_val else valueclampis a utility function that restricts a numericalvaluewithin a specified range[min_val, max_val].- If
valueis less thanmin_val, it returnsmin_val. - If
valueis greater thanmax_val, it returnsmax_val. - Otherwise, it simply returns the original
value.
Example usage
- If
- User
Your updated version does it still have everyhting like fov stuff
- Assistant
Yes, the updated version I provided preserves everything from your original new version, including the FOV radius calculations and filtering, screen cropping, confidence clamping, the entire BitBlt capture, coordinate transforms, NMS, tracking, and the emission of tracked detections.
- User
- Assistant
- User
can you just give me something what take my yolo.pt and turn it to a .onnx like an easy way that it can text and give you the corect result wile it turn it to onnx then i give you the debug info and then you can probevly fix my problem?
- Assistant
- User
no cna you just put it all in one with a small ui wher i drag and drop and it put all result in a debug file and it can create one
- Assistant
- User
i did but [11:14:02] Loaded model path: C:/Users/belze/OneDrive/Desktop/UD Premium Lite/yolo11n.pt [11:14:23] Test image selected: C:/Users/belze/Downloads/d [11:14:23] Loading YOLO model... [11:14:23] Exporting to ONNX... [11:14:24] Error during export or inference: module 'onnxruntime' has no attribute 'get_available_providers' Traceback (most recent call last): File "c:\Users\belze\Downloads\exporter_debugger_gui.py", line 116, in export_and_test providers = ort.get_available_providers() AttributeError: module 'onnxruntime' has no attribute 'get_available_providers'
- Assistant
- User
i need it only to turn it to onnx and give me info that it
- Assistant