【问题标题】:How to put a column of picture names to the csv file of arrays?如何将一列图片名称放入数组的csv文件中?
【发布时间】:2021-08-18 21:38:06
【问题描述】:

这是我在这里的第一个问题,如果我做错了,我很抱歉。

我有一个包含图片的文件夹,我将其转换为数组并使用 Python 3 放入一个 csv 文件。它工作正常,但我想在 csv 文件的开头添加图片的名称作为一行。如果有帮助,我也有单独文件中的图片(如标签),我还可以遍历单独的文件夹并将文件夹的名称添加为 csv 文件左侧的一行,但我确实需要所有最后将数组放在同一个 csv 文件中。我怎样才能做到这一点?这是我用来将图像转换为数组并保存为 csv 文件的代码:

import numpy as np
import os
import cv2

IMG_DIR = '../train'

for img in os.listdir(IMG_DIR):
        img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE)
        if img_array is not None:
            img_array = (img_array.flatten())
        img_array  = img_array.reshape(-1, 1).T
        with open('train.csv', 'ab') as f:
            np.savetxt(f, img_array, delimiter=",")
        print(img_array)
            

【问题讨论】:

    标签: python arrays numpy csv opencv


    【解决方案1】:

    改进的答案(生成每行包含 filename, pixel_value_array 的 csv 文件)

    with open("train2.csv", "w") as f:
        for img_name in os.listdir(IMG_DIR):
            img_array = cv2.imread(os.path.join(IMG_DIR, img_name), cv2.IMREAD_GRAYSCALE)
            f.write(img_name + ",")
            np.savetxt(f, img_array.reshape((1, -1)), delimiter=",")
    

    原答案:先写下所有文件名,再追加数组数据。

    images = os.listdir(IMG_DIR)
    with open("train.csv", "w") as f:
        f.write("\n".join(images) + "\n")
    for img in images:
        img_array = cv2.imread(os.path.join(IMG_DIR, img), cv2.IMREAD_GRAYSCALE)
        img_array = img_array.reshape(-1, 1).T
        with open("train.csv", "ab") as f:
            np.savetxt(f, img_array, delimiter=",")
    

    【讨论】:

    • 非常感谢您的帮助。这确实添加了带有文件名称的行,但该列的其余部分为空并且与数组不匹配:(
    • 请更清楚地解释您希望 csv 文件的外观。你希望它喜欢这个吗? `filename1.png, 0.0, 3.0, 4.0, ... \n filename2.png, 0.0, 0.0, 255.0 ... \EOF
    • 没错!我希望第一行是文件的名称,其余行是该图像中的数组。
    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 2013-08-21
    • 2019-03-30
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多