树莓派开发之旅(二)——利用Opencv的dnn功能部署yolov3-tiny实现目标检测

树莓派开发之旅(二)——利用Opencv的dnn功能部署yolov3-tiny实现目标检测


前言

opencv4之后,官方提供了一些轻度深度学习框架的使用,用起来还是十分方便的,就是官方给的文档和说明的十分有限,不好上手,这里记录一下。

本文的代码基于此借鉴原代码


一、准备工作

主要使用的是官方提供的readNetFromDarknet的函数,去读取模型和官方训练好的权重(当然也可以自己训练自己的权重)去快速搭建网络。

 我们只需要去yolo的官网去下载对应网络的模型和权重即可,这里我们下载yolo-tiny的相关文件

yolo官网

 当然,如果想尝试其他网络,也可以下载试试,本人的树莓派4b,4g的版本跑tiny感觉都有点不太行。

下载完后放到工程根目录即可

 然后官方是基于coco数据集的权重,我们还需要一个coco.names文件,大家复制后,放到记事本里重命名即可。

person
bicycle
car
motorbike
aeroplane
bus
train
truck
boat
traffic light
fire hydrant
stop sign
parking meter
bench
bird
cat
dog
horse
sheep
cow
elephant
bear
zebra
giraffe
backpack
umbrella
handbag
tie
suitcase
frisbee
skis
snowboard
sports ball
kite
baseball bat
baseball glove
skateboard
surfboard
tennis racket
bottle
wine glass
cup
fork
knife
spoon
bowl
banana
apple
sandwich
orange
broccoli
carrot
hot dog
pizza
donut
cake
chair
sofa
pottedplant
bed
diningtable
toilet
tvmonitor
laptop
mouse
remote
keyboard
cell phone
microwave
oven
toaster
sink
refrigerator
book
clock
vase
scissors
teddy bear
hair drier
toothbrush

二、代码

这里代码注意修改一下有关自己的配置文件和权重即可

import cv2 as cv
import numpy as np

confThreshold = 0.3         # confidence threshold
nmsThreshold = 0.2         # NMS threshold

cap = cv.VideoCapture(0)

classesFile = 'coco.names'
classNames = []

modelConfiguration = 'yolov3-tiny.cfg'        # 修改为自己的模型配置文件
modelWeights = 'yolov3-tiny.weights'          # 修改为自己的模型权重

model = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
model.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
model.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

with open(classesFile, 'r') as f:
    classNames  = f.read().splitlines()

# 在输出中获取bbox并使用NMS,和绘制bbox
def findObjects(outputs, img):
    height, width, channel = img.shape
    bbox = []
    classIDs = []
    confs = []

    for output in outputs:
        for det in output:
            scores = det[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            if confidence > confThreshold:
                w, h = int(det[2]*width), int(det[3]*height)
                x, y = int(det[0]*width - w/2), int(det[1]*height - h/2)
                bbox.append([x, y, w, h])
                classIDs.append(classID)
                confs.append(float(confidence))

    indices = cv.dnn.NMSBoxes(bbox, confs, confThreshold, nmsThreshold) # 非极大值抑制
    for i in indices:
        i = i[0]
        box = bbox[i]
        x, y, w, h = box[0], box[1], box[2], box[3]
        cv.rectangle(image, (x, y), (x+w, y+h), (255, 0, 255), 2)
        cv.putText(image, classNames[classIDs[i]], (x, y-10), cv.FONT_HERSHEY_SIMPLEX,
                   0.6, (255, 0, 0), 2)


while cap.isOpened():
    ret, image = cap.read()
    blob = cv.dnn.blobFromImage(image, 1 / 255, (320, 320), [0, 0, 0], 1, crop=False)
    model.setInput(blob)
    layername = model.getLayerNames()
    # 获取yolo输出层
    outputNames = [layername[i[0]-1] for i in model.getUnconnectedOutLayers()] 
    # 从yolo输出层中获得输出
    outputs = model.forward(outputNames)
    findObjects(outputs, image)

    cv.imshow('img', image)
    if cv.waitKey(1) == 27:
        break

结果

这里说一下,使用yolo-tiny的准确率不高,最好把confidence的阈值调低一点。 

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Yolov3-tiny是一种非常流行的目标检测算法,可以用于人脸检测。如果你想使用yolov3-tiny进行人脸检测,可以按照以下步骤: 1. 下载预训练的yolov3-tiny权重文件。 2. 安装OpenCV和Python。 3. 编写Python脚本,读取图像并使用yolov3-tiny进行人脸检测。 4. 显示检测结果。 以下是一个简单的Python脚本示例,用于使用yolov3-tiny进行人脸检测: ```python import cv2 # 加载网络和权重文件 net = cv2.dnn.readNet("yolov3-tiny.weights", "yolov3-tiny.cfg") # 加载图像 image = cv2.imread("test.jpg") # 获取图像的高度和宽度 (h, w) = image.shape[:2] # 设置参数 confidence_threshold = 0.5 nms_threshold = 0.4 # 构建输入图像 blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False) # 设置网络的输入 net.setInput(blob) # 运行网络 outputs = net.forward(net.getUnconnectedOutLayersNames()) # 针对每个输出进行处理 for output in outputs: for detection in output: scores = detection[5:] classId = np.argmax(scores) confidence = scores[classId] # 如果置信度大于阈值,则进行处理 if confidence > confidence_threshold: # 计算边界框的位置 box = detection[0:4] * np.array([w, h, w, h]) (centerX, centerY, width, height) = box.astype("int") # 计算边界框的左上角坐标 x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # 添加边界框和置信度 boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classId) # 应用非最大抑制 indices = cv2.dnn.NMSBoxes(boxes, confidences, confidence_threshold, nms_threshold) # 循环遍历保留下来的边界框 for i in indices: i = i[0] box = boxes[i] (x, y, w, h) = box # 绘制边界框和置信度 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) text = "{}: {:.4f}".format("face", confidences[i]) cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示结果 cv2.imshow("Output", image) cv2.waitKey(0) ``` 请注意,此代码仅是示例,可能需要根据您的需求进行修改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lzzzzzzm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值