k-means聚类出anchors
参考:
YOLOv3使用笔记——Kmeans聚类计算anchor boxes - Gotta-C的博客 - 优快云博客
https://blog.youkuaiyun.com/cgt19910923/article/details/82154401
文章目录
YOLOv3中的9个anchor(在yolov3-voc.cfg中,anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326)是由作者通过聚类COCO数据集得到的。而VOC数据集包含20类目标,其中大到bicycle、bus,小到bird、cat,目标大小差距很大,而如果将其用在自己的数据集上检测目标,其中部分anchor并不合理。因此在自己的数据集上聚类计算anchor,提高bounding box的检出率。
Joseph Redmon论文数据avg iou在67.2,该作者验证在k=9时,多次迭代在VOC 2007数据集上得到avg iou在67.13,相差无几。
程序
example.py
中load_dataset
后的数据长这样子:
data = load_dataset(ANNOTATIONS_PATH)
data:
[[0.41643059 0.262 ]
[0.97450425 0.972 ]
[0.20298507 0.202 ]
...
[0.498 0.992 ]
[0.284 0.424 ]
[0.99465241 0.994 ]]
解析:(举例:[0.41643059 0.262 ]
的由来)
[0.41643059 0.262 ]
对应000001.jpg
的第一个目标。
原始标注数据情况:
000001.jpg
图片的尺寸为353*500
;
该图中第一个目标的位置信息为:
<bndbox>
<xmin>48</xmin>
<ymin>240</ymin>
<xmax>195</xmax>
<ymax>371</ymax>
</bndbox>
所以(195-48) / 353 = 0.4164305949008499,(371-240) / 500 = 0.262
kmeans.py
import numpy as np
def 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)# zul: 把box移到原点,也就是width和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]