YoloV3-生成anchors 和制作数据集

2023-10-10 03:50

本文主要是介绍YoloV3-生成anchors 和制作数据集,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

利用以下代码生成YOLOV3的anchors

# -*- coding: utf-8 -*-
import numpy as np
import random
import argparse
import os
#参数名称
parser = argparse.ArgumentParser(description='使用该脚本生成YOLO-V3的anchor boxes\n')
parser.add_argument('--input_annotation_txt_dir',required=True,type=str,help='输入存储图片的标注txt文件(注意不要有中文)')
parser.add_argument('--output_anchors_txt',required=True,type=str,help='输出的存储Anchor boxes的文本文件')
parser.add_argument('--input_num_anchors',required=True,default=6,type=int,help='输入要计算的聚类(Anchor boxes的个数)')
parser.add_argument('--input_cfg_width',required=True,type=int,help="配置文件中width")
parser.add_argument('--input_cfg_height',required=True,type=int,help="配置文件中height")
args = parser.parse_args()
'''
centroids 聚类点 尺寸是 numx2,类型是ndarray
annotation_array 其中之一的标注框
'''
def IOU(annotation_array,centroids):#similarities = []#其中一个标注框w,h = annotation_arrayfor centroid in centroids:c_w,c_h = centroidif c_w >=w and c_h >= h:#第1中情况similarity = w*h/(c_w*c_h)elif c_w >= w and c_h <= h:#第2中情况similarity = w*c_h/(w*h + (c_w - w)*c_h)elif c_w <= w and c_h >= h:#第3种情况similarity = c_w*h/(w*h +(c_h - h)*c_w)else:#第3种情况similarity = (c_w*c_h)/(w*h)similarities.append(similarity)#将列表转换为ndarrayreturn np.array(similarities,np.float32) #返回的是一维数组,尺寸为(num,)'''
k_means:k均值聚类
annotations_array 所有的标注框的宽高,N个标注框,尺寸是Nx2,类型是ndarray
centroids 聚类点 尺寸是 numx2,类型是ndarray
'''
def k_means(annotations_array,centroids,eps=0.00005,iterations=200000):#N = annotations_array.shape[0]#C=2num = centroids.shape[0]#损失函数distance_sum_pre = -1assignments_pre = -1*np.ones(N,dtype=np.int64)#iteration = 0#循环处理while(True):#iteration += 1#distances = []#循环计算每一个标注框与所有的聚类点的距离(IOU)for i in range(N):distance = 1 - IOU(annotations_array[i],centroids)distances.append(distance)#列表转换成ndarraydistances_array = np.array(distances,np.float32)#该ndarray的尺寸为 Nxnum#找出每一个标注框到当前聚类点最近的点assignments = np.argmin(distances_array,axis=1)#计算每一行的最小值的位置索引#计算距离的总和,相当于k均值聚类的损失函数distances_sum = np.sum(distances_array)#计算新的聚类点centroid_sums = np.zeros(centroids.shape,np.float32)for i in range(N):centroid_sums[assignments[i]] += annotations_array[i]#计算属于每一聚类类别的和for j in range(num):centroids[j] = centroid_sums[j]/(np.sum(assignments==j))#前后两次的距离变化diff = abs(distances_sum-distance_sum_pre)#打印结果print("iteration: {},distance: {}, diff: {}, avg_IOU: {}\n".format(iteration,distances_sum,diff,np.sum(1-distances_array)/(N*num)))#三种情况跳出while循环:1:循环20000次,2:eps计算平均的距离很小 3:以上的情况if (assignments==assignments_pre).all():print("按照前后两次的得到的聚类结果是否相同结束循环\n")breakif diff < eps:print("按照eps结束循环\n")breakif iteration > iterations:print("按照迭代次数结束循环\n")break#记录上一次迭代distance_sum_pre = distances_sumassignments_pre = assignments.copy()
if __name__=='__main__':#聚类点的个数,anchor boxes的个数num_clusters = args.input_num_anchors#索引出文件夹中的每一个标注文件的名字(.txt)names = os.listdir(args.input_annotation_txt_dir)#标注的框的宽和高annotations_w_h = []for name in names:txt_path = os.path.join(args.input_annotation_txt_dir,name)#读取txt文件中的每一行f = open(txt_path,'r')for line in f.readlines():line = line.rstrip('\n')w,h = line.split(' ')[3:]#这时读到的w,h是字符串类型#eval()函数用来将字符串转换为数值型annotations_w_h.append((eval(w),eval(h)))f.close()#将列表annotations_w_h转换为numpy中的array,尺寸是(N,2),N代表多少框annotations_array = np.array(annotations_w_h,dtype=np.float32)N = annotations_array.shape[0]#对于k-means聚类,随机初始化聚类点random_indices = [random.randrange(N) for i in range(num_clusters)]#产生随机数centroids = annotations_array[random_indices]#k-means聚类k_means(annotations_array,centroids,0.00005,200000)#对centroids按照宽排序,并写入文件widths = centroids[:,0]sorted_indices = np.argsort(widths)anchors = centroids[sorted_indices]#将anchor写入文件并保存f_anchors = open(args.output_anchors_txt,'w')#for anchor in  anchors:f_anchors.write('%d,%d'%(int(anchor[0]*args.input_cfg_width),int(anchor[1]*args.input_cfg_height)))f_anchors.write('\n')

 对于以上生成anchors的具体理论,稍后添加

制作YoloV3的训练数据集

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import argparse
import xml.etree.ElementTree as ET
#转换
def convert(size, box):dw = 1./(size[0])dh = 1./(size[1])x = (box[0] + box[1])/2.0 - 1y = (box[2] + box[3])/2.0 - 1w = box[1] - box[0]h = box[3] - box[2]x = x*dww = w*dwy = y*dhh = h*dhreturn (x,y,w,h)
if __name__ == '__main__':#parser = argparse.ArgumentParser(description='利用该脚本文件: 1)将xml格式的标注文件转换为txt文件; 2)将图片的路径存储到txt文件中;3)根据实际情况修改脚本文件中的 classes')parser.add_argument('--input_images_dir',required = True,help = '输入存储图片的文件夹,darkNet是从文件夹名为images的文件夹中寻找图片,如/home/images')parser.add_argument('--input_annotations_dir',required = True,help='输入存储xml格式标注文件的文件夹,如/home/xml')parser.add_argument('--output_txt_dir',required = True,help='输出的存储txt文件的文件夹,darkNet是从文件夹名为labels的文件夹中寻找txt文件,而且文件夹images和labels位于同一级目录下,如/home/labels')parser.add_argument('--output_imagesdir_txt',required = True,help='输出的存储图片路径和图片名的txt文件名')args = parser.parse_args()#类别名classes = ['c1','c2']#索引出标注文件夹下的xml文件names = os.listdir(args.input_annotations_dir)#打开输出的txt文件output_imagesdir_txt = open(args.output_imagesdir_txt,'w')#创建存储xml转换为txt文件的文件夹output_txt_dir = args.output_txt_dirif not os.path.exists(output_txt_dir):os.makedirs(output_txt_dir)#循环处理for name in names:fileName,fileNameExtrend = os.path.splitext(name)#写入对应的图片文件路径output_imagesdir_txt.write(os.path.join(args.input_images_dir,fileName+'.jpg')+'\n')#读取xml文件xml_path = os.path.join(args.input_annotations_dir,name)#对应的输出的txt文件output_txt = open(os.path.join(output_txt_dir,fileName)+'.txt','w')#输出xml文件tree=ET.parse(xml_path)root = tree.getroot()size = root.find('size')w = int(size.find('width').text)h = int(size.find('height').text) for obj in root.iter('object'):difficult = obj.find('difficult').textcls = obj.find('name').textif cls not in classes or int(difficult)==1:continuecls_id = classes.index(cls)xmlbox = obj.find('bndbox')b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))bb = convert((w,h), b)#写入txt文件,如'0 0.2 0.3 0.4 0.5'output_txt.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')output_txt.close()output_imagesdir_txt.close()

用DarkNet训练数据集,在准备数据集时,有2种方式:

第1种:

darkNet训练网络时,
准备数据:
1:将图片存放在images文件夹下,
2:将txt文件存放在labels文件夹下
3:images和labels在同一目录下

darkNet会寻找images(或者JPEGimages)文件夹, 然后在统一目录下,寻找名称是labels的文件夹,该文件夹存放标注文件txt文件,如下图所示:

 

第2种方式:

如果没有images或者JPEGImages文件夹,那么每一张图片和对应的标注文件txt文件,要在同一目录下,如下图所示:

 其中trainImage文件夹中的文件如下所示,每一张图片对应相应的标注文件:

这篇关于YoloV3-生成anchors 和制作数据集的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/177744

相关文章

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