|
| 1 | +#Install Dependencies |
| 2 | +# !python3 -m pip install depthai |
| 3 | + |
| 4 | +import os |
| 5 | +import json |
| 6 | +import numpy as np |
| 7 | +import cv2 |
| 8 | +from pathlib import Path |
| 9 | +import depthai as dai |
| 10 | +import time |
| 11 | + |
| 12 | +# Define path to the model, test data directory, and results |
| 13 | + |
| 14 | +YOLOV8N_MODEL = "/home/jaykumaran/Blogs/Poth-hole-Detection/Final Media/Yolov8-2022.1-blob/yolov8n-pothole-best_openvino_2022.1_8shave.blob" #Adjust path accordingly |
| 15 | +YOLOV8N_CONFIG = "/home/jaykumaran/Blogs/Poth-hole-Detection/Final Media/Yolov8-2022.1-blob/yolov8n-pothole-best.json" #Adjust path accordingly |
| 16 | + |
| 17 | +INPUT_VIDEO = "videoplayback.mp4" |
| 18 | +OUTPUT_VIDEO = "vid_result/960-oak-d-videoplayback_video.mp4" |
| 19 | + |
| 20 | +CAMERA_PREV_DIM = (960, 960) |
| 21 | +LABELS = ["Pot-hole"] |
| 22 | + |
| 23 | +def load_config(config_path): |
| 24 | + with open(config_path) as f: |
| 25 | + return json.load(f) |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +def create_image_pipeline(config_path, model_path): |
| 30 | + pipeline = dai.Pipeline() |
| 31 | + model_config = load_config(config_path) |
| 32 | + nnConfig = model_config.get("nn_config", {}) |
| 33 | + metadata = nnConfig.get("NN_specific_metadata", {}) |
| 34 | + classes = metadata.get("classes", {}) |
| 35 | + coordinates = metadata.get("coordinates", {}) |
| 36 | + anchors = metadata.get("anchors", {}) |
| 37 | + anchorMasks = metadata.get("anchor_masks", {}) |
| 38 | + iouThreshold = metadata.get("iou_threshold", {}) |
| 39 | + confidenceThreshold = metadata.get("confidence_threshold", {}) |
| 40 | + |
| 41 | + detectionIN = pipeline.create(dai.node.XLinkIn) |
| 42 | + detectionNetwork = pipeline.create(dai.node.YoloDetectionNetwork) |
| 43 | + nnOut = pipeline.create(dai.node.XLinkOut) |
| 44 | + |
| 45 | + nnOut.setStreamName("nn") |
| 46 | + detectionIN.setStreamName("detection_in") |
| 47 | + |
| 48 | + detectionNetwork.setConfidenceThreshold(confidenceThreshold) |
| 49 | + detectionNetwork.setNumClasses(classes) |
| 50 | + detectionNetwork.setCoordinateSize(coordinates) |
| 51 | + detectionNetwork.setAnchors(anchors) |
| 52 | + detectionNetwork.setAnchorMasks(anchorMasks) |
| 53 | + detectionNetwork.setIouThreshold(iouThreshold) |
| 54 | + detectionNetwork.setBlobPath(model_path) |
| 55 | + detectionNetwork.setNumInferenceThreads(2) |
| 56 | + detectionNetwork.input.setBlocking(False) |
| 57 | + # Linking |
| 58 | + detectionIN.out.link(detectionNetwork.input) |
| 59 | + detectionNetwork.out.link(nnOut.input) |
| 60 | + |
| 61 | + return pipeline |
| 62 | + |
| 63 | +def annotate_frame(frame, detections, fps): |
| 64 | + color = (0, 0, 255) |
| 65 | + for detection in detections: |
| 66 | + bbox = frame_norm(frame, (detection.xmin, detection.ymin, detection.xmax, detection.ymax)) |
| 67 | + cv2.putText(frame, LABELS[detection.label], (bbox[0] + 10, bbox[1] + 25), cv2.FONT_HERSHEY_TRIPLEX, 1, color) |
| 68 | + cv2.putText(frame, f"{int(detection.confidence * 100)}%", (bbox[0] + 10, bbox[1] + 60), cv2.FONT_HERSHEY_TRIPLEX, 1, color) |
| 69 | + cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 2) |
| 70 | + |
| 71 | + # Annotate the frame with the FPS |
| 72 | + cv2.putText(frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) |
| 73 | + return frame |
| 74 | + |
| 75 | +def to_planar(arr: np.ndarray, shape: tuple) -> np.ndarray: |
| 76 | + resized = cv2.resize(arr, shape) |
| 77 | + return resized.transpose(2, 0, 1) |
| 78 | + |
| 79 | +def frame_norm(frame, bbox): |
| 80 | + norm_vals = np.full(len(bbox), frame.shape[0]) |
| 81 | + norm_vals[::2] = frame.shape[1] |
| 82 | + return (np.clip(np.array(bbox), 0, 1) * norm_vals).astype(int) |
| 83 | + |
| 84 | +# Create pipeline |
| 85 | +pipeline = create_image_pipeline(YOLOV8N_CONFIG, YOLOV8N_MODEL) |
| 86 | + |
| 87 | +# Ensure output directory exists |
| 88 | +os.makedirs(os.path.dirname(OUTPUT_VIDEO), exist_ok=True) |
| 89 | + |
| 90 | +cap = cv2.VideoCapture(INPUT_VIDEO) |
| 91 | +frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) |
| 92 | +frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
| 93 | +fps = cap.get(cv2.CAP_PROP_FPS) |
| 94 | +out = cv2.VideoWriter(OUTPUT_VIDEO, cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height)) |
| 95 | + |
| 96 | +# Connect to device and start pipeline |
| 97 | +with dai.Device(pipeline) as device: |
| 98 | + # Define the queues that will be used in order to communicate with depthai |
| 99 | + detectionIN = device.getInputQueue("detection_in") |
| 100 | + detectionNN = device.getOutputQueue("nn") |
| 101 | + |
| 102 | + start_time = time.time() |
| 103 | + frame_count = 0 |
| 104 | + |
| 105 | + while cap.isOpened(): |
| 106 | + ret, frame = cap.read() |
| 107 | + if not ret: |
| 108 | + break |
| 109 | + |
| 110 | + frame_count += 1 |
| 111 | + |
| 112 | + image_res = cv2.resize(frame, CAMERA_PREV_DIM) |
| 113 | + |
| 114 | + # Initialize depthai NNData() class which is fed with the image data resized and transposed to model input shape |
| 115 | + nn_data = dai.NNData() |
| 116 | + nn_data.setLayer("input", to_planar(frame, CAMERA_PREV_DIM)) |
| 117 | + |
| 118 | + # Send the image to detectionIN queue further passed to the detection network for inference as defined in pipeline |
| 119 | + detectionIN.send(nn_data) |
| 120 | + |
| 121 | + # Fetch the neural network output |
| 122 | + inDet = detectionNN.get() |
| 123 | + detections = [] |
| 124 | + if inDet is not None: |
| 125 | + detections = inDet.detections |
| 126 | + print("Detections", detections) |
| 127 | + |
| 128 | + # Calculate the FPS |
| 129 | + elapsed_time = time.time() - start_time |
| 130 | + fps = frame_count / elapsed_time if elapsed_time > 0 else 0 |
| 131 | + |
| 132 | + # Annotate the frame with detections and FPS |
| 133 | + frame = annotate_frame(frame, detections, fps) |
| 134 | + |
| 135 | + out.write(frame) |
| 136 | + |
| 137 | +cap.release() |
| 138 | +out.release() |
| 139 | + |
| 140 | +print(f"[INFO] Processed video {INPUT_VIDEO} and saved to {OUTPUT_VIDEO}") |
0 commit comments