如何加载文件夹中存在的多个PPM文件作为单个Numpy ndarray? [英] How to load mutiple PPM files present in a folder as single Numpy ndarray?

查看:159
本文介绍了如何加载文件夹中存在的多个PPM文件作为单个Numpy ndarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Python代码创建numpy数组列表。我希望将数据集加载为具有维度 K x M x N x 3 的numpy数组,其中 K 是图像的索引, M x N x 3 是单个图像的维度。如何修改现有代码呢?

The following Python code creates list of numpy array. I want to load by data sets as a numpy array that has dimension K x M x N x 3 , where K is the index of the image and M x N x 3 is the dimension of individual image. How can I modify the existing code to do so ?

    image_list=[]
    for filename in glob.glob(path+"/*.ppm"):
        img = imread(filename,mode='RGB')
        temp_img = img.reshape(img.shape[0]*img.shape[1]*img.shape[2],1)
        image_list.append(temp_img)


推荐答案

你可以初始化那个形状的输出数组,一旦进入循环,就可以索引第一个轴来迭代地分配图像数组 -

You could initialize an output array of that shape and once inside the loop, index into the first axis to assign image arrays iteratively -

out = np.empty((K,M,N,3), dtype=np.uint8) # change dtype if needed
for i,filename in enumerate(glob.glob(path+"/*.ppm")):
    # Get img of shape (M,N,3)
    out[i] = img

如果你事先不知道 K ,我们可以用 len(glob)得到它.glob(路径+/ * .ppm))

If you don't know K beforehand, we could get it with len(glob.glob(path+"/*.ppm")).

这篇关于如何加载文件夹中存在的多个PPM文件作为单个Numpy ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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