yolo 深度学习_OpenCV3与深度学习实例-使用YOLOV3进行物体检测

这篇博客介绍了如何利用OpenCV3和深度学习模型YOLOV3进行物体检测。首先,通过argparse解析输入参数,然后加载YOLO的配置文件、预训练权重和类别文本。接着,定义获取输出层的函数,并从图像中创建blob输入到网络。在前向传播后,应用非极大抑制(NMS)筛选出高置信度的检测框,并在图像上绘制预测结果。最后,显示带有检测框的图像并等待用户按键退出。
摘要由CSDN通过智能技术生成

import cv2

import argparse

import numpy as np

ap = argparse.ArgumentParser()

ap.add_argument('-i', '--image', required=False,default='datas/images/people.jpg',

help = 'path to input image')

ap.add_argument('-c', '--config', required=False,default='datas/models/yolov3/yolov3.cfg',

help = 'path to yolo config file')

ap.add_argument('-w', '--weights', required=False,default='datas/models/yolov3/yolov3.weights',

help = 'path to yolo pre-trained weights')

ap.add_argument('-cl', '--classes', required=False,default='datas/models/yolov3/yolov3.txt',

help = 'path to text file containing class names')

args = ap.parse_args()

def get_output_layers(net):

layer_names = net.getLayerNames()

output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

return output_layers

def draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):

label = str(classes[class_id])

color = COLORS[class_id]

cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)

cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

image = cv2.imread(args.image)

Width = image.shape[1]

Height = image.shape[0]

scale = 0.00392

classes = None

with open(args.classes, 'r') as f:

classes = [line.strip() for line in f.readlines()]

COLORS = np.random.uniform(0, 255, size=(len(classes), 3))

net = cv2.dnn.readNet(args.weights, args.config)

blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)

net.setInput(blob)

outs = net.forward(get_output_layers(net))

class_ids = []

confidences = []

boxes = []

conf_threshold = 0.5

nms_threshold = 0.4

for out in outs:

for detection in out:

scores = detection[5:]

class_id = np.argmax(scores)

confidence = scores[class_id]

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 = center_x - w / 2

y = center_y - h / 2

class_ids.append(class_id)

confidences.append(float(confidence))

boxes.append([x, y, w, h])

indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)

for i in indices:

i = i[0]

box = boxes[i]

x = box[0]

y = box[1]

w = box[2]

h = box[3]

draw_prediction(image, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))

cv2.imshow("object detection", image)

cv2.waitKey()

# cv2.imwrite("object-detection.jpg", image)

cv2.destroyAllWindows()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值