将visdrone2019数据集转换为COCO格式,
因实验需要将将visdrone2019数据集转换为COCO格式,但是在网上找了很多代码都会出各样的问题,这是目前找到的可以正确运行的代码。经过上述代码后可在runs\val\exp#找到生成的.json文件best_predictions.json。3利用上述转换代码获得visdrone2019数据集的标注文件.json文件形式。如何获得获得大中小目标的AP和AR指标(visdrone2019数据
·
因实验需要将将visdrone2019数据集转换为COCO格式,但是在网上找了很多代码都会出各样的问题,这是目前找到的可以正确运行的代码
网上下载的压缩包进行解压后会出现如下的目录

转换代码如下
""""将visdrone数据集转换为COCO格式"""
import os
import cv2
from PIL import Image
from tqdm import tqdm
import json
def convert_to_cocodetection(dir, output_dir):
# 数据目录
train_dir = os.path.join(dir, "VisDrone2019-DET-train")
val_dir = os.path.join(dir, "VisDrone2019-DET-val")
test_dir = os.path.join(dir, "VisDrone2019-DET-test-dev")
# 数据标注目录
train_annotations = os.path.join(train_dir, "annotations")
val_annotations = os.path.join(val_dir, "annotations")
test_annotations = os.path.join(test_dir, "annotations")
# 数据影像目录
train_images = os.path.join(train_dir, "images")
val_images = os.path.join(val_dir, "images")
test_images = os.path.join(test_dir, "images")
id_num = 0
categories = [
{"id": 0, "name": "pedestrian"},
{"id": 1, "name": "people"},
{"id": 2, "name": "bicycle"},
{"id": 3, "name": "car"},
{"id": 4, "name": "van"},
{"id": 5, "name": "truck"},
{"id": 6, "name": "tricycle"},
{"id": 7, "name": "awning-tricycle"},
{"id": 8, "name": "bus"},
{"id": 9, "name": "motor"},
]
for mode in ["test"]:
#for mode in ["train", "val","test"]:
images = []
annotations = []
print(f"start loading {mode} data...")
if mode == "train":
set = os.listdir(train_annotations)
annotations_path = train_annotations
images_path = train_images
elif mode == "test":
set = os.listdir(test_annotations)
annotations_path = test_annotations
images_path = test_images
else:
set = os.listdir(val_annotations)
annotations_path = val_annotations
images_path = val_images
for i in tqdm(set):
f = open(annotations_path + "/" + i, "r")
name = i.replace(".txt", "")
# images属性
image = {}
image_file_path = images_path + os.sep + name + ".jpg"
print(image_file_path)
img_size = Image.open((images_path + os.sep + name + ".jpg")).size
width, height = img_size
# height, width = cv2.imread(images_path + os.sep + name + ".jpg").shape[:2]
file_name = name + ".jpg"
image["id"] = name
image["height"] = height
image["width"] = width
image["file_name"] = file_name
images.append(image)
for line in f.readlines():
# annotation属性
annotation = {}
line = line.replace("\n", "")
if line.endswith(","): # filter data
line = line.rstrip(",")
line_list = [int(i) for i in line.split(",")]
if (line_list[4] == 1 and 0 < line_list[5] < 11): # class 0 为 ignore region class 11 为others 目标检测任务中忽略
bbox_xywh = [line_list[0], line_list[1], line_list[2], line_list[3]]
annotation["id"] = id_num
annotation["image_id"] = name
annotation["category_id"] = int(line_list[5] - 1) # yolo检测结果标签从0开始 为了与结果对齐 -1
annotation["area"] = bbox_xywh[2] * bbox_xywh[3]
# annotation["score"] = line_list[4]
annotation["bbox"] = bbox_xywh
annotation["iscrowd"] = 0
id_num += 1
annotations.append(annotation)
dataset_dict = {}
dataset_dict = {}
dataset_dict["images"] = images
dataset_dict["annotations"] = annotations
dataset_dict["categories"] = categories
json_str = json.dumps(dataset_dict)
with open(f'{output_dir}/VisDrone2019-DET_{mode}_coco_start.json', 'w') as json_file:
json_file.write(json_str)
print("json file write done...")
def get_test_namelist(dir, out_dir):
full_path = out_dir + "/" + "test.txt"
file = open(full_path, 'w')
for name in tqdm(os.listdir(dir)):
name = name.replace(".txt", "")
file.write(name + "\n")
file.close()
return None
def centerxywh_to_xyxy(boxes):
"""
args:
boxes:list of center_x,center_y,width,height,
return:
boxes:list of x,y,x,y,cooresponding to top left and bottom right
"""
x_top_left = boxes[0] - boxes[2] / 2
y_top_left = boxes[1] - boxes[3] / 2
x_bottom_right = boxes[0] + boxes[2] / 2
y_bottom_right = boxes[1] + boxes[3] / 2
return [x_top_left, y_top_left, x_bottom_right, y_bottom_right]
def centerxywh_to_topleftxywh(boxes):
"""
args:
boxes:list of center_x,center_y,width,height,
return:
boxes:list of x,y,x,y,cooresponding to top left and bottom right
"""
x_top_left = boxes[0] - boxes[2] / 2
y_top_left = boxes[1] - boxes[3] / 2
width = boxes[2]
height = boxes[3]
return [x_top_left, y_top_left, width, height]
def clamp(coord, width, height):
if coord[0] < 0:
coord[0] = 0
if coord[1] < 0:
coord[1] = 0
if coord[2] > width:
coord[2] = width
if coord[3] > height:
coord[3] = height
return coord
if __name__ == '__main__':
# 第一个参数输入上面目录的路径,第二个参数是要输出的路径
convert_to_cocodetection("D:\yolov5\datasets\VisDrone","D:\yolov5\datasets\VisDrone")
如何获得获得大中小目标的AP和AR指标(visdrone2019数据集)?
1,需要先在环境中安装pycocotools
pip install pycocotools
2,修改文件
修改val文件
1.'--save-json' 添加 default=True
parser.add_argument('--save-json', default=True, action='store_true', help='save a COCO-JSON results file')
2.注释下句 # opt.save_json |= opt.data.endswith('coco.yaml')
经过上述代码后可在runs\val\exp#找到生成的.json文件best_predictions.json
3利用上述转换代码获得visdrone2019数据集的标注文件.json文件形式
4运行下列代码可获得大中小目标的AP值
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
import numpy as np
#import skimage.io as io
import pylab, json
if __name__ == "__main__":
cocoGt = COCO(r"D:\datasets\VisDrone\annotations\VisDrone2019-DET_test_coco.json") # 标注文件的路径及文件名,json文件形式
cocoDt = cocoGt.loadRes(
r"D:\yolo\runs\val\exp48\best_predictions.json") # 自己的生成的结果的路径及文件名,json文件形式
cocoEval = COCOeval(cocoGt, cocoDt, "bbox")
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()
4结果如下所示

更多推荐
所有评论(0)