【问题标题】:Read multiple images from a directory and turn them into .csv files从一个目录中读取多个图像并将它们转换为 .csv 文件
【发布时间】:2019-07-27 09:44:26
【问题描述】:

我正在尝试获取一个装满图像的文件夹并将它们转换为数组,将每个数组展平为 1 行,并将输出另存为单个 .csv 文件和一个集体 .csv 文件。

import numpy as np
import cv2

IMG_DIR = 'directory'
for img in os.listdir(IMG_DIR):
    img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE)
    img_array = np.array(img_array)
    img_array = (img_array.flatten())
    print(img_array)
    np.savetxt('output.csv', img_array)

我有上传所有所需图像的目录,PowerShell 显示所有图像都已转换为一维数组,但只有最后一张图像保存在 .csv 中。 还有没有办法将一维数组保存为行而不是列?

【问题讨论】:

    标签: python arrays image csv numpy


    【解决方案1】:

    您使用与输出文件相同的名称,并且在写入时,您会删除该文件包含的所有先前数据。执行此操作的一种方法是之前以附加模式打开文件:

    import numpy as np
    import cv2
    
    IMG_DIR = 'directory'
    
    for img in os.listdir(IMG_DIR):
            img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE)
            # unnecesary because imread already returns a numpy.array
            #img_array = np.array(img_array)
            img_array = (img_array.flatten())
            # add one dimension back to the array and 
            # transpose it to have the a row matrix instead of a column matrix
            img_array  = img_array.reshape(-1, 1).T
            print(img_array)
            # opening in binary and append mode
            with open('output.csv', 'ab') as f:
                # expliciting the delimiter as a comma
                np.savetxt(f, img_array, delimiter=",")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2013-01-07
      • 2018-04-29
      相关资源
      最近更新 更多