<h5 dir="auto">System information (version)</h5>

<ul dir="auto">
<li>OpenCV =&gt;4.4</li>
<li>Operating System / Platform =&gt; Windows 64 Bit</li>
<li>Compiler =&gt; Visual Studio 2017</li>
</ul>
<h5 dir="auto">Detailed description</h5>

<p dir="auto">I tried some models from <a href="https://github.com/AlexeyAB/darknet">https://github.com/AlexeyAB/darknet</a>，as listed bellow:</p>
<table role="table">
<thead>
<tr>
<th>模型</th>
<th>模型大小</th>
<th>FPS</th>
</tr>
</thead>
<tbody>
<tr>
<td>YOLOv2</td>
<td>194 MB</td>
<td>-</td>
</tr>
<tr>
<td>YOLOv2-tiny</td>
<td>43MB</td>
<td>15.3</td>
</tr>
<tr>
<td>YOLOv3</td>
<td>236 MB</td>
<td>1.3</td>
</tr>
<tr>
<td>YOLOv3-tiny</td>
<td>33.7 MB</td>
<td>13.3</td>
</tr>
<tr>
<td>YOLOv3-tiny-prn</td>
<td>18.8 MB</td>
<td>17.1</td>
</tr>
<tr>
<td>YOLOv3-SPP</td>
<td>240 MB</td>
<td>-</td>
</tr>
<tr>
<td>csresnext50-panet-spp-original-optimal_final</td>
<td>217 MB</td>
<td>1.8</td>
</tr>
<tr>
<td>YOLOv4</td>
<td>245 MB</td>
<td>1.2</td>
</tr>
<tr>
<td>YOLOV4-tiny</td>
<td>23.1 MB</td>
<td>9.8</td>
</tr>
<tr>
<td>enet-coco</td>
<td>18.3 MB</td>
<td>4.9</td>
</tr>
</tbody>
</table>
<p dir="auto">It failed to load <code class="notranslate">yolov3-spp</code> and <code class="notranslate">yolov2</code> using the same code as other models uesd.</p>
<h5 dir="auto">Steps to reproduce</h5>

<p dir="auto">The code is listed bellow:</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="import cv2
import matplotlib.pyplot as plt
import time
import numpy as np
coco_names = r&quot;F:\opencv\sources\samples\dnn\coco.names&quot;

model_yolov2 = r&quot;F:\opencv\sources\samples\dnn\yolov2.weights&quot;
cfg_yolov2 = r&quot;F:\opencv\sources\samples\dnn\yolov2.cfg&quot;

model_yolov2_tiny = r&quot;E:\MachineLearning\darknet\yolov2-tiny.weights&quot;
cfg_yolov2_tiny = &quot;E:\MachineLearning\darknet\cfg\yolov2-tiny.cfg&quot;

model_yolov3 = r&quot;F:\opencv\sources\samples\dnn\yolov3.weights&quot;
cfg_yolov3 = r&quot;F:\opencv\sources\samples\dnn\yolov3.cfg&quot;

model_yolov3_tiny = r&quot;E:\MachineLearning\darknet\yolov3-tiny.weights&quot;
cfg_yolov3_tiny = &quot;E:\MachineLearning\darknet\cfg\yolov3-tiny.cfg&quot;

model_yolov3_tiny_prn = r&quot;E:\MachineLearning\darknet\yolov3-tiny-prn.weights&quot;
cfg_yolov3_tiny_prn = &quot;E:\MachineLearning\darknet\cfg\yolov3-tiny-prn.cfg&quot;

model_yolov3_spp = r&quot;F:\opencv\sources\samples\dnn\yolov3-spp.weights&quot;
cfg_yolov3_spp = r&quot;F:\opencv\sources\samples\dnn\yolov3-spp.cfg&quot;

csresnext_model = r&quot;E:\MachineLearning\darknet\csresnext50-panet-spp-original-optimal_final.weights&quot;
csresnext_cfg = r&quot;E:\MachineLearning\darknet\cfg\csresnext50-panet-spp-original-optimal.cfg&quot;

