如何在numpy数组中加载多个图像? [英] How to load multiple images in a numpy array ?

查看:95
本文介绍了如何在numpy数组中加载多个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在numpy数组的目录中加载多个图像的像素.我已经在numpy数组中加载了单个图像.但是无法弄清楚如何从目录中加载多个图像.这是我到目前为止所做的事情

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 from a directory . Here what i have done so far

image = Image.open('bn4.bmp')
nparray=np.array(image)

这将加载32 * 32矩阵.我想在numpy数组中加载100张图像.我想做100 * 32 * 32大小的numpy array.我怎样才能做到这一点 ?我知道结构看起来像这样

This loads a 32*32 matrices . I want to load 100 of the images in a numpy array . I want to make 100*32*32 size numpy array . How can i do that ? I know that the structure would look something like this

for filename in listdir("BengaliBMPConvert"):
  if filename.endswith(".bmp"):
       -----------------
  else:
       continue

但是无法找出如何将图像加载到numpy数组中

But can not find out how to load the images in numpy array

推荐答案

获取BMP文件列表

要从目录BengaliBMPConvert中获取BMP文件列表,请使用:

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'

将所有图像组合成一个numpy数组

要将所有图像组合到一个阵列中:

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])

酸洗一个numpy数组

要使用pickle将numpy数组保存到文件中,

Pickling a numpy array

To save a numpy array to file using pickle:

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

其中,x是要保存的numpy数组,filehandle是pickle文件的句柄,例如open('filename.p', 'wb'),并且protocol=2告诉pickle使用其当前格式,而不是某些古老的格式.日期格式.

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.

或者,可以使用numpy提供的方法来腌制numpy数组(提示: tegan ).要在文件file.npy中转储数组x,请使用:

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')

要从文件重新加载数组x:

To load array x back in from file:

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

有关更多信息,请参见转储 load .

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

这篇关于如何在numpy数组中加载多个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