close

How to load multiple images in a numpy array ?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to load multiple images in a numpy array in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to load multiple images in a numpy array ?

  1. How to load multiple images in a numpy array ?

    where x is the numpy array to be save, filehandle is the handle for the pickle file, such as open('filename.p', 'wb'), and protocol=2 tells pickle to use its current format rather than some ancient out-of-date format.

  2. load multiple images in a numpy array

    where x is the numpy array to be save, filehandle is the handle for the pickle file, such as open('filename.p', 'wb'), and protocol=2 tells pickle to use its current format rather than some ancient out-of-date format.

Method 1

Getting a list of BMP files

To get a list of BMP files from the directory BengaliBMPConvert, use:

import glob
filelist = glob.glob('BengaliBMPConvert/*.bmp')

On the other hand, if you know the file names already, just put them in a sequence:

filelist = 'file1.bmp', 'file2.bmp', 'file3.bmp'

Combining all the images into one numpy array

To combine all the images into one array:

x = np.array([np.array(Image.open(fname)) for fname in filelist])

Pickling a numpy array

To save a numpy array to file using pickle:

import pickle
pickle.dump( x, filehandle, protocol=2 )

where x is the numpy array to be save, filehandle is the handle for the pickle file, such as open('filename.p', 'wb'), and protocol=2 tells pickle to use its current format rather than some ancient out-of-date format.

Alternatively, numpy arrays can be pickled using methods supplied by numpy. To dump array x in file file.npy, use:

x.dump('file.npy')

To load array x back in from file:

x = np.load('file.npy')

Method 2

Use OpenCV’s imread() function together with os.listdir(), like

import numpy as np
import cv2
import os

instances = []

# Load in the images
for filepath in os.listdir('images/'):
    instances.append(cv2.imread('images/{0}'.format(filepath),0))

print(type(instances[0]))

class ‘numpy.ndarray’

This returns you a list (==instances) in which all the greyscale values of the images are stored. For colour images simply set .format(filepath),1.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read