简体   繁体   中英

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

I am trying to take a folder full of images and turn them into arrays, flatten each array into 1 line, and save the output as individual .csv files and as one collective .csv file.

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)

I have the directory uploading all of the desired images and PowerShell shows that all of the images were converted into 1D arrays but only the last image is saved in the .csv. Also is there a way to save the 1D array as a row instead of a column?

You are using the same name as output file and when writing, you erase all previous data that this file contained. One way to perform this is opening the file previously in the append mode:

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=",")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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