Faa
Faa

Reputation: 13

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

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

Upvotes: 1

Views: 602

Answers (1)

vighub
vighub

Reputation: 183

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)

Upvotes: 1

Related Questions