本文主要参考下面两篇博文,并在部分细节处做了修改。
一、数据集准备
(训练集验证集测试集的数据分别准备)
1、标注数据集
大多数人会用labelme来标注数据集,然后用labelme将每张标注图片都生成一个json文件。labelme教程网上很多,这里不再赘述。
本人由于原图的标注目标很小,用labelme标注未免不精确,所以先用PS手动标注后再写代码把标注图转换成了labelme格式的json文件。
结果如图:
2、将这些json文件转换成coco格式
这一步我使用如下代码可成功转换。
#-*- coding:utf-8 -*-
importos, sysimportargparseimportjsonimportmatplotlib.pyplot as pltimportskimage.io as iofrom labelme importutilsimportnumpy as npimportglobimportPIL.ImageclassMyEncoder(json.JSONEncoder):defdefault(self, obj):ifisinstance(obj, np.integer):returnint(obj)elifisinstance(obj, np.floating):returnfloat(obj)elifisinstance(obj, np.ndarray):returnobj.tolist()else:returnsuper(MyEncoder, self).default(obj)classlabelme2coco(object):def __init__(self, labelme_json=[], save_json_path='./tran.json'):''':param labelme_json: 所有labelme的json文件路径组成的列表
:param save_json_path: json保存位置'''self.labelme_json=labelme_json
self.save_json_path=save_json_path
self.images=[]
self.categories=[]
self.annotations=[]#self.data_coco = {}self.label=[]
self.annID= 1self.height=0
self.width=0
self.save_json()defdata_transfer(self):for num, json_file inenumerate(self.labelme_json):
with open(json_file,'r') as fp:
data= json.load(fp) #加载json文件self.images.append(self.image(data, num))for shapes in data['shapes']:
label= shapes['label']if label not inself.label:
self.categories.append(self.categorie(label))
self.label.append(label)
points= shapes['points'] #这里的point是用rectangle标注得到的,只有两个点,需要转成四个点points.append([points[0][0], points[1][1]])
points.append([points[1][0], points[0][1]])
self.annotations.append(self.annotation(points, label, num))
self.annID+= 1
defimage(self, data, num):
image={}#img = utils.img_b64_to_arr(data['imageData']) # 解析原图片数据
#img=io.imread(data['imagePath']) # 通过图片路径打开图片
#img = cv2.imread(data['imagePath'], 0)
#height, width = img.shape[:2]height= data['imageHeight']
width= data['imageWidth']
image['height'] =height
image['width'] =width
image['id'] = num + 1image['file_name'] = data['imagePath'].split('/')[-1]
self.height=height
self.width=widthreturnimagedefcategorie(self, label):
categorie={}
categorie['supercategory'] = &#