Why am I getting this error for YOLO webcam object detection in python?

1.3k Views Asked by At

I am trying to make object detection in python using OpenCV and Yolov3. But for some reason I am getting this error:

cv2.error: OpenCV(4.3.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-6cwppm05\opencv\modules\dnn\src\darknet\darknet_io.cpp:601: error: (-215:Assertion failed) separator_index < line.size() in function 'cv::dnn::darknet::ReadDarknetFromCfgStream'

This is the code:

import cv2
import numpy as np
net = cv2.dnn.readNet('yolov3.cfg', 'yolov3.weights')
classes = []
with open('coco.names', 'r') as f:
    classes = f.read().splitlines()
cap = cv2.VideoCapture(0)
while True:
    _, img = cap.read()
    height, width, _ = img.shape
    blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), (0, 0, 0), swapRB=True, crop=False)
    net.setInput(blob)
    output_layers_names = net.getUnconnectedOutLayersNames()
    layerOutputs = net.forward(output_layers_names)
    boxes = []
    confidence = []
    class_ids = []
    for output in layerOutputs:
        for detection in output:
            scores = detection[5:]
            class_id = np.argmax(scores)
            if confidence > 0.5:
                center_x = int(detection[0]*width)
                center_y = int(detection[1]*height)
                w = int(detection[2]*width)
                h = int(detection[3]*height)
                x = int(center_x - w/2)
                y = int(center_y - h/2)
                boxes.append([x, y, w, h])
                confidence.append((float(confidence)))
                class_ids.append(class_id)
    indexes = cv2.dnn.NMSBoxes(boxes, confidence, 0.5, 0.4)
    font = cv2.FONT_HERSHEY_PLAIN
    colors = np.random.uniform(0, 255, size=(len(boxes), 3))
    if len(indexes)>0:
        for i in indexes.flatten():
            x,y,w,h = boxes[i]
            label = str(classes[class_ids[i]])
            confidence = str(round(confidence[i], 2))
            color = colors[i]
            cv2.rectangle(img, (x, y), (x+w, y+h), color, 2)
            cv2.putText(img, label + '' + confidence, (x, y+20), font, 2, (255, 255, 255), 2)
    cv2.imshow("Video", img)
    if cv2.waitKey(0) & 0xFF == ord('q'):
        break

I am new to OpenCV and Python so can someone please help me?

1

There are 1 best solutions below

1
On BEST ANSWER

Based on the error you're getting, I'd suggest you try this in line 3:

net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')

And make sure the .cfg and .weights files are in the same dir you're running your python script from.

Check the docs

Also make sure your cfg file is correct. This is what it should look like/