|
import xml.etree.ElementTree as ET
import numpy as np
import glob
# 利用IOU值进行K-means聚类,得出最佳的anchor框设置
# Anchor和图片的输入分辨率有没有关系 这个问题了,当时这个问题有很多群友都在问。
# 通过kmeans函数得到的结果实际上是归一化到0-1之间的,
# 然后Anchor的输出是在此基础上乘以输入分辨率的大小。所以个人认为Anchor和图片的输入分辨率是有关系的
def iou(box, clusters):
"""
计算一个ground truth边界盒和k个先验框(Anchor)的交并比(IOU)值。
参数box: 元组或者数据,代表ground truth的宽高。
参数clusters: 形如(k,2)的numpy数组,其中k是聚类Anchor框的个数
返回:ground truth和每个Anchor框的交并比。
"""
# print("某个gt box:", box)
# print("所有的anchor box:", clusters)
# print("都已经归一化了 ,而且anchor box是作用于固定网络输入尺寸的 如608,与实际尺寸没有关系了")
x = np.minimum(clusters[:, 0], box[0])
y = np.minimum(clusters[:, 1], box[1])
# print("比较后,较小的宽:", x)
# print("比较后,较小的高:", y)
# assert 0 == 1, "停"
if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:
raise ValueError("Box has no area")
# 为了计算交集
intersection = x * y
box_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):
"""
计算一个ground truth和k个Anchor的交并比的均值。
"""
return np.mean([np.max(iou(boxes, clusters)) for i in range(boxes.shape[0])])
def kmeans(boxes, k, dist=np.median):
"""
利用IOU值进行K-means聚类
参数boxes: 形状为(r, 2)的ground truth框,其中r是ground truth的个数
参数k: Anchor的个数
参数dist: 距离函数
返回值:形状为(k, 2)的k个Anchor框
"""
# 即是上面提到的r
rows = boxes.shape[0]
print("一共多少个人工标注框:", rows)
# 距离数组,计算每个ground truth和k个Anchor的距离
distances = np.empty((rows, k))
# 上一次每个ground truth"距离"最近的Anchor索引
last_clusters = np.zeros((rows,))
# 设置随机数种子
np.random.seed()
# 初始化聚类中心,k个簇,从r个ground truth随机选k个
# replace=False 不重复的
clusters = boxes[np.random.choice(rows, k, replace=False)]
# 开始聚类
while True:
# 计算每个ground truth和k个Anchor的距离,用1-IOU(box,anchor)来计算
for row in range(rows):
# 某个gt box与所有的anchor box之间计算iou
# iou越大越好 而距离是越小越好
distances[row] = 1 - iou(boxes[row], clusters)
# 对每个ground truth,选取距离最小的那个Anchor,并存下索引
nearest_clusters = np.argmin(distances, axis=1)
# 如果当前每个ground truth"距离"最近的Anchor索引和上一次一样,聚类结束
if (last_clusters == nearest_clusters).all():
break
# 更新簇中心为簇里面所有的ground truth框的均值
for cluster in range(k):
clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)
# 更新每个ground truth"距离"最近的Anchor索引
last_clusters = nearest_clusters
return clusters
# 加载自己的数据集,只需要所有labelimg标注出来的xml文件即可
def 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"))
print("直接从xml文件获取的宽={},高={}".format(width, height))
for obj in tree.iter("object"):
# 偏移量
xmin = int(obj.findtext("bndbox/xmin")) / width
ymin = int(obj.findtext("bndbox/ymin")) / height
xmax = int(obj.findtext("bndbox/xmax")) / width
ymax = int(obj.findtext("bndbox/ymax")) / height
xmin = np.float64(xmin)
ymin = np.float64(ymin)
xmax = np.float64(xmax)
ymax = np.float64(ymax)
if xmax == xmin or ymax == ymin:
print("没有box的xml:", xml_file)
# 将Anchor的长宽放入dateset,运行kmeans获得Anchor
dataset.append([xmax - xmin, ymax - ymin])
return np.array(dataset)
if __name__ == '__main__':
# xml文件所在文件夹
# ANNOTATIONS_PATH = "/media/jiang/AI_DataSets/DataSets/VOCdevkit/VOC2012/Annotations"
ANNOTATIONS_PATH = "/media/jiang/AI_DataSets/DataSets/VOCdevkit/VOC2007/Annotations"
CLUSTERS = 9 # 聚类数量,anchor数量 clusters
INPUTDIM = 416 # 输入网络大小 inputdim
data = load_dataset(ANNOTATIONS_PATH)
# data里放的是:该数据集中所有目标框box的 [宽度, 高度] 并已经归一化的
print("数据集一共有多少个目标框box(非图片个数):", len(data))
out = kmeans(data, k=CLUSTERS)
print('Boxes聚类后:')
print(np.array(out) * INPUTDIM)
print("聚类后该值最大Accuracy: {:.2f}%".format(avg_iou(data, out) * 100))
final_anchors = np.around(out[:, 0] / out[:, 1], decimals=2).tolist()
print("Before Sort 宽高比Ratios:\n {}".format(final_anchors))
print("After Sort 宽高比Ratios:\n {}".format(sorted(final_anchors)))
|
|