繁体   English   中英

从目录中读取多个图像并将其转换为.csv文件

[英]Read multiple images from a directory and turn them into .csv files

我正在尝试获取一个充满图像的文件夹,并将它们转换为数组,将每个数组展平为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显示所有图像都已转换为1D数组,但是只有最后一个图像保存在.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)
        # 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=",")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM