|
| 1 | +import numpy as np |
| 2 | +import imutils |
| 3 | +import cv2 |
| 4 | +import time |
| 5 | +from .config import MODEL_PATH, CONFIG_PATH, OUTPUT_PATH, COLORS, LABELS |
| 6 | + |
| 7 | + |
| 8 | +def detect_objects(video, confidence_threshold, nms_threshold): |
| 9 | + # get video frames and pass to YOLO for output |
| 10 | + |
| 11 | + # load YOLO from cv2.dnn |
| 12 | + # determine only the output layer names we need from YOLO |
| 13 | + net = cv2.dnn.readNetFromDarknet(CONFIG_PATH, MODEL_PATH) |
| 14 | + ln = net.getLayerNames() |
| 15 | + ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] |
| 16 | + |
| 17 | + # initialize video stream, pointer to output video file and grabbing frame dimension |
| 18 | + vs = cv2.VideoCapture(video) |
| 19 | + fps = vs.get(cv2.CAP_PROP_FPS) |
| 20 | + writer_width = int(vs.get(cv2.CAP_PROP_FRAME_WIDTH)) |
| 21 | + writer_height = int(vs.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
| 22 | + |
| 23 | + writer = None |
| 24 | + (W, H) = (None, None) |
| 25 | + |
| 26 | + # determine the total number of frames in a video |
| 27 | + try: |
| 28 | + prop = cv2.CAP_PROP_FRAME_COUNT if imutils.is_cv2() else cv2.CAP_PROP_FRAME_COUNT |
| 29 | + total = int(vs.get(prop)) |
| 30 | + print(f"[INFO] {total} frames in the video") |
| 31 | + |
| 32 | + # if error occurs print |
| 33 | + except: |
| 34 | + print(f"[INFO] {total} frames in the video") |
| 35 | + total = -1 |
| 36 | + |
| 37 | + # loop over on entire video frames |
| 38 | + while True: |
| 39 | + # read next frame |
| 40 | + (grabbed, frame) = vs.read() |
| 41 | + |
| 42 | + # if no frame is grabbed, we reached the end of video, so break the loop |
| 43 | + if not grabbed: |
| 44 | + break |
| 45 | + # if the frame dimensions are empty, grab them |
| 46 | + if W is None or H is None: |
| 47 | + (H, W) = frame.shape[:2] |
| 48 | + |
| 49 | + # build blob and feed forward to YOLO to get bounding boxes and probability |
| 50 | + blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False) |
| 51 | + start = time.time() |
| 52 | + net.setInput(blob) |
| 53 | + layerOutputs = net.forward(ln) |
| 54 | + end = time.time() |
| 55 | + |
| 56 | + # get metrics from YOLO |
| 57 | + |
| 58 | + boxes = [] |
| 59 | + confidences = [] |
| 60 | + classIDs = [] |
| 61 | + |
| 62 | + # loop over each output from layeroutputs |
| 63 | + for output in layerOutputs: |
| 64 | + # loop over each detecton in output |
| 65 | + for detection in output: |
| 66 | + # extract score, ids and confidence of current object detection |
| 67 | + score = detection[5:] |
| 68 | + classID = np.argmax(score) |
| 69 | + confidence = score[classID] |
| 70 | + |
| 71 | + # filter out weak detections with confidence threshold |
| 72 | + if confidence > confidence_threshold: |
| 73 | + # scale bounding box coordinates back relative to image size |
| 74 | + # YOLO spits out center (x,y) of bounding boxes followed by |
| 75 | + # boxes width and heigth |
| 76 | + box = detection[0:4] * np.array([W, H, W, H]) |
| 77 | + (centerX, centerY, width, height) = box.astype('int') |
| 78 | + |
| 79 | + # grab top left coordinate of the box |
| 80 | + x = int(centerX - (width / 2)) |
| 81 | + y = int(centerY - (height / 2)) |
| 82 | + |
| 83 | + boxes.append([x, y, int(width), int(height)]) |
| 84 | + confidences.append(float(confidence)) |
| 85 | + classIDs.append(classID) |
| 86 | + |
| 87 | + # Apply Non-Max Suppression, draw boxes and write output video |
| 88 | + |
| 89 | + idxs = cv2.dnn.NMSBoxes(boxes, confidences, confidence_threshold, nms_threshold) |
| 90 | + # ensure detection exists |
| 91 | + if len(idxs) > 0: |
| 92 | + for i in idxs.flatten(): |
| 93 | + # getting box coordinates |
| 94 | + (x, y) = (boxes[i][0], boxes[i][1]) |
| 95 | + (w, h) = (boxes[i][2], boxes[i][3]) |
| 96 | + |
| 97 | + # color and draw boxes |
| 98 | + color = [int(c) for c in COLORS[classIDs[i]]] |
| 99 | + cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) |
| 100 | + text = f"{LABELS[classIDs[i]]}: {confidences[i]}" |
| 101 | + cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) |
| 102 | + |
| 103 | + if writer is None: |
| 104 | + # initialize video writer by setting fourcc |
| 105 | + # and writing output video to output path |
| 106 | + # fourcc = cv2.VideoWriter_fourcc(*'H264') |
| 107 | + fourcc = cv2.VideoWriter_fourcc(*"mp4v") |
| 108 | + if not fourcc: |
| 109 | + break |
| 110 | + writer = cv2.VideoWriter(OUTPUT_PATH, fourcc, fps, (writer_width, writer_height), True) |
| 111 | + |
| 112 | + if total > 0: |
| 113 | + elap = (end - start) |
| 114 | + print(f"[INFO] single frame took {round(elap / 60, 2)} minutes") |
| 115 | + print(f"[INFO] total estimated time to finish: {(elap * total) / 60} minutes") |
| 116 | + |
| 117 | + writer.write(frame) |
| 118 | + |
| 119 | + writer.release() |
| 120 | + vs.release() |
| 121 | + |
| 122 | + return total, elap |
0 commit comments