Certainly! Below is a full self-contained Python module implementing your YOLO Ensemble and DetectionThread adapted to ONNX with DirectML, including:
- Proper ONNX model output decoding assuming a YOLOv8 export style (replace with your exact model logic if needed)
- Preprocessing and postprocessing for ONNX outputs with decoding and NMS
- BitBlt screen capture as before
- Tracking and signal emitting as you had
- Preserves your higher FPS and DirectML acceleration
Important notes:
- This example assumes your ONNX model outputs raw YOLOv8-style inference results with shape
(1, N, 85) where 85 = 4 box coords + 1 objectness + 80 class probs (COCO standard). Modify NUM_CLASSES if different.
- You must adapt
postprocess if your ONNX model outputs differ—e.g., a simpler output or a custom layer.
- Make sure to install required packages:
onnxruntime-gpu, numpy, opencv-python, torch (for compatible dummy tensor wrapping), PyQt6 or PySide6 for QtCore.
Here is the full Python code with detailed comments:
import threading
import ctypes
import logging
import time
import numpy as np
import cv2
import onnxruntime as ort
import torch # For wrapping outputs, your detection signal expects torch tensors
from PyQt6 import QtCore
# Simplified SORT tracker interface placeholder - use your own implementation
# from sort import Sort
# Example minimal SORT implementation placeholder (replace with your actual tracker)
class Sort:
def __init__(self, max_age=10, min_hits=1, iou_threshold=0.2):
pass
def update(self, dets):
# Return empty array for simplicity in this example
return np.empty((0, 5))
def clamp(value, min_val, max_val):
return min_val if value < min_val else max_val if value > max_val else value
class YOLOEnsemble:
_instance = None
_lock = threading.Lock()
def __init__(self, models_config):
"""
models_config: List of tuples [(onnx_model_path, input_img_size), ...]
"""
self.models = [] # List of dicts with keys session, input_name, imgsz
self.names = {} # Map class ids to names; for demo, assume COCO person class only
self.NUM_CLASSES = 80 # Adjust according to model! Example: 80 COCO classes
self._load_models(models_config)
# COCO class names minimal for demo - add your classes as needed
self.names = {0: 'person'}
def _load_models(self, models_config):
for model_path, imgsz in models_config:
try:
logging.info(f"Loading ONNX model for DirectML: {model_path} (imgsz={imgsz})")
providers = ['DmlExecutionProvider', 'CPUExecutionProvider'] # Try DirectML then CPU fallback
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
session = ort.InferenceSession(model_path, sess_options, providers=providers)
input_name = session.get_inputs()[0].name
self.models.append({
'session': session,
'input_name': input_name,
'imgsz': imgsz
})
except Exception as ex:
logging.error(f"Failed to load ONNX model {model_path}: {ex}")
def preprocess(self, frame, imgsz):
# frame: np.ndarray RGB image
img = cv2.resize(frame, (imgsz, imgsz), interpolation=cv2.INTER_LINEAR)
img = img.astype(np.float32) / 255.0 # normalize to 0-1
# Convert HWC to CHW
img = np.transpose(img, (2, 0, 1))
# Add batch dimension
img = np.expand_dims(img, 0).astype(np.float32)
return img
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def postprocess(self, outputs, conf_thres=0.3, iou_thres=0.25, max_det=40):
"""
Postprocess raw ONNX output for YOLOv8-style models.
Typical ONNX output shape for YOLOv8: (1, N, 85)
Columns: [x_center, y_center, width, height, obj_conf, class_scores...]
Returns:
boxes: (M,4) xyxy boxes in input image space
scores: (M,) confidences (obj_conf * class_conf)
classes: (M,) class ids
"""
preds = outputs[0] # Shape: (1, N, 85)
preds = np.squeeze(preds, axis=0) # (N, 85)
if preds.size == 0:
return np.empty((0, 4)), np.empty(0), np.empty(0, dtype=int)
# Split preds into components
boxes = preds[:, 0:4] # xywh format
obj_conf = self.sigmoid(preds[:, 4])
class_probs = self.sigmoid(preds[:, 5:5 + self.NUM_CLASSES])
# Multiply obj_conf by class probabilities to get class scores
scores = obj_conf[:, None] * class_probs # shape (N, num_classes)
# Filter by conf threshold
class_ids = np.argmax(scores, axis=1)
confs = scores[np.arange(scores.shape[0]), class_ids]
conf_mask = confs > conf_thres
if not np.any(conf_mask):
return np.empty((0, 4)), np.empty(0), np.empty(0, dtype=int)
boxes = boxes[conf_mask]
confs = confs[conf_mask]
class_ids = class_ids[conf_mask]
# Convert xywh to xyxy
xyxy = np.zeros_like(boxes)
xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2 # x1
xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2 # y1
xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2 # x2
xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2 # y2
# Clip boxes at 0 and imgsz (optional depends on your usage)
xyxy = np.clip(xyxy, 0, np.inf)
# Run NMS
keep = self.fast_nms(xyxy, confs, iou_thres)
if len(keep) > max_det:
keep = keep[:max_det]
return xyxy[keep], confs[keep], class_ids[keep]
def fast_nms(self, boxes, scores, iou_threshold=0.25):
if boxes.shape[0] == 0:
return []
boxes = boxes.astype(np.float32)
scores = scores.astype(np.float32)
indices = np.argsort(scores)[::-1]
keep = []
while len(indices) > 0:
current = indices[0]
keep.append(current)
if len(indices) == 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):
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 predict(self, frame, conf_thres=0.3):
"""
Run inference on all models and return list of dummy results.
Each dummy result has .boxes (with .xyxy, .conf, .cls torch tensors) and scale info.
"""
all_results = []
h0, w0 = frame.shape[:2]
for model_info in self.models:
session = model_info['session']
input_name = model_info['input_name']
imgsz = model_info['imgsz']
input_tensor = self.preprocess(frame, imgsz)
try:
outputs = session.run(None, {input_name: input_tensor})
boxes, scores, classes = self.postprocess(outputs, conf_thres=conf_thres)
if boxes.size == 0:
continue
# Scale boxes back to original image size
scale_x = w0 / imgsz
scale_y = h0 / imgsz
boxes[:, [0, 2]] *= scale_x
boxes[:, [1, 3]] *= scale_y
# Convert to torch tensors to keep compatibility downstream
boxes_torch = torch.from_numpy(boxes).float()
conf_torch = torch.from_numpy(scores).float()
class_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, conf_torch, class_torch)
results = DummyResults(dummy_boxes, scale_x, scale_y, w0, h0)
all_results.append(results)
except Exception as e:
logging.warning(f"ONNX Runtime inference error: {e}")
continue
return all_results
class DetectionThread(QtCore.QThread):
detection_signal = QtCore.pyqtSignal(list, list, list, list, list)
def __init__(self, settings):
super().__init__()
self.settings = settings
self.running = False
self.frame_lock = threading.Lock()
# Windows BitBlt setup
self.user32 = ctypes.windll.user32
self.gdi32 = ctypes.windll.gdi32
self.dc = None
self.memdc = None
self.bitmap = None
self.bitmapinfo = None
# Tracker (use your own SORT implementation)
self.tracker = Sort(max_age=10, min_hits=1, iou_threshold=0.2)
self.frame_skip = 0
self.last_detection_time = 0
self.screen_width = 0
self.screen_height = 0
self.center_x = 0
self.center_y = 0
model_paths = [
("models/yolo11n.onnx", 256), # Example: You can load multiple models here
]
self.yolo_ensemble = YOLOEnsemble(model_paths)
def setup_bitblt(self):
try:
hwnd = self.user32.GetDesktopWindow()
self.dc = self.user32.GetDC(hwnd)
self.memdc = self.gdi32.CreateCompatibleDC(self.dc)
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [
("biSize", ctypes.c_uint32),
("biWidth", ctypes.c_int),
("biHeight", ctypes.c_int),
("biPlanes", ctypes.c_short),
("biBitCount", ctypes.c_short),
("biCompression", ctypes.c_uint32),
("biSizeImage", ctypes.c_uint32),
("biXPelsPerMeter", ctypes.c_int),
("biYPelsPerMeter", ctypes.c_int),
("biClrUsed", ctypes.c_uint32),
("biClrImportant", ctypes.c_uint32)
]
self.bitmapinfo = BITMAPINFOHEADER()
self.bitmapinfo.biSize = ctypes.sizeof(BITMAPINFOHEADER)
self.bitmapinfo.biPlanes = 1
self.bitmapinfo.biBitCount = 32
self.bitmapinfo.biCompression = 0
return True
except Exception as e:
logging.error(f"BitBlt setup failed: {e}")
return False
def cleanup_bitblt(self):
try:
if self.bitmap:
self.gdi32.DeleteObject(self.bitmap)
self.bitmap = None
if self.memdc:
self.gdi32.DeleteDC(self.memdc)
self.memdc = None
if self.dc:
self.user32.ReleaseDC(None, self.dc)
self.dc = None
except Exception as e:
logging.error(f"BitBlt cleanup failed: {e}")
def capture_screen_region(self, x, y, width, height):
try:
self.bitmapinfo.biWidth = width
self.bitmapinfo.biHeight = -height # negative for top-down bitmap
self.bitmapinfo.biSizeImage = width * height * 4
self.bitmap = self.gdi32.CreateCompatibleBitmap(self.dc, width, height)
self.gdi32.SelectObject(self.memdc, self.bitmap)
if not self.gdi32.BitBlt(self.memdc, 0, 0, width, height,
self.dc, x, y, 0x00CC0020):
raise Exception("BitBlt failed")
buf_size = width * height * 4
buffer = (ctypes.c_byte * buf_size)()
self.gdi32.GetDIBits(self.memdc, self.bitmap, 0, height, buffer,
ctypes.byref(self.bitmapinfo), 0)
array = np.frombuffer(buffer, dtype=np.uint8)
array = array.reshape(height, width, 4)
self.gdi32.DeleteObject(self.bitmap)
self.bitmap = None
return array
except Exception as e:
logging.error(f"BitBlt capture failed: {e}")
return None
def fast_nms(self, boxes, scores, iou_threshold=0.25):
if len(boxes) == 0:
return []
boxes_np = np.asarray(boxes, dtype=np.float32)
scores_np = np.asarray(scores, dtype=np.float32)
indices = np.argsort(scores_np)[::-1]
keep = []
while indices.size > 0:
current = indices[0]
keep.append(current)
if indices.size == 1:
break
remaining = indices[1:]
current_box = boxes_np[current]
remaining_boxes = boxes_np[remaining]
# compute IoU
x1 = np.maximum(current_box[0], remaining_boxes[:, 0])
y1 = np.maximum(current_box[1], remaining_boxes[:, 1])
x2 = np.minimum(current_box[2], remaining_boxes[:, 2])
y2 = np.minimum(current_box[3], remaining_boxes[:, 3])
inter_area = np.maximum(0, x2 - x1) * np.maximum(0, y2 - y1)
current_area = (current_box[2] - current_box[0]) * (current_box[3] - current_box[1])
remaining_area = (remaining_boxes[:, 2] - remaining_boxes[:, 0]) * (remaining_boxes[:, 3] - remaining_boxes[:, 1])
union = current_area + remaining_area - inter_area
iou = inter_area / np.maximum(union, 1e-10)
indices = remaining[iou <= iou_threshold]
return keep
def transform_coordinates(self, boxes, crop_x, crop_y, scale_x, scale_y):
transformed = []
for box in boxes:
x1, y1, x2, y2 = box
x1_screen = int(x1 * scale_x + crop_x)
y1_screen = int(y1 * scale_y + crop_y)
x2_screen = int(x2 * scale_x + crop_x)
y2_screen = int(y2 * scale_y + crop_y)
transformed.append((x1_screen, y1_screen, x2_screen, y2_screen))
return transformed
def run(self):
self.running = True
if not self.yolo_ensemble.models:
logging.error("No models loaded")
return
if not self.setup_bitblt():
logging.error("BitBlt setup failed")
return
self.screen_width = self.user32.GetSystemMetrics(0)
self.screen_height = self.user32.GetSystemMetrics(1)
self.center_x = self.screen_width >> 1
self.center_y = self.screen_height >> 1
logging.info(f"Detection started: {self.screen_width}x{self.screen_height}")
last_time = time.perf_counter()
try:
while self.running:
current_time = time.perf_counter()
fov_radius = clamp(self.settings.get('fov_radius', 150), 50,
min(self.screen_width, self.screen_height) >> 1)
crop_x = max(self.center_x - fov_radius, 0)
crop_y = max(self.center_y - fov_radius, 0)
crop_width = min(fov_radius * 2, self.screen_width - crop_x)
crop_height = min(fov_radius * 2, self.screen_height - crop_y)
if crop_width < 100 or crop_height < 100:
continue
frame = self.capture_screen_region(crop_x, crop_y, crop_width, crop_height)
if frame is None or frame.size == 0:
continue
frame = np.ascontiguousarray(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2RGB)
conf_thres = clamp(self.settings.get('confidence', 0.5), 0.2, 0.95)
all_results = self.yolo_ensemble.predict(frame, conf_thres=conf_thres)
detections = []
for results in all_results:
if not hasattr(results, 'boxes'):
continue
if results.boxes.xyxy.shape[0] == 0:
continue
boxes = results.boxes.xyxy.cpu().numpy()
confs = results.boxes.conf.cpu().numpy()
classes = results.boxes.cls.cpu().numpy()
scale_x = getattr(results, 'scale_x', 1.0)
scale_y = getattr(results, 'scale_y', 1.0)
screen_boxes = self.transform_coordinates(boxes, crop_x, crop_y, scale_x, scale_y)
for i, (box, conf, cls) in enumerate(zip(screen_boxes, confs, classes)):
if conf < conf_thres:
continue
x1_s, y1_s, x2_s, y2_s = box
if x1_s >= x2_s or y1_s >= y2_s or x1_s < 0 or y1_s < 0 or x2_s > self.screen_width or y2_s > self.screen_height:
continue
class_id = int(cls)
class_name = self.yolo_ensemble.names.get(class_id, "person")
# Distance check from center for FOV radius
det_center_x = (x1_s + x2_s) >> 1
det_center_y = (y1_s + y2_s) >> 1
dx = det_center_x - self.center_x
dy = det_center_y - self.center_y
dist_sq = dx*dx + dy*dy
if dist_sq <= fov_radius * fov_radius:
detections.append((x1_s, y1_s, x2_s, y2_s, float(conf), class_name))
detections.sort(key=lambda x: x[4], reverse=True)
boxes = [(d[0], d[1], d[2], d[3]) for d in detections]
confidences = [d[4] for d in detections]
labels = [d[5] for d in detections]
if boxes:
selected_indices = self.fast_nms(boxes, confidences, iou_threshold=0.25)
boxes = [boxes[i] for i in selected_indices]
labels = [labels[i] for i in selected_indices]
confidences = [confidences[i] for i in selected_indices]
dets_for_sort = np.array([[*box, conf] for box, conf in zip(boxes, confidences)]) if boxes else np.empty((0, 5))
tracked_objects = self.tracker.update(dets_for_sort)
tracked_boxes = []
track_ids = []
for obj in tracked_objects:
x1t, y1t, x2t, y2t, track_id = obj
x1t, y1t, x2t, y2t = map(int, (x1t, y1t, x2t, y2t))
if x1t < x2t and y1t < y2t and 0 <= x1t < self.screen_width and 0 <= y1t < self.screen_height and x2t <= self.screen_width and y2t <= self.screen_height:
tracked_boxes.append((x1t, y1t, x2t, y2t))
track_ids.append(int(track_id))
self.detection_signal.emit(tracked_boxes, labels, confidences, labels, track_ids)
self.frame_skip += 1
if self.frame_skip >= 200:
fps = 1.0 / max(0.001, current_time - last_time)
logging.info(f"Detection FPS: {fps:.1f}, Detections: {len(tracked_boxes)}")
self.frame_skip = 0
last_time = current_time
except Exception as e:
logging.error(f"Detection error: {e}")
finally:
self.cleanup_bitblt()
def stop(self):
self.running = False
self.cleanup_bitblt()
logging.info("Detection stopped")
How to use
settings = {
"fov_radius": 150,
"confidence": 0.5
}
detection_thread = DetectionThread(settings)
detection_thread.start()
# To stop thread:
# detection_thread.stop()
# detection_thread.wait()
What you need to verify and possibly customize:
NUM_CLASSES in YOLOEnsemble to match your model classes count.
- Your ONNX model's actual output shape and channels, update
postprocess accordingly.
- Model path and input image size in
model_paths list.
- Detections class names dictionary
names if you want more classes.
- Your real SORT tracker import and usage (replace dummy
Sort).
If your ONNX model uses a different output format, please provide the exact model output shape and values so I can help further customize the postprocess function.
This code keeps your design, threading, detection signal, bitblt input capture, and achieves ONNX+DirectML with proper decoding for YOLO-typical outputs.
Let me know if you want to improve error handling, performance details, or adapt for different ONNX exports!