【目标检测】K
我们都知道yolov3对训练数据使用了k-means聚类的算法
来获得anchor boxes大小,但是具体其计算过程是怎样的呢?
下面我们来详细的分析其具体计算过程:
第一步:首先我们要知道我们需要聚类的是bounding box,所以我们无需考虑其所属类别,第一步我们需要将所有的bounding box坐标提取出来,也许一张图有一个矩形框,也许有多个,但是我们需要无区别的将所有图片的所有矩形框提取出来,放在一起。
第二步:数据处理获得所有训练数据bounding boxes的宽高数据。给的训练数据往往是其bounding box的4个坐标,但是我们后续需要聚类分析的是bounding box的宽高大小,所以我们需要将坐标数据转换为框的宽高大小,计算方法很简单:宽 = 右下角横坐标 - 左上角横坐标、高 = 右下角纵坐标-左上角纵坐标。
第三步:初始化k个anchor box,通过在所有的bounding boxes中随机选取k个值作为k个anchor boxes的初始值。
第四步:计算每个bounding box与每个anchor box的iou值。传统的聚类方法是使用欧氏距离来衡量差异,也就是说如果我们运用传统的k-means聚类算法,可以直接聚类bounding box的宽和高,产生k个宽、高组合的anchor boxes,但是作者发现此方法在box尺寸比较大的时候,其误差也更大,所以作者引入了iou值,可以避免这个问题。iou值计算方法:这里参考下图和计算代码:
min_w_matrix = np.minimum(cluster_w_matrix, box_w_matrix) #cluster_w_matrix, box_w_matrix分别代表anchor box和bounding box宽大小
min_h_matrix = np.minimum(cluster_h_matrix, box_h_matrix) #cluster_h_matrix, box_h_matrix分别代表anchor box和bounding box高大小
inter_area = np.multiply(min_w_matrix, min_h_matrix) #inter_area表示重叠面积
IOU = inter_area / (box_area + cluster_area - inter_area)#box_area表示bounding box面积 ;cluster_area表示anchor box面积
由于iou值往往越大越好,所以作者定义了一个距离d参数,用来表示其误差:
d=1-IOU
第五步:分类操作。经过前一步的计算可以的到每一个bounding box对于每个anchor box的误差d(n,k),我们通过比较每个bounding box其对于每个anchor box的误差大小{d(i,1),d(i,2),…,d(i,k)},选取最小误差的那个anchor box,将这个bounding box分类给它,对于每个bounding box都做这个操作,最后记录下来每个anchor box有哪些bounding box属于它。
第六步:anchor box更新。经过上一步,我们就知道每一个anchor box都有哪些bounding box属于它,然后对于每个anchor box中的那些bounding box,我们再求这些bounding box的宽高中值大小(这里参照github上作者qqwweee那个yolov3项目,也许也有使用平均值进行更新),将其作为该anchor box新的尺寸。
第七步:重复操作第四步到第六步,直到在第五步中发现对于全部bounding box其所属的anchor box类与之前所属的anchor box类完全一样。(这里表示所有bounding box的分类已经不再更新)
第八步:计算anchor boxes精确度。至第七步,其实已经通过k-means算法计算出anchor box。但是细心的同学可能已经发现,k-means.py还给出其精确度大小,其计算方法如下:使用最后得到的anchor boxes与每个bounding box计算其IOU值,对于每个bounding box选取其最高的那个IOU值(代表其属于某一个anchor box类),然后求所有bounding box该IOU值的平均值也即最后的精确度值。
代码:
import glob
import random
import xml.etree.ElementTree as ETimport numpy as npdef cas_iou(box, cluster):x = np.minimum(cluster[:, 0], box[0])y = np.minimum(cluster[:, 1], box[1])intersection = x * yarea1 = box[0] * box[1]area2 = cluster[:, 0] * cluster[:, 1]iou = intersection / (area1 + area2 - intersection)return ioudef avg_iou(box, cluster):return np.mean([np.max(cas_iou(box[i], cluster)) for i in range(box.shape[0])])def kmeans(box, k):# 取出一共有多少框row = box.shape[0]# 每个框各个点的位置distance = np.empty((row, k))# 最后的聚类位置last_clu = np.zeros((row,))np.random.seed()# 随机选5个当聚类中心cluster = box[np.random.choice(row, k, replace=False)]# cluster = random.sample(row, k)while True:# 计算每一行距离五个点的iou情况。for i in range(row):distance[i] = 1 - cas_iou(box[i], cluster)# 取出最小点near = np.argmin(distance, axis=1)if (last_clu == near).all():break# 求每一个类的中位点for j in range(k):cluster[j] = np.median(box[near == j], axis=0)last_clu = nearreturn clusterdef load_data(path):data = []# 对于每一个xml都寻找boxfor 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'))if height <= 0 or width <= 0:continue# 对于每一个目标都获得它的宽高for obj in tree.iter('object'):xmin = int(float(obj.findtext('bndbox/xmin'))) / widthymin = int(float(obj.findtext('bndbox/ymin'))) / heightxmax = int(float(obj.findtext('bndbox/xmax'))) / widthymax = int(float(obj.findtext('bndbox/ymax'))) / heightxmin = np.float64(xmin)ymin = np.float64(ymin)xmax = np.float64(xmax)ymax = np.float64(ymax)# 得到宽高data.append([xmax - xmin, ymax - ymin])return np.array(data)if __name__ == '__main__':# 运行该程序会计算'./VOCdevkit/VOC2007/Annotations'的xml# 会生成yolo_anchors.txtSIZE = 416anchors_num = 6# 载入数据集,可以使用VOC的xmlpath = "/home/ubuntu/Z/XYZ/DET/z-yolov3-cfg-linux/data/Annotations"# 载入所有的xml# 存储格式为转化为比例后的width,heightdata = load_data(path)# 使用k聚类算法out = kmeans(data, anchors_num)out = out[np.argsort(out[:, 0])]print('acc:{:.2f}%'.format(avg_iou(data, out) * 100))print(out * SIZE)data = out * SIZEf = open("yolo_anchors.txt", 'w')row = np.shape(data)[0]for i in range(row):if i == 0:x_y = "%d,%d" % (data[i][0], data[i][1])else:x_y = ", %d,%d" % (data[i][0], data[i][1])f.write(x_y)f.close()
如果聚类后效果不是很好,那是因为和自身数据集有关系,建议对生成的锚框进行缩放。
import numpy as np
anchor = open('model_data/neuron_anchors.txt') #原始anchors
expand_anchor = open('model_data/neuron_anchors1.txt','w') #变换后的anchor保存地址
ratio=0.5 #最小的锚框缩小倍数
base_ratio=3 #最大的锚框扩大倍数
box=anchor.read().split(',')
box=np.array(box)
for i in range(0,len(box)):box[i]=float(box[i].strip())
box=box.reshape((len(box)//2,2))
new_box=np.zeros((len(box),2))
length = len(box)
new_box[0,0]=int(float(box[0,0])*ratio)
new_box[0,1]=int(float(box[0,1])*ratio)
new_box[-1,0]=int(float(box[-1,0])*base_ratio)
new_box[-1,1]=int(float(box[-1,1])*base_ratio)
print(box)
for i in range(1,length-1):new_box[i,0]=(float(box[i,0])-float(box[0,0]))/(float(box[-1,0])-float(box[0,0]))*(new_box[-1,0]-new_box[0,0])+new_box[0,0]new_box[i,1]=new_box[i,0]*float(box[i,1])/float(box[i,0])new_box[i,0]=int(new_box[i,0])new_box[i,1]=int(new_box[i,1])for i in range(length):if i == 0:x_y = "%d,%d" % (new_box[i][0], new_box[i][1])else:x_y = ", %d,%d" % (new_box[i][0], new_box[i][1])expand_anchor.write(x_y)
expand_anchor.close()
anchor.close()print(new_box)
参考此篇博客。
参考
.html
.py
.py
发布者:admin,转转请注明出处:http://www.yc00.com/news/1688768158a168615.html
评论列表(0条)