YOLO格式的数据集划分
标题标签格式txt
import os
import cv2
import random
from PIL import Image
img_train_path ='./img_train/'
img_val_path = './img_val/'
labels_train_path = './labels_train/'
labels_val_path = './labels_val/'
dir_images = './img/'
dir_labels = './ann-txt/'
images = os.listdir(dir_images)
labels = os.listdir(dir_labels)
random.seed(2021)
random.shuffle(images)
random.seed(2021)
random.shuffle(labels)
train_spilt_rate =0.8
a = int(len(images)*train_spilt_rate)
for i,image in enumerate(images):
image_path = dir_images + image
img = Image.open(image_path)
if i < a:
img.save(img_train_path + image)
else:
img.save(img_val_path + image)
for i , label in enumerate(labels):
with open(dir_labels + label, 'r') as f:
if i < a:
with open(labels_train_path + label , 'w') as s:
s.write(f.read())
else:
with open(labels_val_path + label , 'w') as s:
s.write(f.read())
|