Search code examples
pythonnumpyopencvimage-processingglob

read dynamic number of images of same shape into Python NumPy array


I have this code:

image_list = []
for filename in glob.glob('C:\\Users\\Utilizador\\Desktop\\menu\\*.jpg'): 
    im=cv2.imread(filename)
    image_list.append(im)

This creates me a list of images, but I need it to be in an array form with shape (num_of_images, width, height, 3)

All images have the same shape Any ideas? Thanks


Solution

  • Since all images have same shape, we can create an empty array and then read each image into that.

    In [103]: file_path = 'C:\\Users\\Utilizador\\Desktop\\menu\\*.jpg'
    In [104]: num_imgs = len(glob.glob(file_path))
    In [105]: width, height, channels = 512, 512, 3
    
    In [106]: batch_arr = np.empty((num_imgs, width, height, channels), dtype=np.uint8)
    
    In [107]: for idx, filename in enumerate(glob.glob(file_path)):
                  img = cv2.imread(filename)
                  # if img is of different width and height than defined above
                  # do some resize and then insert in the array.
                  batch_arr[idx] = img