How to upload multiple PPM files present in a folder as a single Numpy ndarray?

The following Python code creates a list of a numpy array. I want to load datasets as a numpy array with size K x M x N x 3, where Kis the image index and M x N x 3is the size of a single image. How can I modify existing code to do this?

    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)
-one
source share
1 answer

You can initialize the output array of this form and once inside the loop, index on 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

If you do not know Kin advance, we can get it using len(glob.glob(path+"/*.ppm")).

+2
source

All Articles