Convert annotations to YoloV8 format?
Closed this issue · 1 comments
fatbringer commented
I want to train YoloV8 using this dataset for person detection and get bounding box.
I see the current annotation are just xy coordinates.
Would you know how to convert your annotations to YoloV8 annotation?
fatbringer commented
ok i will answer myself since i fixd it
import os
from pathlib import Path
import yaml
from ultralytics.utils.downloads import download
def visdrone2yolo(dir):
from PIL import Image
from tqdm import tqdm
def convert_box(size, box):
# Convert VisDrone box to YOLO xywh box
dw = 1. / size[0]
dh = 1. / size[1]
return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
(dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
for f in pbar:
img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
lines = []
with open(f, 'r') as file: # read annotation.txt
for row in [x.split(',') for x in file.read().strip().splitlines()]:
if row[4] == '0': # VisDrone 'ignored regions' class 0
continue
#modifications to include only pedestrian and people
if row[5] == "1" or "2" or "3" or "7":
#cls = int(row[5]) - 1
cls = 0 #turns all the people classes into 0, pls make sure consistent across all training
box = convert_box(img_size, tuple(map(int, row[:4])))
lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
with open(str(f).replace(f'{os.sep}annotations{os.sep}', f'{os.sep}labels{os.sep}'), 'w') as fl:
fl.writelines(lines) # write label.txt
print("done")
# Download
with open("VisDrone.yaml", "r") as stream:
try:
yamlfile = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
print("cwd is: ", Path.cwd())
base_dir = Path.cwd()
dir = base_dir.joinpath(yamlfile['path'])
#dir = ( Path.cwd() / yamlfile['path'] ) # dataset root dir
print("dataset root dir is: ", dir)
urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
#download(urls, dir=dir, curl=True, threads=4)
# Convert
for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
thanks!