生成数据集
生成数据集可以用labelImg工具,可以生成voc格式数据
voc转yolo
VOC数据格式
生成的voc格式长这样
--Root
--Annotations
--videoDir1
--0.xml
--1.xml
--videoDir2
--0.xml
--1.xml
--Images
--videoDir1
--0.jpg
--1.jpg
--videoDir2
--0.jpg
--1.jpg
利用这个代码可以将voc格式转成yolo格式,自动划分训练集测试集
voc2yolo代码
```python
import os
import glob
import random
import xml.etree.ElementTree as ET
currentRoot = os.getcwd()
classes = ["alive_fish","dead_fish"] #这里改成你自己的类名
train_percent = 0.8
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
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(xmlfile,labelfile):
with open(xmlfile,'r') as in_file:
with open(labelfile, 'w') as out_file:
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
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')
if __name__ == "__main__":
currentRoot = os.getcwd()
imgdirpath = os.path.join(currentRoot,"images","*")
imgdirlist = glob.glob(imgdirpath)
for i in range(len(imgdirlist)):
imgdir = imgdirlist[i]
labeldir = imgdir.replace('images','labels')
if(not os.path.exists(labeldir)):
os.mkdir(labeldir)
imgdirpath = os.path.join(imgdirpath,"*.jpg")
imgpathlist = glob.glob(imgdirpath)
for i in range(len(imgpathlist)):
imgfilepath = imgpathlist[i]
labelfilepath = imgfilepath.replace('images','labels')
labelfilepath = labelfilepath.replace('.jpg','.txt')
if(not os.path.exists(labelfilepath)):
xmlfilepath = imgfilepath.replace('images','Annotations')
xmlfilepath = xmlfilepath.replace('.jpg','.xml')
if(not os.path.exists(xmlfilepath)):
print("no xml file exists: "+xmlfilepath)
continue
else:
convert_annotation(xmlfilepath,labelfilepath)
labelfilepath = os.path.join(os.path.join(currentRoot,"labels","*","*.txt"))
labelfilepathlist = glob.glob(labelfilepath)
imagelist = []
for i in range(len(labelfilepathlist)):
labelfilepath = labelfilepathlist[i]
image = labelfilepath.replace('labels','images')
image = image.replace('.txt','.jpg')
imagelist.append(image)
print(len(imagelist))
num = len(imagelist)
trainnum = int(num * train_percent)
random.shuffle(imagelist)
print(len(imagelist))
for i in range(num):
if(i<trainnum):
with open('train.txt', 'a') as trainf:
trainf.write(imagelist[i]+'\n')
else:
with open('test.txt', 'a') as testf:
testf.write(imagelist[i]+'\n')
运行后生成的yolo数据长这样,然后就可以训练yolo啦
YOLO格式
yolo格式长这样
--Root
--Annotations
--videoDir1
--0.xml
--1.xml
--videoDir2
--0.xml
--1.xml
--Images
--videoDir1
--0.jpg
--1.jpg
--videoDir2
--0.jpg
--1.jpg
--labels
--videoDir1
--0.txt
--1.txt
--videoDir2
--0.txt
--1.txt
--train.txt
--test.txt
yolo转coco
因为yolo对拥挤和遮挡的物体检测效果并不是很好,我打算尝试用最近刚出的Detr来做检测
Detr利用了自注意力机制,中间采用了transform进行解码,该论文在github上已有实现,
该项目采取的是coco数据,所以我得将数据集转换成coco格式
利用下面这个代码可以将yolo格式转成coco格式
"""
YOLO 格式的数据集转化为 COCO 格式的数据集
--root_path 输入根路径
"""
import os
import cv2
import json
from tqdm import tqdm
import argparse
import glob
parser = argparse.ArgumentParser("ROOT SETTING")
parser.add_argument('--root_path',type=str,default='coco', help="root path of images and labels")
arg = parser.parse_args()
# 默认划分比例为 8:1:1。 第一个划分点在8/10处,第二个在9/10。
VAL_SPLIT_POINT = 4/5
TEST_SPLIT_POINT = 9/10
root_path = arg.root_path
print(root_path)
# 原始标签路径
originLabelsDir = os.path.join(root_path, 'labels/*/*.txt')
# 原始标签对应的图片路径
originImagesDir = os.path.join(root_path, 'images/*/*.jpg')
# dataset用于保存所有数据的图片信息和标注信息
train_dataset = {
'categories': [], 'annotations': [], 'images': []}
val_dataset = {
'categories': [], 'annotations': [], 'images': []}
test_dataset = {
'categories': [], 'annotations': [], 'images': []}
# 打开类别标签
with open(os.path.join(root_path, 'classes.txt')) as f:
classes = f.read().strip().split()
# 建立类别标签和数字id的对应关系
for i, cls in enumerate(classes, 1):
train_dataset['categories'].append({
'id': i, 'name': cls, 'supercategory': 'fish'})
val_dataset['categories'].append({
'id': i, 'name': cls, 'supercategory': 'fish'})
test_dataset['categories'].append({
'id': i, 'name': cls, 'supercategory': 'fish'})
# 读取images文件夹的图片名称
indexes = glob.glob(originImagesDir)
print(len(indexes))
# ---------------接着将,以上数据转换为COCO所需要的格式---------------
for k, index in enumerate(tqdm(indexes)):
txtFile = index.replace('images','labels').replace('jpg','txt')
# 用opencv读取图片,得到图像的宽和高
im = cv2.imread(index)
H, W, _ = im.shape
# 切换dataset的引用对象,从而划分数据集
if k+1 > round(len(indexes)*VAL_SPLIT_POINT):
if k+1 > round(len(indexes)*TEST_SPLIT_POINT):
dataset = test_dataset
else:
dataset = val_dataset
else:
dataset = train_dataset
# 添加图像的信息到dataset中
if(os.path.exists(txtFile)):
with open(txtFile, 'r') as fr:
dataset['images'].append({
'file_name': index.replace("\\","/"),
'id': k,
'width': W,
'height': H})
labelList = fr.readlines()
for label in labelList:
label = label.strip().split()
x = float(label[1])
y = float(label[2])
w = float(label[3])
h = float(label[4])
# convert x,y,w,h to x1,y1,x2,y2
#imagePath = os.path.join(originImagesDir,
# txtFile.replace('txt', 'jpg'))
image = cv2.imread(index)
x1 = (x - w / 2) * W
y1 = (y - h / 2) * H
x2 = (x + w / 2) * W
y2 = (y + h / 2) * H
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
# 为了与coco标签方式对,标签序号从1开始计算
cls_id = int(label[0]) + 1
width = max(0, x2 - x1)
height = max(0, y2 - y1)
dataset['annotations'].append({
'area': width * height,
'bbox': [x1, y1, width, height],
'category_id': int(cls_id),
'id': i,
'image_id': k,
'iscrowd': 0,
# mask, 矩形是从左上角点按顺时针的四个顶点
'segmentation': [[x1, y1, x2, y1, x2, y2, x1, y2]]
})
#print(dataset)
#break
else:
continue
# 保存结果的文件夹
folder = os.path.join(root_path, 'annotations')
if not os.path.exists(folder):
os.makedirs(folder)
for phase in ['train','val','test']:
json_name = os.path.join(root_path, 'annotations/{}.json'.format(phase))
with open(json_name, 'w',encoding="utf-8") as f:
if phase == 'train':
json.dump(train_dataset, f,ensure_ascii=False,indent=1)
if phase == 'val':
json.dump(val_dataset, f,ensure_ascii=False,indent=1)
if phase == 'test':
json.dump(test_dataset, f,ensure_ascii=False,indent=1)
coco格式
coco格式数据长这样
--Root
--Annotations
test.json
train.json
val.json
--Images
--videoDir1
--0.jpg
--1.jpg
--videoDir2
--0.jpg
--1.jpg