shutil.copyfile()复制文件

读取文件夹内所有文件数,随机分成训练集、测试集,将生成的text文件遍历后,移动xml文件和jpg图片到训练集测试集中

import os  
import random
from shutil import copyfile  


def create_main_txts(trainval_percent, train_percent):
    xmlfilepath = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations'  
    imgfilepath = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages'  
    txtsavepath = 'ImageSets\Main'

    if not os.path.exists(txtsavepath):
        os.makedirs(txtsavepath)

    total_xml = os.listdir(xmlfilepath) 
    #total_img = os.listdir(imgfilepath)   
    num=len(total_xml)  
    list=range(num)  
    tv=int(num*trainval_percent)  
    tr=int(tv*train_percent)  
    trainval= random.sample(list,tv)  
    train=random.sample(trainval,tr)

    for i  in list:  
        name_xml=total_xml[i]
        oldname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations/'+name_xml 
        trainname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations2/train/'+name_xml
        valname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations2/val/'+name_xml 
        testname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations2/test/'+name_xml 
        
        name_img=total_xml[i][:-4]+'.jpg'
        oldname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages/'+name_img
        trainname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages2/train/'+name_img
        valname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages2/val/'+name_img
        testname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages2/test/'+name_img 
        if i in trainval:  
            if i in train:  
                copyfile(oldname_xml,trainname_xml) 
                copyfile(oldname_img,trainname_img)
            else:  
                copyfile(oldname_xml,valname_xml)
                copyfile(oldname_img,valname_img)
        else:  
            copyfile(oldname_xml,testname_xml)
            copyfile(oldname_img,testname_img)

if __name__ == "__main__":
    create_main_txts(0.8,1)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值