1.下载yolov4-tiny.cfg和yolov4-tiny.cfg
地址:https://github.com/AlexeyAB/darknet
2.opencv dnn调用代码
import cv2 as cv
import numpy as np
yolo_tiny_model = "yolov4-tiny.weights";
yolo_tiny_cfg = "yolov4-tiny.cfg";
# Load names of classes
classes = None
with open("coco.txt", 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# load tensorflow model
net = cv.dnn.readNetFromDarknet(yolo_tiny_cfg, yolo_tiny_model)
# set back-end
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)
image = cv.imread('pedestrian_02.png')
image = cv.flip(image, 1)
h, w = image.shape[:2]
blobImage = cv.dnn.blobFromImage(image, 1.0/255.0, (416, 416), None, True, False);
outNames = net.getUnconnectedOutLayersNames()
net.setInput(blobImage)
outs = net.forward(outNames)
t, _ = net.getPerfProfile()
fps = 1000 / (t * 1000.0 / cv.getTickFrequency())
label = 'FPS: %.2f' % fps
cv.putText(image, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
# 绘制检测矩形
classIds = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
classId = np.argmax(scores)
confidence = scores[classId]
# numbers are [center_x, center_y, width, height]
if confidence > 0.5:
center_x = int(detection[0] * w)
center_y = int(detection[1] * h)
width = int(detection[2] * w)
height = int(detection[3] * h)
left = int(center_x - width / 2)
top = int(center_y - height / 2)
classIds.append(classId)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# 使用非最大抑制
indices = cv.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
cv.rectangle(image, (left, top), (left+width, top+height), (0, 0, 255), 2, 8, 0)
cv.putText(image, classes[classIds[i]], (left, top),
cv.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 0), 2)
c = cv.waitKey(1)
cv.namedWindow("YOLOv4-tiny-Detection-Demo",cv.WINDOW_NORMAL)
cv.imshow('YOLOv4-tiny-Detection-Demo', image)
cv.waitKey(0)
cv.destroyAllWindows()
3.BUG解决
报错内容如下:
error: (-212:Parsing error) Failed to parse NetParameter file:
./yolov4-tiny.cfg in function 'cv::dnn::dnn4_v20190122::readNetFromDarknet'
解决方案:修改yolov4-tiny.cfg
粗暴的将以下内容删除
[net]
# Testing
#batch=1
#subdivisions=1
# Training
batch=64
subdivisions=1
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1
learning_rate=0.00261
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1
4.运行成功