11import cv2
2- import numpy as np
2+ from ultralytics import YOLO
33
44class 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 ))
5+ def __init__ (self ):
6+ self .classNames = ["person" , "bicycle" , "car" , "motorbike" , "aeroplane" , "bus" , "train" , "truck" , "boat" ,
7+ "traffic light" , "fire hydrant" , "stop sign" , "parking meter" , "bench" , "bird" , "cat" ,
8+ "dog" , "horse" , "sheep" , "cow" , "elephant" , "bear" , "zebra" , "giraffe" , "backpack" , "umbrella" ,
9+ "handbag" , "tie" , "suitcase" , "frisbee" , "skis" , "snowboard" , "sports ball" , "kite" , "baseball bat" ,
10+ "baseball glove" , "skateboard" , "surfboard" , "tennis racket" , "bottle" , "wine glass" , "cup" ,
11+ "fork" , "knife" , "spoon" , "bowl" , "banana" , "apple" , "sandwich" , "orange" , "broccoli" ,
12+ "carrot" , "hot dog" , "pizza" , "donut" , "cake" , "chair" , "sofa" , "pottedplant" , "bed" ,
13+ "diningtable" , "toilet" , "tvmonitor" , "laptop" , "mouse" , "remote" , "keyboard" , "cell phone" ,
14+ "microwave" , "oven" , "toaster" , "sink" , "refrigerator" , "book" , "clock" , "vase" , "scissors" ,
15+ "teddy bear" , "hair drier" , "toothbrush"
16+ ]
17+ self .model = YOLO ("yolov8/yolov8n.pt" , verbose = False )
18+ self .people = 0
19+
5320
54- return image
21+ def stream (self , callback , show = True ):
22+ cap = cv2 .VideoCapture (0 )
23+ cap .set (3 , 640 )
24+ cap .set (4 , 480 )
25+
26+ while True :
27+ ret , frame = cap .read ()
28+ if not ret :
29+ break
30+
31+ results = self .model (frame , stream = True )
32+ self .people = 0
33+ for result in results :
34+ boxes = result .boxes
35+ for box in boxes :
36+ cls = int (box .cls [0 ])
37+ if self .classNames [cls ] == "person" :
38+ self .people += 1
39+
40+ if show and self .classNames [cls ] == "person" :
41+ x , y , w , h = box .xyxy [0 ]
42+ x , y , w , h = int (x ), int (y ), int (w ), int (h )
43+ cv2 .rectangle (frame , (x , y ), (w , h ), (0 , 255 , 0 ), 2 )
44+
45+ cv2 .putText (frame , self .classNames [cls ], (x , y - 10 ), cv2 .FONT_HERSHEY_SIMPLEX , 0.9 , (36 ,255 ,12 ), 2 )
5546
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 )
47+ callback (self .people )
6148
62- def show ( self , image ) :
63- cv2 .imshow ('Object Detection' , image )
64- cv2 .waitKey (0 )
65- cv2 . destroyAllWindows ()
49+ if show :
50+ cv2 .imshow ("Frame" , frame )
51+ if cv2 .waitKey (1 ) & 0xFF == ord ( "q" ):
52+ break
6653
67- def export ( self , image , path ):
68- cv2 .imwrite ( path , image )
54+ cap . release ()
55+ cv2 .destroyAllWindows ( )
0 commit comments