Как разделить изображения на папки на основе меток CSV с помощью Pandas в Python

Чтобы разделить изображения на папки на основе меток CSV с помощью pandas в Python, вы можете использовать несколько методов. Вот несколько подходов:

Метод 1. Использование pandas и Shutil

import pandas as pd
import shutil
import os
# Read the label CSV file
labels_df = pd.read_csv('labels.csv')
# Iterate over each row in the CSV
for index, row in labels_df.iterrows():
    image_file = row['image_file']
    label = row['label']

    # Create a folder if it doesn't exist
    folder_path = os.path.join('output', label)
    os.makedirs(folder_path, exist_ok=True)

    # Move the image file to the corresponding folder
    shutil.move(image_file, folder_path)

Метод 2. Использование pandas и операционной системы

import pandas as pd
import os
# Read the label CSV file
labels_df = pd.read_csv('labels.csv')
# Iterate over each row in the CSV
for index, row in labels_df.iterrows():
    image_file = row['image_file']
    label = row['label']

    # Create a folder if it doesn't exist
    folder_path = os.path.join('output', label)
    os.makedirs(folder_path, exist_ok=True)

    # Copy the image file to the corresponding folder
    os.rename(image_file, os.path.join(folder_path, os.path.basename(image_file)))

Метод 3: использование pandas и Pathlib

import pandas as pd
from pathlib import Path
# Read the label CSV file
labels_df = pd.read_csv('labels.csv')
# Iterate over each row in the CSV
for index, row in labels_df.iterrows():
    image_file = row['image_file']
    label = row['label']

    # Create a folder if it doesn't exist
    folder_path = Path('output') / label
    folder_path.mkdir(parents=True, exist_ok=True)

    # Move the image file to the corresponding folder
    Path(image_file).rename(folder_path / Path(image_file).name)

Эти методы используют pandas для чтения CSV-файла метки и перебора каждой строки. Они создают папки на основе меток и перемещают/копируют соответствующие файлы изображений в соответствующие папки.