前言

yolov3是一个很优秀的object-detection模型,其中的anchor box机制在多尺度检测上取得了不错的效果。然而,作者提供的anchor box值是基于voc和coco数据集上的,如果应用到自己数据集可能不完全适用,那么如何基于自己的训练数据聚类anchor box呢?好吧,源代码如下所示。

kemans.py

import numpy as npdef iou(box, clusters):"""Calculates the Intersection over Union (IoU) between a box and k clusters.:param box: tuple or array, shifted to the origin (i. e. width and height):param clusters: numpy array of shape (k, 2) where k is the number of clusters:return: numpy array of shape (k, 0) where k is the number of clusters"""x = np.minimum(clusters[:, 0], box[0])y = np.minimum(clusters[:, 1], box[1])if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:raise ValueError("Box has no area")intersection = x * ybox_area = box[0] * box[1]cluster_area = clusters[:, 0] * clusters[:, 1]iou_ = intersection / (box_area + cluster_area - intersection)return iou_def avg_iou(boxes, clusters):"""Calculates the average Intersection over Union (IoU) between a numpy array of boxes and k clusters.:param boxes: numpy array of shape (r, 2), where r is the number of rows:param clusters: numpy array of shape (k, 2) where k is the number of clusters:return: average IoU as a single float"""return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])])def translate_boxes(boxes):"""Translates all the boxes to the origin.:param boxes: numpy array of shape (r, 4):return: numpy array of shape (r, 2)"""new_boxes = boxes.copy()for row in range(new_boxes.shape[0]):new_boxes[row][2] = np.abs(new_boxes[row][2] - new_boxes[row][0])new_boxes[row][3] = np.abs(new_boxes[row][3] - new_boxes[row][1])return np.delete(new_boxes, [0, 1], axis=1)def kmeans(boxes, k, dist=np.median):"""Calculates k-means clustering with the Intersection over Union (IoU) metric.:param boxes: numpy array of shape (r, 2), where r is the number of rows:param k: number of clusters:param dist: distance function:return: numpy array of shape (k, 2)"""rows = boxes.shape[0]distances = np.empty((rows, k))last_clusters = np.zeros((rows,))np.random.seed()# the Forgy method will fail if the whole array contains the same rowsclusters = boxes[np.random.choice(rows, k, replace=False)]while True:for row in range(rows):distances[row] = 1 - iou(boxes[row], clusters)nearest_clusters = np.argmin(distances, axis=1)if (last_clusters == nearest_clusters).all():breakfor cluster in range(k):clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)last_clusters = nearest_clustersreturn clusters

cluster.py


import glob
import xml.etree.ElementTree as ET
import numpy as np
from kemans import kmeans, avg_iouANNOTATIONS_PATH = "F:/garbage/annotations"
CLUSTERS = 12def load_dataset(path):dataset = []for xml_file in glob.glob("{}/*xml".format(path)):tree = ET.parse(xml_file)height = int(tree.findtext("./size/height"))width = int(tree.findtext("./size/width"))for obj in tree.iter("object"):xmin = int(obj.findtext("bndbox/xmin")) / widthymin = int(obj.findtext("bndbox/ymin")) / heightxmax = int(obj.findtext("bndbox/xmax")) / widthymax = int(obj.findtext("bndbox/ymax")) / heightxmin = np.float64(xmin)ymin = np.float64(ymin)xmax = np.float64(xmax)ymax = np.float64(ymax)if xmax == xmin or ymax == ymin:print(xml_file)dataset.append([xmax - xmin, ymax - ymin])return np.array(dataset)if __name__ == '__main__':# print(__file__)data = load_dataset(ANNOTATIONS_PATH)out = kmeans(data, k=CLUSTERS)# clusters = [[10,13],[16,30],[33,23],[30,61],[62,45],[59,119],[116,90],[156,198],[373,326]]# out= np.array(clusters)/416.0print(out)print("Accuracy: {:.2f}%".format(avg_iou(data, out) * 100))print("Boxes:\n {}-{}".format(out[:, 0] * 608, out[:, 1] * 608))ratios = np.around(out[:, 0] / out[:, 1], decimals=2).tolist()print("Ratios:\n {}".format(sorted(ratios)))

最终聚类的结果:

[[0.3770724  0.15486111][0.03958333 0.0375    ][0.20677083 0.13686314][0.0703125  0.05347222][0.17916667 0.08472222][0.47375    0.24791667][0.08489583 0.08819444][0.125      0.0625    ][0.12447917 0.11319444][0.28541667 0.1025    ][0.2640625  0.21597222][0.14942708 0.1875    ]]
Accuracy: 75.99%
Boxes:[229.26001999  24.06666667 125.71666667  42.75       108.93333333288.04        51.61666667  76.          75.68333333 173.53333333160.55        90.85166667]-[ 94.15555556  22.8         83.21278721  32.51111111  51.51111111150.73333333  53.62222222  38.          68.82222222  62.32131.31111111 114.        ]
Ratios:[0.8, 0.96, 1.06, 1.1, 1.22, 1.31, 1.51, 1.91, 2.0, 2.11, 2.43, 2.78]

