【问题标题】:How to create image sub folders in python based on image labels如何根据图像标签在python中创建图像子文件夹
【发布时间】:2020-01-12 21:41:36
【问题描述】:

我需要根据它的标签创建图像子文件夹,标签存储在 csv 文件示例中

data\images(图片文件夹包含所有图片)

0.jpg,1.jpg,2.jpg......

data\train.csvtrain.csv 文件夹包含图像名称和类)

train.head()

image_id     catergory

0              22

1             44

..             ...

这个我已经试过了

train_dir = r'C:\Users\Admin\Downloads\Flower recognition\data\train'
train_sep_dir = r'C:\Users\Admin\Downloads\Flower recognition\data\train\train_sep'
if not os.path.exists(train_sep_dir):
    os.mkdir(train_sep_dir)

for image_id, category in labels.values:
    # Create subdirectory with `class_name`
    if not os.path.exists(train_sep_dir + str(category)):
        os.mkdir(train_sep_dir + str(category)
    src_path = train_dir + image_id + '.jpg'
    dst_path = train_sep_dir + category + '/' + image_id + '.jpg'
    try:
        shutil.copy(src_path, dst_path)
    except IOError as e:
        print('Unable to copy file {} to {}'
              .format(src_path, dst_path))
    except:
        print('When try copy file {} to {}, unexpected error: {}'
              .format(src_path, dst_path, sys.exc_info()))

【问题讨论】:

  • os.makedirs(name)
  • 感谢您的回复,但我需要根据那里的标签存储每个图像,如何做到这一点
  • 获取标签并使用它 - os.makedirs(label) 和后来的 shutil.move("filename", label) 将文件移动到此文件夹。
  • hai furas,你能分享一下资源吗
  • @HEMANTHKUMARGADI 给出输入和所需输出

标签: python computer-vision subdirectory


【解决方案1】:
import shutil, os
import pandas as pd

labels = pd.read_csv("train.csv")
labels = labels.sort_values('Class')

class_names = list(labels.Class.unique())

train_images = '/train'
train_cat = '/train_'

#creating subfolders
for i in class_names:
    os.makedirs(os.path.join('train_', i))

#moving the image files to their respective categories
for c in class_names: # Category Name
    for i in list(labels[labels['Class']==c]['Image']): # Image Id
        get_image = os.path.join('train', i) # Path to Images 
        move_image_to_cat = shutil.move(get_image, 'train_/'+c)

''' 图片 - image_id | 类 - 类别 '''

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2020-10-14
    • 1970-01-01
    • 2021-05-04
    • 2011-05-25
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多