YOLO,是You Only Look Once的缩写,一种基于深度卷积神经网络的物体检测算法,YOLO v3是YOLO的第3个版本,检测算法更快更准。

本文源码:https://github.com/SpikeKing/keras-yolo3-detection

欢迎Follow我的GitHub:https://github.com/SpikeKing

数据集

YOLO v3已经提供COCO(Common Objects in Context)数据集的模型参数,支持直接用于物体检测,模型248M,下载:

wget https://pjreddie.com/media/files/yolov3.weights

将模型参数转换为Keras的模型参数,模型248.6M,转换:

python convert.py -w yolov3.cfg model_data/yolov3.weights model_data/yolo_weights.h5

画出网络结构:

plot_model(model, to_file='./model_data/model.png', show_shapes=True, show_layer_names=True)  # 网络图

COCO含有80个类别:

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(牙刷)

YOLO的默认anchors是9个,对应三个尺度,每个尺度含有3个anchors,如下:

10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326

检测器

YOLO检测类的构造器:

  1. anchors、model、classes是参数文件,其中,anchors可以使用默认,但是model与classes必须相互匹配;
  2. score和iou是检测参数,即置信度阈值和交叉区域阈值,置信度阈值避免误检,交叉区域阈值避免物体重叠;
  3. self.class_namesself.anchors,读取类别和anchors;
  4. self.sess是TensorFlow的上下文环境;
  5. self.model_image_size,检测图片尺寸,将原图片同比例resize检测尺寸,空白填充;
  6. self.generate()是参数流程,输出框(boxes)、置信度(scores)和类别(classes);

源码:

class YOLO(object):def __init__(self):self.anchors_path = 'configs/yolo_anchors.txt'  # anchorsself.model_path = 'model_data/yolo_weights.h5'  # 模型文件self.classes_path = 'configs/coco_classes.txt'  # 类别文件self.score = 0.3  # 置信度阈值# self.iou = 0.45self.iou = 0.20  # 交叉区域阈值self.class_names = self._get_class()  # 获取类别self.anchors = self._get_anchors()  # 获取anchorself.sess = K.get_session()self.model_image_size = (416, 416)  # fixed size or (None, None), hwself.boxes, self.scores, self.classes = self.generate()def _get_class(self):classes_path = os.path.expanduser(self.classes_path)with open(classes_path) as f:class_names = f.readlines()class_names = [c.strip() for c in class_names]return class_namesdef _get_anchors(self):anchors_path = os.path.expanduser(self.anchors_path)with open(anchors_path) as f:anchors = f.readline()anchors = [float(x) for x in anchors.split(',')]return np.array(anchors).reshape(-1, 2)

参数流程:输出框(boxes)、置信度(scores)和类别(classes)

  1. yolo_body网络中,加载yolo_model参数;
  2. 为不同的框,生成不同的颜色,随机;
  3. 将模型的输出,经过置信度和交叉区域,过滤框;

源码:

def generate(self):model_path = os.path.expanduser(self.model_path)  # 转换~assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'num_anchors = len(self.anchors)  # anchors的数量num_classes = len(self.class_names)  # 类别数# 加载模型参数self.yolo_model = yolo_body(Input(shape=(None, None, 3)), 3, num_classes)self.yolo_model.load_weights(model_path)print('{} model, {} anchors, and {} classes loaded.'.format(model_path, num_anchors, num_classes))# 不同的框,不同的颜色hsv_tuples = [(float(x) / len(self.class_names), 1., 1.)for x in range(len(self.class_names))]  # 不同颜色self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))self.colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors))  # RGBnp.random.seed(10101)np.random.shuffle(self.colors)np.random.seed(None)# 根据检测参数,过滤框self.input_image_shape = K.placeholder(shape=(2,))boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors, len(self.class_names),self.input_image_shape, score_threshold=self.score, iou_threshold=self.iou)return boxes, scores, classes

检测方法detect_image

第1步,图像处理:

  1. 将图像等比例转换为检测尺寸,检测尺寸需要是32的倍数,周围进行填充;
  2. 将图片增加1维,符合输入参数格式;
if self.model_image_size != (None, None):  # 416x416, 416=32*13,必须为32的倍数,最小尺度是除以32assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))  # 填充图像
else:new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32))boxed_image = letterbox_image(image, new_image_size)
image_data = np.array(boxed_image, dtype='float32')
print('detector size {}'.format(image_data.shape))
image_data /= 255.  # 转换0~1
image_data = np.expand_dims(image_data, 0)  # 添加批次维度,将图片增加1维

第2步,feed数据,图像,图像尺寸;

out_boxes, out_scores, out_classes = self.sess.run([self.boxes, self.scores, self.classes],feed_dict={self.yolo_model.input: image_data,self.input_image_shape: [image.size[1], image.size[0]],K.learning_phase(): 0})

第3步,绘制边框,自动设置边框宽度,绘制边框和类别文字,使用Pillow。

font = ImageFont.truetype(font='font/FiraMono-Medium.otf',size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))  # 字体
thickness = (image.size[0] + image.size[1]) // 512  # 厚度
for i, c in reversed(list(enumerate(out_classes))):predicted_class = self.class_names[c]  # 类别box = out_boxes[i]  # 框score = out_scores[i]  # 执行度label = '{} {:.2f}'.format(predicted_class, score)  # 标签draw = ImageDraw.Draw(image)  # 画图label_size = draw.textsize(label, font)  # 标签文字top, left, bottom, right = boxtop = max(0, np.floor(top + 0.5).astype('int32'))left = max(0, np.floor(left + 0.5).astype('int32'))bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))right = min(image.size[0], np.floor(right + 0.5).astype('int32'))print(label, (left, top), (right, bottom))  # 边框if top - label_size[1] >= 0:  # 标签文字text_origin = np.array([left, top - label_size[1]])else:text_origin = np.array([left, top + 1])# My kingdom for a good redistributable image drawing library.for i in range(thickness):  # 画框draw.rectangle([left + i, top + i, right - i, bottom - i],outline=self.colors[c])draw.rectangle(  # 文字背景[tuple(text_origin), tuple(text_origin + label_size)],fill=self.colors[c])draw.text(text_origin, label, fill=(0, 0, 0), font=font)  # 文案del draw

