Home > Blockchain >  How to split images depend on it's label so each label will have it's image's folder
How to split images depend on it's label so each label will have it's image's folder

Time:11-21

I have a csv file which contain images label and path, and I have another folder contain all images, so I want to save each label's images in it's own folder, here how the csv looks like, I appreciate any help

enter image description here

I didn't find any code for this one

CodePudding user response:

You have to use pandas for reading the csv, os for creating the folders e shutil for copying files.

import os
import shutil
import pandas as pd

# read the file
csv_file = pd.read_csv('file.csv', dtype=str)

# create the folders
labels = csv_file['label']
for label in labels:
    os.makedirs(label, exist_ok=True)    

# iterate rows and copy images
for _, row in csv_file.iterrows():
    label = row['label']
    path = row['path']
    img_name = os.path.split(path)[-1]
    new_path = os.path.join(label, img_name)
    shutil.copy(path, new_path)
  • Related