Object Detection using yolov4 and opencv in python error: cv2.error: bad allocation I am getting this error while using yolov4

68 Views Asked by At

detections = net.forward(layer_names) cv2.error: bad allocation

I am getting this error while using yolov4 model https://github.com/AlexeyAB/darknet

Please do help me out

import cv2
import numpy as np

# Load YOLOv4 model and configuration
net = cv2.dnn.readNet("C:/Users/256918/Downloads/yolov4.weights", "C:/Users/256918/Downloads/yolov4.cfg")

# Load COCO classes
with open("C:/Users/256918/Downloads/coco (1).names", "r") as f:
    classes = f.read().strip().split("\n")

# Open a video file or use the webcam (change the path accordingly)
cap = cv2.VideoCapture("vid4.mp4")

while True:
    ret, frame = cap.read()
    if not ret:
        print("hello")
        break

    # Detect objects in the frame
    blob = cv2.dnn.blobFromImage(frame, 1/255.0, (608, 608), (0, 0, 0), swapRB=True, crop=False)
    net.setInput(blob)
    layer_names = net.getUnconnectedOutLayersNames()
    detections = net.forward(layer_names)

    # Process detections
    for detection in detections:
        for obj in detection:
            scores = obj[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]

            if confidence > 0.5:
                # Get object coordinates
                center_x = int(obj[0] * frame.shape[1])
                center_y = int(obj[1] * frame.shape[0])
                width = int(obj[2] * frame.shape[1])
                height = int(obj[3] * frame.shape[0])

                # Calculate bounding box coordinates
                x = int(center_x - width / 2)
                y = int(center_y - height / 2)

                # Draw bounding box and label
                color = (0, 255, 0)  # Green color for bounding box
                cv2.rectangle(frame, (x, y), (x + width, y + height), color, 2)
                label = f"{classes[class_id]}: {confidence:.2f}"
                cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    # Display the output frame
    cv2.imshow("Object Detection", frame)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# Release the video capture and close the OpenCV windows
cap.release()
cv2.destroyAllWindows()

I am running it on a system without GPU but 18gb ram is this the reason? I am using the configuration and weights file from the https://github.com/AlexeyAB/darknet but I don't have the full darknet is this the reason?

I only took the yolov4.cfg and yolov4.weights from that git.

I was expecting to get object detection i.e., bounding box on detected objects with their class names and confidence.

0

There are 0 best solutions below