区分数据集每张图片的类别并分别保存

from cgi import print_arguments
import shutil
import random
import os
import pathlib
import numpy as np
import pandas as pd
from numpy import size
from collections import Counter
# from torch import classes

img_path = 'val/val/images'
txt_path = 'val/val/labels'
all_path = 'classes/'

size = [800, 800]
classes = ['ship', 'airplane', 'vehicle', 'wind-mill', 'storage-tank', 'bridge', 'swimming-pool', 'person']

txt_name = os.listdir(txt_path)  #列出全部的txt
img_name = os.listdir(img_path)

# all_label = np.array([])

for txt in txt_name:  
    txtpath = os.path.join(txt_path,txt)
    all_label = np.array([])
    gt = np.loadtxt(open(txtpath, encoding='utf8'),dtype=np.str, delimiter=' ')
    if(gt.ndim==1):
        gt = np.expand_dims(gt, axis=0)   
    length = gt.shape[0]
    for j in range(length):
        label_ = gt[j][4]
        all_label = np.append(all_label,str(label_))  #将一个txt的 所有类别都保存下来
    print(all_label)
    dict_ = {}
    for i in all_label:
        if i not in dict_.keys():
            dict_[i] = Counter(all_label)[i]
    print(dict_)
    class1_ = max(dict_, key = dict_.get) 
    print(class1_)
    if (class1_ in classes):
        savetxt = all_path + str(class1_) + '/txt'  #保存该txt的路径
        shutil.copy(txtpath, savetxt)
        txt = str(txt)
        img = txt[:-4] + ".jpg"
        saveimg = all_path + str(class1_) + '/img'
        if img in img_name:
            imgpath = img_path + '/' + img
            shutil.copy(imgpath, saveimg)  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值