import cv2 import numpy as np def get_class_color(class_id): """Generates a consistent color for each class ID.""" np.random.seed(class_id) return tuple(np.random.randint(0, 255, 3).tolist()) def draw_box(frame, x1, y1, x2, y2, conf, class_id, class_name): """Draws a bounding box and label on the frame (BGR format).""" x1, y1, x2, y2 = map(int, [x1, y1, x2, y2]) color = get_class_color(class_id) label = f"{class_name} {conf:.2f}" cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) cv2.putText(frame, label, (x1, max(0, y1 - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) def apply_nms(boxes, iou_thresh=0.4): """ Applies Non-Maximum Suppression (NMS) to filter overlapping bounding boxes. """ if not boxes: return [] xywh = [] confs = [] for b in boxes: x1, y1, x2, y2, c, cid, cname = b w = x2 - x1 h = y2 - y1 xywh.append([x1, y1, w, h]) confs.append(c) xywh = np.array(xywh) confs = np.array(confs) idxs = cv2.dnn.NMSBoxes(xywh.tolist(), confs.tolist(), 0.25, iou_thresh) if idxs is None or len(idxs) == 0: return [] return [boxes[i] for i in idxs.flatten()]