【问题标题】:How do I replace the name of an image with its classification? The classification are in a csv file如何将图像的名称替换为其分类?分类在 csv 文件中
【发布时间】:2019-09-23 16:48:49
【问题描述】:

我正在对要在神经网络上使用的数据进行预处理,并且我将一些照片保存在一个文件夹中,这些照片以数字命名(1.png、2.png、3.png)。另外,我有一个 csv,其中包含文件夹中每个图像的分类。 csv文件的结构如下:

文件名;类

例子:

1.png;cat
2.png;dog
3.png;cat

我想要做的是,使用 csv,将照片的名称替换为它的分类 + 它的名称。

最后,每张图片的名字的结果是:cat_1.png, dog_2.png, cat_3.png。

我正在使用 python 3 和 jupyter 进行开发。

你能帮帮我吗?

【问题讨论】:

    标签: python csv dataframe dataset classification


    【解决方案1】:
    import pandas as pd
    import os
    
    csv= pd.read_csv('path_to.csv')
    
    path_to_imgs = os.path.join('path','to','img')
    
    def rename_files(row):
        column_class = row['column of class in csv']
        file_name = row['column of file name in csv']
        new_file_name = f'{column_class}_{file_name}'
        os.rename(
            os.path.join(path_to_imgs, file_name),
            os.path.join(path_to_imgs, new_file_name)
        )
    
    csv.apply(rename_files, axis=1)
    

    读取 csv 文件,创建一个函数 (rename_files),在 csv 文件上逐行将 csv 中的旧名称 (file_name) 更改为新格式 (new_file_name)。

    【讨论】:

    • 通过一些小的调整,您的代码对我有用!只做语法调整:用“def”代替“function”,把“class”改成别的名字,因为是保留字。谢谢!
    • @ThiagoMoreira 哈哈哈我不知道我为什么要输入这些东西哈哈哈我会编辑答案:)
    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多