0

I'm encountering a parsing error when attempting to load a YOLOv3 model using OpenCV 4.10.0 in Python. Specifically, the error occurs while trying to read the configuration file yolov3.cfg. Despite verifying that the file exists and is accessible, the error persists. The exact error message from OpenCV is:

darknet_importer.cpp:210: error: (-212:Parsing error) Failed to open NetParameter file: c:/Users/haege/Documents/PV/Projets/Projet Héron cendré/Codes\\yolov3.cfg in function 'cv::dnn::dnn4_v20240521::readNetFromDarknet'

I have verified the following:

The yolov3.cfg file exists at the specified path. File permissions are correct, and the file is accessible for reading. I've attempted different configurations and paths, but the error persists. Could someone help me diagnose why OpenCV is failing to parse yolov3.cfg correctly? Any insights or suggestions would be greatly appreciated.

I have attempted several troubleshooting steps to resolve the issue with loading the YOLOv3 model using OpenCV in Python:

File Verification: I verified that the yolov3.cfg configuration file exists at the specified path (c:/Users/haege/Documents/PV/Projets/Projet Héron cendré/Codes\\yolov3.cfg) and confirmed it is accessible for reading.

Permissions Check: I ensured that the file permissions are set correctly to allow reading from the yolov3.cfg file.

Alternative Configurations: I tried different configurations and paths for both the yolov3.weights and yolov3.cfg files to see if the error persisted with different setups.

OpenCV Version: I am using OpenCV 4.10.0, and I suspect there might be compatibility issues or specific requirements with this version that could be contributing to the parsing error.

What I expected:

I expected that after verifying the file existence, permissions, and trying different configurations, the YOLOv3 model would load successfully without encountering a parsing error in OpenCV. However, despite these efforts, the issue remains unresolved. I'm seeking assistance to understand why OpenCV is failing to parse the yolov3.cfg file correctly and how to fix it.

Here is my code :

import cv2
import numpy as np
from flask import Flask, request, jsonify
import os

# Check file paths and accessibility
base_path = "c:/Users/haege/Documents/PV/Projets/Projet Héron cendré/Codes"
weights_path = os.path.join(base_path, "yolov3.weights")
config_path = os.path.join(base_path, "yolov3.cfg")
names_path = os.path.join(base_path, "coco.names")

def check_file_access(path):
    if os.path.exists(path):
        print(f"The file exists : {path}")
        try:
            with open(path, 'r', encoding='latin-1') as file:
                print(f"The file {path} is available for reading.")
                for _ in range(5):
                    print(file.readline().strip())
        except IOError:
            print(f"The file {path} is not available for reading.")
    else:
        print(f"The file does not exist : {path}")

check_file_access(weights_path)
check_file_access(config_path)
check_file_access(names_path)

# Load YOLO model
net = None
try:
    net = cv2.dnn.readNet(weights_path, config_path)
    print("The model has been successfully loaded.")
except cv2.error as e:
    print(f"Error loading model : {e}")

if net is not None:
    # Load classes
    with open(names_path, "r", encoding='latin-1') as f:
        classes = [line.strip() for line in f.readlines()]

    # Get output layer names
    layer_names = net.getLayerNames()
    output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

    # Camera RTSP URL
    rtsp_url = '(rtsp://myurl)'

    # Video stream initialization
    cap = cv2.VideoCapture(rtsp_url)

    # Check if the video capture is open
    if not cap.isOpened():
        print("Error : Unable to open RTSP stream")
        exit()

    app = Flask(__name__)

    coordinates = None

    @app.route('/get_coordinates', methods=['GET'])
    def get_coordinates():
        global coordinates
        return jsonify(coordinates)

    def detect_objects(frame):
        height, width, _ = frame.shape
        blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
        net.setInput(blob)
        outs = net.forward(output_layers)

        class_ids = []
        confidences = []
        boxes = []

        for out in outs:
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.5:  # Seuil de confiance
                    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])
                    confidences.append(float(confidence))
                    class_ids.append(class_id)

        indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

        for i in range(len(boxes)):
            if i in indexes:
                x, y, w, h = boxes[i]
                label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
                cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
                return (x, y, w, h)  # Returns the coordinates of the detected object
        return None

    def detect_motion_and_objects():
        global coordinates

        while True:
            ret, frame = cap.read()
            if not ret:
                print("Error: Unable to play video stream")
                break

            coordinates = detect_objects(frame)

            cv2.imshow('Camera Feed', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()

    if __name__ == '__main__':
        from threading import Thread
        t = Thread(target=detect_motion_and_objects)
        t.daemon = True
        t.start()
        app.run(host='0.0.0.0', port=5000)
else:
    print("Unable to load YOLO model. Please check configuration files and paths.")
1
  • I'm guessing it's non-ascii in the path. Commented Jul 8 at 7:09

0