yolov3聚类自己数据的anchor box相关推荐

  1. ECCV2020 AABO: Adaptive Anchor Box Optimization for Object Detection via Bayesian Sub-sampling论文翻译

    ECCV2020 AABO论文翻译 摘要 1.介绍 2.相关工作 3.提出的方法 3.1 初步分析 3.2 anchors的搜索空间优化 3.3 通过子抽样的贝叶斯锚优化 4.实验 4.1数据集,指标 ...

  2. (Object detection)目标检测从入门到精通——第四部分anchor box

    3.8 Anchor Boxes 到目前为止,对象检测中存在的一个问题是每个格子只能检测出一个对象,如果你想让一个格子检测出多个对象,你可以这么做,就是使用anchor box这个概念,我们从一个例子 ...

  3. 0927锚框(Anchor box)

    锚框(Anchor box) 目标检测算法中,通常会在输入图像中采样大量的区域,然后判断这些区域中是否包含所感兴趣的目标,并调整区域边界从而更加准确地预测目标的真实边界框(ground-truth b ...

  4. 【YOLOv3从头训练 数据篇】

    YOLOv3从头训练 数据篇 前言 数据下载 数据可视化 标签生成 生成训练路径文件 结语 前言 最近在忙着怎么从头实现YOLOv3,从网上找了很多教程,也在GitHub上面找到了挺多的代码的,有些能 ...

  5. 【目标检测】概念理解:region proposal、bounding box、anchor box、ground truth、IoU、NMS、RoI Pooling

    最近刚接触图像识别,理解一些概念十分困难,尤其是动不动就冒出个看不懂的英语,让人抓狂.查了不少资料后做一个总结并加上一些自己的理解,理解若有误,烦请大家指出,相互学习. 本文主要对region pro ...

  6. anchor box 是如何确定的?

    文章目录 anchor box 是如何确定的? anchor box 框的位置是怎么设置的? anchor box 的数量和形状是怎么设置的? anchor box 的预测过程是怎样的? 1. 将 a ...

  7. Anchor box的理解

    Anchor box的理解 这个概念最初是在Faster R-CNN中提出,此后在SSD.YOLOv2.YOLOv3等优秀的目标识别模型中得到了广泛的应用. 背景 在Faster-RCNN中首次提出a ...

  8. R语言ggplot2可视化可视化聚类图、使用geom_encircle函数绘制多边形标定属于同一聚类簇的数据点、并自定义每个聚类簇数据点的颜色、多边形框的颜色(Cluster Plot)、主副标题题注

    R语言ggplot2可视化可视化聚类图.使用geom_encircle函数绘制多边形标定属于同一聚类簇的数据点.并自定义每个聚类簇数据点的颜色.多边形框的颜色(Cluster Plot).主副标题题注 ...

  9. 抛弃Anchor box和NMS,目标检测新范式开源:Sparse R-CNN

    点击上方,选择星标或置顶,不定期资源大放送! 阅读大概需要10分钟 Follow小博主,每天更新前沿干货 作者丨孙培泽@知乎 来源丨https://zhuanlan.zhihu.com/p/31005 ...

  10. 计算机视觉 滑动窗方法,图像分割相关技术之滑动窗口、RPN以及anchor box简介

    图像分割相关技术之滑动窗口.RPN以及anchor box简介 标签:## 时间:2019/11/17 11:07:25 作者:小木 对象识别(object recognition)是计算机视觉(co ...

最新文章

  1. Centos7多内核情况下修改默认启动内核方法
  2. 论文阅读笔记四十:Deformable ConvNets v2: More Deformable, Better Results(CVPR2018)
  3. vc与matlab联合,浅析VC与Matlab联合编程(二) - VC知识库文章
  4. ModuleNotFoundError: No module named ‘pandas._libs.tslibs.base‘
  5. java控制器删除数据_javaWeb删除一条及多条数据
  6. awk 分隔符 多个空格_如何在awk中指定多个分隔符
  7. python内置json模块的作用_python详解json模块
  8. .zip.001 -- .zip.003解压缩
  9. linux 不可中断的进程,不可中断进程和僵尸进程
  10. Python网页爬虫--
  11. 26元买4500斤脐橙,农民淘宝店被主播带头薅亏700万,“羊毛党”太狠了!
  12. 用计算机怎么算lnk,lnk格式怎么处理!我的电脑除了系统自带其他软件都变成lnk格式...
  13. 医院耗材管理系统开发_4
  14. [大数据]黑马hadoop学习笔记一
  15. html字体版权,字体在网站中的版权问题
  16. DIAMOND: 超快的蛋白序列比对软件
  17. 节后上班 北京车辆尾号限行2日轮换
  18. 02、江苏专转本(专业课笔记)第二章、计算机的组成原理
  19. BUUCTF之[Zer0pts2020]Can you guess it? basename函数绕过
  20. Git将分支代码合并到主干/将主干代码合并到分支

热门文章

  1. ubuntu 环境变量配置
  2. JSON 之 SuperObject(3): 访问
  3. 多线程下的资源同步访问
  4. MySQL5.6.10的安装
  5. 必备9种能力、9种手段、9种心态
  6. Visual Studio 2010全球发布会 上海站(图)
  7. 在c#中使用全局快捷键
  8. 真倒霉,前不久分區表錯誤把我數據全部搞沒了
  9. 清除Eclipse工作空间列表
  10. htmlspecialchars_decode 和 htmlspecialchars