python 自动生成图片集的验证集(图片对+label)

"""
By Fivethousand

输入图片二级目录根目录,随机生成该图片集的验证集(图片对+label)
"""
import os
import random

correct_label="1"
error_label="0"
def V_S_G(loadpath,savepath="./AutoSaved.txt",split=",",same_num=10,diff_num=50):                #V_S_G refers to Verification-set-generator
    f = open(savepath, 'a+')
    f.seek(0)
    f.truncate()  # 清空文件
    subfile_list1 = os.listdir(loadpath)      #一级子文件名列表
    dictionary={}
    for file in subfile_list1:
        subfile_list2=os.listdir(os.path.join(loadpath,file) )        #某一个一级子文件下的二级子文件列表
        dictionary[file]=subfile_list2                  #将该列表存入字典中,索引值为其母文件名

    for file in subfile_list1:          #生成相同的图片对
        count=2*same_num
        if count>len(dictionary[file]):
            count=len(dictionary[file])
            if count%2 is not 0:              #必须保证count是偶数
                count=count-1
        rdlist=random.sample(range(0,len(dictionary[file])),count)     #生成相同的图片对
        for i in range(int(count/2)):
            first=os.path.join(loadpath,file,dictionary[file][rdlist[2*i]])
            second=os.path.join(loadpath,    file, dictionary[file][rdlist[2 * i + 1]])
            f.write(first+split+second+split+correct_label+"\n")

    wrong_pair_num=diff_num
    if(diff_num>len(subfile_list1)):
        wrong_pair_num=len(subfile_list1)
    for i in range(wrong_pair_num):             #生成不相同的图片对
        rdpair=random.sample(range(0,len(subfile_list1)),2)
        first_file_name=subfile_list1[rdpair[0]]
        first_rd=random.sample(range(0,len(dictionary[first_file_name])),1)[0]
        first=os.path.join(loadpath,first_file_name,dictionary[first_file_name][first_rd])
        second_file_name=subfile_list1[rdpair[1]]
        second_rd=random.sample(range(0,len(dictionary[second_file_name])),1)[0]
        second=os.path.join(loadpath,second_file_name,dictionary[second_file_name][second_rd])
        f.write(first+split+second+split+error_label+"\n")
    f.close()

V_S_G("F:\python_programs\\tasks_from_King\datasets\CASIA-WebFace-part")




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值