Memory Crash when running object identification on videos using yolov4 in python

Viewed 24

I'm running the following code that loops through frames in a video and identifies objects using the yolov4 weights, classes and config files. however this works as expected for a few frames until it causes my PC to crash and I'm unsure where the memory leak is occurring. Below is the code I'm using. Is there a way to fix this issue?

import numpy as np
import cv2

#load classes
LABELS = open("coco.names").read().strip().split("\n")
np.random.seed(42)
net = cv2.dnn.readNetFromDarknet("yolov4.cfg","yolov4.weights")
capture = cv2.VideoCapture('testcut.mp4')

if not capture.isOpened():
    print('Unable to open video')
    exit(0)

cy = 540

while True:
    ret, frame = capture.read()
    if frame is None:
        break
    #crop frame
    frame = frame[cy:,:]  
    H, W = frame.shape[:2]
    ln = net.getLayerNames()
    ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),swapRB=True, crop=False)
    net.setInput(blob)
    layerOutputs = net.forward(ln)
    boxes = []
    confidences = []
    classIDs = []
    for output in layerOutputs:
        # loop over each of the detections
        for detection in output:
            # extract the class ID and confidence (i.e., probability) of
            # the current object detection
            scores = detection[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            # filter out weak predictions by ensuring the detected
            # probability is greater than the minimum probability
            if confidence > 0.5:
                # scale the bounding box coordinates back relative to the
                # size of the image, keeping in mind that YOLO actually
                # returns the center (x, y)-coordinates of the bounding
                # box followed by the boxes' width and height
                box = detection[0:4] * np.array([W, H, W, H])
                (centerX, centerY, width, height) = box.astype("int")
                # use the center (x, y)-coordinates to derive the top and
                # and left corner of the bounding box
                x = int(centerX - (width / 2))
                y = int(centerY - (height / 2))
                # update our list of bounding box coordinates, confidences,
                # and class IDs
                boxes.append([x, y, int(width), int(height)])
                confidences.append(float(confidence))
                classIDs.append(classID)
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.6,0.3)
    # ensure at least one detection exists
    if len(idxs) > 0:
        # loop over the indexes we are keeping
        for i in idxs.flatten():
            # extract the bounding box coordinates
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])
            # draw a bounding box rectangle and label on the image
            color = (0,255,0)
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
            cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 2)
    cv2.imshow("H", frame)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
capture.release()
cv2.destroyAllWindows()
0 Answers
Related