└─VisDrone
├─VisDrone2019-DET-test-challenge
│ └─images
├─VisDrone2019-DET-test-dev
│ ├─annotations
│ └─images
├─VisDrone2019-DET-train
│ ├─annotations
│ ├─images
下载的原始结构类似于上图,annotations中的txt标注文件无法直接在yolo中使用,因此需要写一个脚本将其转化为可用的yolo格式的标注文件,如下所示:
import os
import cv2
def get_image_size(image_path):
img = cv2.imread(image_path)
if img is not None:
height, width, _ = img.shape
return width, height
else:
return None, None
def convert_to_yolo_format(input_file, output_file, image_width, image_height):
with open(input_file, 'r') as f:
lines = f.readlines()
with open(output_file, 'w') as f:
for line in lines: # 例如原txt文件中,某一行是249,297,23,30,1,4,0,2
data = line.strip().split(',')
x_top_left = float(data[0]) #249
y_top_left = float(data[1]) #297
width = float(data[2]) #23
height = float(data[3]) #30
consider = int(data[4]) # 0 or 1 表示是否忽略这个标注框
class_label = int(data[5]) # class label
if consider == 0:
continue # Skip if the bounding box should be ignored
# Calculate normalized coordinates
x_center = (x_top_left + width / 2) / image_width
y_center = (y_top_left + height / 2) / image_height
normalized_width = width / image_width
normalized_height = height / image_height
# Write to output file in YOLO format
f.write(f"{class_label} {x_center:.6f} {y_center:.6f} {normalized_width:.6f} {normalized_height:.6f}\n")
def convert_annotations_in_folder(input_folder, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(".txt"):
# Get corresponding image size
image_name, _ = os.path.splitext(filename)
image_path = os.path.join(input_folder, '..', 'images', f"{image_name}.jpg")
image_width, image_height = get_image_size(image_path)
if image_width is None or image_height is None:
print(f"Error: Failed to get image size for {image_path}")
continue
input_file = os.path.join(input_folder, filename)
output_file = os.path.join(output_folder, filename)
convert_to_yolo_format(input_file, output_file, image_width, image_height)
print(f"Converted {input_file} to YOLO format.")
# Example usage:
input_folder = 'D:\\studydie\\objectdetect\\datasets\\drone\\VisDrone2019-DET-train\\VisDrone2019-DET-train\\annotations' # Replace with your annotations folder path
output_folder = 'D:\\studydie\\objectdetect\\datasets\\drone\\VisDrone2019-DET-train\\VisDrone2019-DET-train\\labels' # Replace with your desired output folder path
convert_annotations_in_folder(input_folder, output_folder)
直接复制,只需要修改input_folder为annotions的地址,output_folder是你想要输出的保存标注文件的地址