1+ import cv2
2+ import numpy as np
3+
4+ class Detector :
5+ def __init__ (self , config , weights , classes ):
6+ self .net = cv2 .dnn .readNet (weights , config )
7+ self .output_layers = self .net .getUnconnectedOutLayersNames ()
8+ self .scale = 0.00392
9+ self .conf_threshold = 0.5
10+ self .nms_threshold = 0.4
11+
12+ with open (classes , 'r' ) as f :
13+ self .classes = [line .strip () for line in f .readlines ()]
14+
15+ self .colors = np .random .uniform (0 , 255 , size = (len (self .classes ), 3 ))
16+
17+ def detect (self , image ):
18+ H , W , _ = image .shape
19+ blob = cv2 .dnn .blobFromImage (image , self .scale , (416 ,416 ), (0 ,0 ,0 ), True , crop = False )
20+ self .net .setInput (blob )
21+ outs = self .net .forward (self .output_layers )
22+
23+ class_ids = []
24+ confidences = []
25+ boxes = []
26+
27+ for out in outs :
28+ for detection in out :
29+ scores = detection [5 :]
30+ class_id = np .argmax (scores )
31+ confidence = scores [class_id ]
32+ if confidence > self .conf_threshold :
33+ center_x = int (detection [0 ] * W )
34+ center_y = int (detection [1 ] * H )
35+ w = int (detection [2 ] * W )
36+ h = int (detection [3 ] * H )
37+ x = center_x - w / 2
38+ y = center_y - h / 2
39+ class_ids .append (class_id )
40+ confidences .append (float (confidence ))
41+ boxes .append ([x , y , w , h ])
42+
43+ indices = cv2 .dnn .NMSBoxes (boxes , confidences , self .conf_threshold , self .nms_threshold )
44+
45+ for i in indices :
46+ box = boxes [i ]
47+ x = box [0 ]
48+ y = box [1 ]
49+ w = box [2 ]
50+ h = box [3 ]
51+
52+ self .draw_bounding_box (image , class_ids [i ], round (x ), round (y ), round (x + w ), round (y + h ))
53+
54+ return image
55+
56+ def draw_bounding_box (self , img , class_id , x , y , x_plus_w , y_plus_h ):
57+ label = str (self .classes [class_id ])
58+ color = self .colors [class_id ]
59+ cv2 .rectangle (img , (x ,y ), (x_plus_w ,y_plus_h ), color , 2 )
60+ cv2 .putText (img , label , (x - 10 ,y - 10 ), cv2 .FONT_HERSHEY_SIMPLEX , 0.5 , color , 2 )
61+
62+ def show (self , image ):
63+ cv2 .imshow ('Object Detection' , image )
64+ cv2 .waitKey (0 )
65+ cv2 .destroyAllWindows ()
66+
67+ def export (self , image , path ):
68+ cv2 .imwrite (path , image )
0 commit comments