Add images to pandas dataframe rows

Viewed 1557

I would like to load images from a folder , convert them to numpy arrays and then store them as dataframe rows. How should I proceed?

Here's what I came up with:

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img

BASE_DIR = '/kaggle/input/coughspectrograms/content/'
os.chdir('/kaggle/input/coughspectrograms/content/')

files_in_train = sorted(os.listdir(BASE_DIR))
files_in_train.pop(0)
img_df = pd.DataFrame()

for img in files_in_train: 
    loaded_img = load_img(img)
    img_array = img_to_array(loaded_img)

    img_df = pd.DataFrame({"image": [img_array]})
1 Answers

If you want to have a final dataframe of shape [n_images, 1] you can simply replace the last line in your code with:

img_df = img_df.append({"image": [img_array]}, ignore_index=True)

This will iteratively add a row to the empty dataframe you created, what you're doing now is just creating a new data frame with a single image at each iteration

Related