model_yolov4 = r&quot;F:\opencv\sources\samples\dnn\yolov4.weights&quot;
cfg_yolov4 = r&quot;F:\opencv\sources\samples\dnn\yolov4.cfg&quot;

model_yolov4_tiny = r&quot;E:\MachineLearning\darknet\yolov4-tiny.weights&quot;
cfg_yolov4_tiny = &quot;E:\MachineLearning\darknet\cfg\yolov4-tiny.cfg&quot;

enet_model = r&quot;E:\MachineLearning\darknet\enetb0-coco_final.weights&quot;
enet_cfg = r&quot;E:\MachineLearning\darknet\cfg\enet-coco.cfg&quot;

img_file = r&quot;C:\Users\admin\Pictures\car.jpg&quot;
video_file = r'F:/opencv-4.4.0/samples/data/vtest.avi'

model = model_yolov3_spp
cfg = cfg_yolov3_spp

with open(coco_names,'rt') as f:
    names = f.read().rstrip('\n').split('\n')

def det_image_v1(model, cfg, img_file, c_threshold=0.5, nms=0.5):
    
    classes = names
    # initialize a list of colors to represent each possible class label
    COLORS = np.random.randint(0, 255, size=(len(classes), 3),dtype=&quot;uint8&quot;)
    
    print(&quot;[INFO] loading model...&quot;)
    net = cv2.dnn.readNetFromDarknet(cfg, model)
    
    # load the input image and construct an input blob for the image
    # by resizing to a fixed 300x300 pixels and then normalizing it
    image = cv2.imread(img_file)
    (H,W) = image.shape[:2]

    # Get the names of output layers
    ln = net.getLayerNames()
    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    
    # generate blob for image input to the network
    blob = cv2.dnn.blobFromImage(image,1/255,(416,416),swapRB=True, crop=False)
    net.setInput(blob)
    
    start = time.time()
    
    layersOutputs = net.forward(ln)
    print(layersOutputs)
    
    boxes = []
    confidences = []
    classIDs = []
    
    for output in layersOutputs:
    	# 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 &gt; 0.5:
    			
    			box = detection[0:4]* np.array([W, H, W, H])
    			(centerX, centerY, width, height) = box.astype(&quot;int&quot;)
     
    			# 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)
    			
    # Remove unnecessary boxes using non maximum suppression
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, c_threshold, nms)
    
    if len(idxs) &gt; 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 = [int(c) for c in COLORS[classIDs[i]]]
    		cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
    		text = &quot;{}: {:.4f}&quot;.format(classes[classIDs[i]], confidences[i])
    		cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,
    			0.4, color, 1)
    
    end = time.time()
    # print the time required
    print('FPS:', 1/(end- start))
    
    # show the output image
    cv2.imshow(&quot;Image&quot;, image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

det_image_v1(model,cfg, img_file)

def det_image_v2(model, cfg, img_file, c_threshold=0.5, nms=0.5):
    # 加载yolo模型
    net = cv2.dnn_DetectionModel(model, cfg)
    net.setInputSize(512,512) # 设置网络输入尺寸
    net.setInputScale(1.0/255)
    net.setInputSwapRB(True)
    
    frame=cv2.imread(img_file)

    classes, confs, boxes = net.detect(frame, c_threshold, nms)
    
    for id, conf, box in zip(classes.flatten(), confs.flatten(), boxes):
        label = '{}, {:.2f}'.format(names[id], conf)
        # print(label)
        labelsize, baseLine= cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX,0.5,1)
        left, top, width, height = box
        top = max(top, labelsize[1])
        cv2.rectangle(frame, box, color=(0, 255, 0), thickness=3)
        cv2.rectangle(frame, (left, top-labelsize[1]),
                     (left+labelsize[0], top+baseLine),(255, 255, 255), cv2.FILLED)
        cv2.putText (frame, label,(left, top), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,0, 0))
    
    # plt.imshow(frame[:,:,::-1])
    # plt.show()
    cv2.imshow('frame', frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

det_image_v2(model, cfg, img_file)"><pre class="notranslate"><code class="notranslate">import cv2
import matplotlib.pyplot as plt
import time
import numpy as np
coco_names = r"F:\opencv\sources\samples\dnn\coco.names"

model_yolov2 = r"F:\opencv\sources\samples\dnn\yolov2.weights"
cfg_yolov2 = r"F:\opencv\sources\samples\dnn\yolov2.cfg"

model_yolov2_tiny = r"E:\MachineLearning\darknet\yolov2-tiny.weights"
cfg_yolov2_tiny = "E:\MachineLearning\darknet\cfg\yolov2-tiny.cfg"

model_yolov3 = r"F:\opencv\sources\samples\dnn\yolov3.weights"
cfg_yolov3 = r"F:\opencv\sources\samples\dnn\yolov3.cfg"

model_yolov3_tiny = r"E:\MachineLearning\darknet\yolov3-tiny.weights"
cfg_yolov3_tiny = "E:\MachineLearning\darknet\cfg\yolov3-tiny.cfg"

model_yolov3_tiny_prn = r"E:\MachineLearning\darknet\yolov3-tiny-prn.weights"
cfg_yolov3_tiny_prn = "E:\MachineLearning\darknet\cfg\yolov3-tiny-prn.cfg"

model_yolov3_spp = r"F:\opencv\sources\samples\dnn\yolov3-spp.weights"
cfg_yolov3_spp = r"F:\opencv\sources\samples\dnn\yolov3-spp.cfg"

csresnext_model = r"E:\MachineLearning\darknet\csresnext50-panet-spp-original-optimal_final.weights"
csresnext_cfg = r"E:\MachineLearning\darknet\cfg\csresnext50-panet-spp-original-optimal.cfg"

model_yolov4 = r"F:\opencv\sources\samples\dnn\yolov4.weights"
cfg_yolov4 = r"F:\opencv\sources\samples\dnn\yolov4.cfg"

model_yolov4_tiny = r"E:\MachineLearning\darknet\yolov4-tiny.weights"
cfg_yolov4_tiny = "E:\MachineLearning\darknet\cfg\yolov4-tiny.cfg"

enet_model = r"E:\MachineLearning\darknet\enetb0-coco_final.weights"
enet_cfg = r"E:\MachineLearning\darknet\cfg\enet-coco.cfg"

img_file = r"C:\Users\admin\Pictures\car.jpg"
video_file = r'F:/opencv-4.4.0/samples/data/vtest.avi'

model = model_yolov3_spp
cfg = cfg_yolov3_spp

with open(coco_names,'rt') as f:
    names = f.read().rstrip('\n').split('\n')

def det_image_v1(model, cfg, img_file, c_threshold=0.5, nms=0.5):
    
    classes = names
    # initialize a list of colors to represent each possible class label
    COLORS = np.random.randint(0, 255, size=(len(classes), 3),dtype="uint8")
    
    print("[INFO] loading model...")
    net = cv2.dnn.readNetFromDarknet(cfg, model)
    
    # load the input image and construct an input blob for the image
    # by resizing to a fixed 300x300 pixels and then normalizing it
    image = cv2.imread(img_file)
    (H,W) = image.shape[:2]

    # Get the names of output layers
    ln = net.getLayerNames()
    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    
    # generate blob for image input to the network
    blob = cv2.dnn.blobFromImage(image,1/255,(416,416),swapRB=True, crop=False)
    net.setInput(blob)
    
    start = time.time()
    
    layersOutputs = net.forward(ln)
    print(layersOutputs)
    
    boxes = []
    confidences = []
    classIDs = []
    
    for output in layersOutputs:
    	# 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 &gt; 0.5:
    			
    			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)
    			
    # Remove unnecessary boxes using non maximum suppression
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, c_threshold, nms)
    
    if len(idxs) &gt; 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 = [int(c) for c in COLORS[classIDs[i]]]
    		cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
    		text = "{}: {:.4f}".format(classes[classIDs[i]], confidences[i])
    		cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,
    			0.4, color, 1)
    
    end = time.time()
    # print the time required
    print('FPS:', 1/(end- start))
    
    # show the output image
    cv2.imshow("Image", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

det_image_v1(model,cfg, img_file)

def det_image_v2(model, cfg, img_file, c_threshold=0.5, nms=0.5):
    # 加载yolo模型
    net = cv2.dnn_DetectionModel(model, cfg)
    net.setInputSize(512,512) # 设置网络输入尺寸
    net.setInputScale(1.0/255)
    net.setInputSwapRB(True)
    
    frame=cv2.imread(img_file)

    classes, confs, boxes = net.detect(frame, c_threshold, nms)
    
    for id, conf, box in zip(classes.flatten(), confs.flatten(), boxes):
        label = '{}, {:.2f}'.format(names[id], conf)
        # print(label)
        labelsize, baseLine= cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX,0.5,1)
        left, top, width, height = box
        top = max(top, labelsize[1])
        cv2.rectangle(frame, box, color=(0, 255, 0), thickness=3)
        cv2.rectangle(frame, (left, top-labelsize[1]),
                     (left+labelsize[0], top+baseLine),(255, 255, 255), cv2.FILLED)
        cv2.putText (frame, label,(left, top), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0,0, 0))
    
    # plt.imshow(frame[:,:,::-1])
    # plt.show()
    cv2.imshow('frame', frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

det_image_v2(model, cfg, img_file)
</code></pre></div>
<p dir="auto">I used <code class="notranslate">cv2.dnn.readNetFromDarknet()</code> and <code class="notranslate">cv2.dnn_DetectionModel()</code>， both of them failed. The error is:</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-2b5g8ysb\opencv\modules\dnn\src\darknet\darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: F:\opencv\sources\samples\dnn\yolov3-spp.cfg in function 'cv::dnn::dnn4_v20200609::readNetFromDarknet'"><pre class="notranslate"><code class="notranslate">error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-2b5g8ysb\opencv\modules\dnn\src\darknet\darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: F:\opencv\sources\samples\dnn\yolov3-spp.cfg in function 'cv::dnn::dnn4_v20200609::readNetFromDarknet'
</code></pre></div>
<h5 dir="auto">Issue submission checklist</h5>
<ul class="contains-task-list">
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox"> I report the issue, it's not a question

</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox"> I checked the problem with documentation, FAQ, open issues,<br>
answers.opencv.org, Stack Overflow, etc and have not found solution

</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox"> I updated to latest OpenCV version and the issue is still there

</li>
<li class="task-list-item"><input type="checkbox" id="" disabled="" class="task-list-item-checkbox"> There is reproducer code and related data files: videos, images, onnx, etc

</li>
</ul>
<p dir="auto">OpenCV 4.2.0</p>
<p dir="auto">New models from Alexey Darknet repository</p>
<p dir="auto">CFG:  <a href="https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/csresnext50-panet-spp-original-optimal.cfg" rel="nofollow">https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/csresnext50-panet-spp-original-optimal.cfg</a></p>
<p dir="auto">WEIGHTS: <a href="https://drive.google.com/open?id=1_NnfVgj0EDtb_WLNoXV8Mo7WKgwdYZCc" rel="nofollow">https://drive.google.com/open?id=1_NnfVgj0EDtb_WLNoXV8Mo7WKgwdYZCc</a></p>
<p dir="auto">Testing with the new OPENCV-dnn with cuda support I achieve better performance than using Darknet library (even 2x FPS on a 1060 GTX), but the problem is that this model (which is quite better than the standard yolov3.cfg) causes this error.</p>
<p dir="auto"><strong>opencv/modules/dnn/src/dnn.cpp:1428:<br>
error: (-204:Requested object was not found) Layer with requested id=-1 not found in function 'getLayerData'</strong></p>