1.提取出特定种类的数据集训练时间更短,coco数据集大概有120000张,而只包含“people,car,bicycle,motorcycle”的照片只有6万张,而只包含car的数据集只有两万张,提取出所需种类的数据集可以成倍地减少漫长的训练时间。
2.训练所得的模型更小,得益于训练目标数量的减少,得到的网络模型的大小也会变化,我用80个种类的数据集在yolov5s训练得到的模型为15.7m,而用4个种类的数据集训练得到的模型大小为14.0m,虽然差别不算太大,但对于在较低端的单片机平台上运行的项目来说这11%意义非凡。
提取出需要的种类,并将json文件转化成xml文件
from pycocotools.coco import COCO
import os
import shutil
from tqdm import tqdm
import skimage.io as io
import matplotlib.pyplot as plt
import cv2
from PIL import Image, ImageDraw
#the path you want to save your results for coco to voc
savepath="/coco_class/"
img_dir=savepath+'images/val2014/'
anno_dir=savepath+'Annotations/val2014/'
# datasets_list=['train2014', 'val2014']
# datasets_list=['train2014']
datasets_list=['val2014']
classes_names = ["person","bicycle","car","motorbike", "bus", "truck"]
#Store annotations and train2014/val2014/... in this folder
dataDir= '/coco/'
headstr = """\
VOC
%s
%d
%d
%d
0
"""
objstr = """\
"""
tailstr = '''\
'''
#if the dir is not exists,make it,else delete it
def mkr(path):
if os.path.exists(path):
shutil.rmtree(path)
os.mkdir(path)
else:
os.mkdir(path)
mkr(img_dir)
mkr(anno_dir)
def id2name(coco):
classes=dict()
for cls in coco.dataset['categories']:
classes[cls['id']]=cls['name']
return classes
def write_xml(anno_path,head, objs, tail):
f = open(anno_path, "w")
f.write(head)
for obj in objs:
f.write(objstr%(obj[0],obj[1],obj[2],obj[3],obj[4]))
f.write(tail)
def save_annotations_and_imgs(coco,dataset,filename,objs):
#eg:COCO_train2014_000000196610.jpg-->COCO_train2014_000000196610.xml
anno_path=anno_dir+filename[:-3]+'xml'
img_path=dataDir+'images/'+dataset+'/'+filename
# print(img_path)
dst_imgpath=img_dir+filename
print(img_path,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
img=cv2.imread(img_path)
# print(img)
if (img.shape[2] == 1):
print(filename + " not a RGB image")
return
shutil.copy(img_path, dst_imgpath)
head=headstr % (filename, img.shape[1], img.shape[0], img.shape[2])
tail = tailstr
write_xml(anno_path,head, objs, tail)
def showimg(coco,dataset,img,classes,cls_id,show=True):
global dataDir
I=Image.open('%s/%s/%s/%s'%(dataDir,'images',dataset,img['file_name']))
#Get the annotated information by ID
annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None)
# print(annIds)
anns = coco.loadAnns(annIds)
# print(anns)
# coco.showAnns(anns)
objs = []
for ann in anns:
class_name=classes[ann['category_id']]
if class_name in classes_names:
print(class_name)
if 'bbox' in ann:
bbox=ann['bbox']
xmin = int(bbox[0])
ymin = int(bbox[1])
xmax = int(bbox[2] + bbox[0])
ymax = int(bbox[3] + bbox[1])
obj = [class_name, xmin, ymin, xmax, ymax]
objs.append(obj)
draw = ImageDraw.Draw(I)
draw.rectangle([xmin, ymin, xmax, ymax])
if show:
plt.figure()
plt.axis('off')
plt.imshow(I)
plt.show()
return objs
for dataset in datasets_list:
#./COCO/annotations/instances_train2014.json
annFile='{}/annotations/instances_{}.json'.format(dataDir,dataset)
#COCO API for initializing annotated data
coco = COCO(annFile)
'''
When the COCO object is created, the following information will be output:
loading annotations into memory...
Done (t=0.81s)
creating index...
index created!
So far, the JSON script has been parsed and the images are associated with the corresponding annotated data.
'''
#show all classes in coco
classes = id2name(coco)
print(classes)
#[1, 2, 3, 4, 6, 8]
classes_ids = coco.getCatIds(catNms=classes_names)
print(classes_ids)
# exit()
for cls in classes_names:
#Get ID number of this class
cls_id=coco.getCatIds(catNms=[cls])
img_ids=coco.getImgIds(catIds=cls_id)
print(cls,len(img_ids))
# imgIds=img_ids[0:10]
for imgId in tqdm(img_ids):
img = coco.loadImgs(imgId)[0]
filename = img['file_name']
# print(filename)
objs=showimg(coco, dataset, img, classes,classes_ids,show=False)
print(objs)
save_annotations_and_imgs(coco, dataset, filename, objs)
因为yolov5是用不了xml文件的,所以要将他转化成txt文件
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
classes = ['person','bicycle','car','motorbike', 'bus', 'truck']
#classes = ['truck']
def convert(size, box):
dw = 1./(size[0])
dh = 1./(size[1])
x = (box[0] + box[1])/2.0 - 1
y = (box[2] + box[3])/2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x*dw
w = w*dw
y = y*dh
h = h*dh
return (x,y,w,h)
def convert_annotation(image_id):
in_file = open('/coco_class/Annotations/train2014/%s.xml'%(image_id))
out_file = open('/coco_class/labels/train2014/%s.txt'%(image_id), 'w')
tree=ET.parse(in_file)
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').text
cls = obj.find('name').text
print(cls)
if cls not in classes or int(difficult)==1:
continue
cls_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)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
data_path = '/coco_class/images/train2014'
img_names = os.listdir(data_path)
list_file = open('/coco_class/class_train.txt', 'w')
for img_name in img_names:
if not os.path.exists('coco_class/labels/train2014'):
os.makedirs('/coco_class/labels/train2014')
list_file.write('/coco_class/images/train2014/%s\n'%img_name)
image_id = img_name[:-4]
convert_annotation(image_id)
list_file.close()
成功转化后要注意有些坏的转化文件要修改后才能运行
最后附上训练得到的结果(由于算力的限制训练的效果不算很理想,加上有两类单车和摩托车经常搞混淆,所以这两类对map的拉低非常的大,但在实际应用中我将单车和摩托车是归为一类去处理的,这样实际上我的map实际可以达到0.8+以上):
这里是引用https://blog.csdn.net/weixin_42224823/article/details/106282114?ops_request_misc=%25257B%252522request%25255Fid%252522%25253A%252522161337082316780262559475%252522%25252C%252522scm%252522%25253A%25252220140713.130102334.pc%25255Fall.%252522%25257D&request_id=161337082316780262559475&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v29-3-106282114.first_rank_v2_pc_rank_v29&utm_term=coco%25E6%258F%2590%25E5%258F%2596yolo