DEV1205
DEV1205

Reputation: 372

Read multiple images using glob (Python) and save them in csv

Trying to read several images from a local folder and save them to csv using numpy.savetxt. Using following code

filelist = glob.glob('Filepath/*.png')
x = np.array([np.array(Image.open(fname)) for fname in filelist])
print(x.shape)
np.savetxt('csvfile.csv', x,fmt='%s')

Want this code to save one image as one row in the csv in one column. But this is storing array in 2 columns and not seperating the array to new line. As in the image second array is stored just after the first one and not to the new row.

[252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252] [252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252 252...

Upvotes: 2

Views: 831

Answers (1)

horizon
horizon

Reputation: 77



I think you could try with glob.glob, what should help


import numpy as np
import glob
import cv2
import csv

Libraries ⬆️; You know what⬇️

image_list = []

for filename in glob.glob(r'C:\your path to\file*.png'):    # '*' will count files each by one
    
    #Read
    img = cv2.imread(filename)
    flattened = img.flatten() 
    print(flattened) # recommend to avoid duplicates, see files and so on.

    #Save
    with open('output2.csv', 'ab') as f: #ab is set 
            np.savetxt(f, flattened, delimiter=",")

Cheers

Upvotes: 1

Related Questions