|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | + |
| 4 | + |
| 5 | +yolo_net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg') |
| 6 | + |
| 7 | + |
| 8 | +class_names = [] |
| 9 | +with open('coco.names', 'r') as f: |
| 10 | + class_names = f.read().strip().split('\n') |
| 11 | + |
| 12 | + |
| 13 | +video_capture = cv2.VideoCapture('video_file.mp4') |
| 14 | + |
| 15 | +while video_capture.isOpened(): |
| 16 | + ret, frame = video_capture.read() |
| 17 | + if not ret: |
| 18 | + break |
| 19 | + |
| 20 | + height, width, _ = frame.shape |
| 21 | + |
| 22 | + |
| 23 | + blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False) |
| 24 | + yolo_net.setInput(blob) |
| 25 | + |
| 26 | + layer_names = yolo_net.getUnconnectedOutLayersNames() |
| 27 | + outs = yolo_net.forward(layer_names) |
| 28 | + |
| 29 | + for out in outs: |
| 30 | + for detection in out: |
| 31 | + scores = detection[5:] |
| 32 | + |
| 33 | + class_id = np.argmax(scores) |
| 34 | + confidence = scores[class_id] |
| 35 | + if confidence > 0.5 and class_id == 2: |
| 36 | + center_x = int(detection[0] * width) |
| 37 | + |
| 38 | + center_y = int(detection[1] * height) |
| 39 | + bbox_width = int(detection[2] * width) |
| 40 | + |
| 41 | + bbox_height = int(detection[3] * height) |
| 42 | + |
| 43 | + x = int(center_x - bbox_width / 2) |
| 44 | + y = int(center_y - bbox_height / 2) |
| 45 | + cv2.rectangle(frame, (x, y), (x + bbox_width, y + bbox_height), (0, 255, 0), 2) |
| 46 | + |
| 47 | + |
| 48 | + resized_frame = cv2.resize(frame, (720, 480)) |
| 49 | + |
| 50 | + cv2.imshow('Car Tracking', frame) |
| 51 | + |
| 52 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 53 | + break |
| 54 | + |
| 55 | +video_capture.release() |
| 56 | +cv2.destroyAllWindows() |
0 commit comments