MMUZAMMUL123 commited on
Commit
53dc77b
·
verified ·
1 Parent(s): 160a676

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +42 -0
utils.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+ def get_class_color(class_id):
5
+ """Generates a consistent color for each class ID."""
6
+ np.random.seed(class_id)
7
+ return tuple(np.random.randint(0, 255, 3).tolist())
8
+
9
+ def draw_box(frame, x1, y1, x2, y2, conf, class_id, class_name):
10
+ """Draws a bounding box and label on the frame (BGR format)."""
11
+ x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
12
+ color = get_class_color(class_id)
13
+ label = f"{class_name} {conf:.2f}"
14
+
15
+ cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
16
+ cv2.putText(frame, label, (x1, max(0, y1 - 10)),
17
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
18
+
19
+ def apply_nms(boxes, iou_thresh=0.4):
20
+ """
21
+ Applies Non-Maximum Suppression (NMS) to filter overlapping bounding boxes.
22
+ """
23
+ if not boxes:
24
+ return []
25
+
26
+ xywh = []
27
+ confs = []
28
+ for b in boxes:
29
+ x1, y1, x2, y2, c, cid, cname = b
30
+ w = x2 - x1
31
+ h = y2 - y1
32
+ xywh.append([x1, y1, w, h])
33
+ confs.append(c)
34
+
35
+ xywh = np.array(xywh)
36
+ confs = np.array(confs)
37
+
38
+ idxs = cv2.dnn.NMSBoxes(xywh.tolist(), confs.tolist(), 0.25, iou_thresh)
39
+ if idxs is None or len(idxs) == 0:
40
+ return []
41
+
42
+ return [boxes[i] for i in idxs.flatten()]