0

我正在尝试获取一个充满图像的文件夹并将它们转换为数组,将每个数组展平为 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 中。还有一种方法可以将一维数组保存为行而不是列?

4

1 回答 1

0

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

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=",")
于 2019-03-05T20:55:18.383 回答