目标检测

使用YOLO检测器,检测图像:

def detect_img_for_test(yolo):img_path = './dataset/a4386X6Te9ajq866zgOtWKLx18XGW.jpg'image = Image.open(img_path)r_image = yolo.detect_image(image)r_image.show()yolo.close_session()if __name__ == '__main__':detect_img_for_test(YOLO())

效果:

OK,that‘s all! Enjoy it!

目标检测 YOLO v3 验证 COCO 模型相关推荐

  1. yolov3网络结构图_目标检测——YOLO V3简介及代码注释(附github代码——已跑通)...

    GitHub: liuyuemaicha/PyTorch-YOLOv3​github.com 注:该代码fork自eriklindernoren/PyTorch-YOLOv3,该代码相比master分 ...

  2. 目标检测 YOLO v3 训练 人脸检测模型

    YOLO,是You Only Look Once的缩写,一种基于深度卷积神经网络的物体检测算法,YOLO v3是YOLO的第3个版本,检测算法更快更准. 本文源码:https://github.com ...

  3. 对象检测目标小用什么模型好_自动驾驶目标检测- YOLO v3 深入解析

    从2016年 Joseph Redmon 发布第一代YOLO开始,YOLO已经更新四代了,凭借着在一个网络模型中完成对图像中所有对象边界框和类别预测的独特创新,成为现今使用最广泛也是最快的对象检测算法 ...

  4. 重温目标检测--YOLO v3

    YOLOv3: An Incremental Improvement https://pjreddie.com/yolo/ 本文是对 YOLO系列的进一步完善. 先上和其他检测算法的 COCO 对比结 ...

  5. 目标检测YOLO系列------YOLO简介

    目标检测YOLO系列------YOLO简介 1.为什么会出现YOLO算法 2.YOLO算法会逐渐成为目标检测的主流吗     YOLO以及各种变体已经广泛应用于目标检测算法所涉及到的方方面面,为了梳 ...

  6. 目标检测 YOLOv5 - v6.2版本模型在瑞芯微 Rockchip设备从训练到C++部署实践

    目标检测 YOLOv5 - v6.2版本模型在瑞芯微 Rockchip设备从训练到C++部署实践 flyfish 源码地址 https://github.com/shaoshengsong/rockc ...

  7. 目标检测 | YOLO系列超全讲解v1,v2,v3

    前言 一.YOLOv1 1. 网络结构 2. 实现方法 3. 损失函数 4. 缺点 二.YOLOv2 1. 网络结构 2. 改进方法 3. YOLO9000 4. 网络训练细节 三.YOLOv3 1. ...

  8. 目标检测 YOLO 系列模型

    前言 YOLO (You Only Look Once) 系列模型追求实时目标检测,因此会在一定程度上牺牲精度,以实现更高的检测速度. 如果你对这篇文章感兴趣,可以点击「[访客必读 - 指引页]一文囊 ...

  9. 目标检测YOLO实战应用案例100讲-基于YOLO模型的遥感影像 飞机目标检测技术研究

    目录 基于YOLOv5模型的遥感影像飞机目标检测 基于深度学习的目标检测算法 POLO系列模型原理

最新文章

  1. 后台获取视图对应的字符串
  2. 自制树莓派“防松鼠神器”在Reddit火了,13行代码就能让AI替你护食,成本300+元...
  3. PHP连接数据库的三种方式
  4. 数据库三范式经典实例解析
  5. 如何隐藏android的屏幕上的Title Bar
  6. ExtJS入门(08)窗口,按钮,输入框,
  7. PAT(乙级)1009
  8. python自动化运维快速入门pdf下载_Python自动化运维快速入门
  9. Python 进程 Process 与线程 threading 区别 - Python零基础入门教程
  10. 如何利用开源项目,帮助企业免费搭建小程序官网
  11. Request/Response
  12. Web_add_cookie的作用
  13. 谨以此文献给才毕业1--5年的朋友。。
  14. JavaScript:获取帧率FrameUtil.js
  15. 笔试题算法系列(五)百度2017买帽子
  16. mt6771(Helio P60)套片开发资料下载,mt6771处理器性能
  17. php语言有哪些特性,盘点PHP编程语言具有的特性
  18. 我读经典管理书籍《管理的实践》有感
  19. PhotoshopCC2019(64位)下载+安装教程
  20. 天虹数科Java笔试题B

热门文章

  1. Linux Shell中的美元符号$
  2. hypermill后处理构造器安装_NX后处理直白易操作教程
  3. 伺服CAN总线设计(电工Demo)
  4. ECNU_OJ_1073
  5. python抓取网页数据并截图_网络爬虫-使用Python抓取网页数据
  6. 使用simulink进行自适应滤波
  7. HDU-4540 威威猫系列故事——打地鼠
  8. 【语音去噪】基于matlab GUI切比雪夫+椭圆形低通滤波器语音去噪【含Matlab源码 2198期】
  9. JSP实现养老院管理系统
  10. 小.心情5(21天减肥法)