How to load multiple images in a numpy array ?

前端 未结 3 461
余生分开走
余生分开走 2020-12-31 00:28

How to load pixels of multiple images in a directory in a numpy array . I have loaded a single image in a numpy array . But can not figure out how to load multiple images fr

3条回答
  •  误落风尘
    2020-12-31 01:23

    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 (hat tip: tegan). 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')
    

    For more information, see the numpy docs for dump and load.

提交回复
热议问题