64

Loading and saving images in OpenCV is quite limited, so... what is the preferred ways to load all images from a given folder? Should I search for files in that folder with .png or .jpg extensions, store the names and use imread with every file? Or is there a better way?

0

11 Answers 11

79

Why not just try loading all the files in the folder? If OpenCV can't open it, oh well. Move on to the next. cv2.imread() returns None if the image can't be opened. Kind of weird that it doesn't raise an exception.

import cv2
import os

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        img = cv2.imread(os.path.join(folder,filename))
        if img is not None:
            images.append(img)
    return images
0
31

I used skimage. You can create a collection and access elements the standard way, i.e. col[index]. This will give you the RGB values.

from skimage.io import imread_collection

#your path 
col_dir = 'cats/*.jpg'

#creating a collection with the available images
col = imread_collection(col_dir)
1
  • If I have the following scheme: many folders with images, how can I read them all? For instance folders with other folders inside and images... Jul 2, 2022 at 9:50
28
import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
    n= cv2.imread(img)
    cv_img.append(n)`
3
  • 2
    This works but the files are not in any particular order. Oct 20, 2019 at 16:58
  • 2
    Just sort it by list = sort(glob.glob("Path/to/dir/*.jpg"))).
    – shinxg
    Jan 11, 2020 at 12:06
  • even better if you use natsorted(glob.glob("Path/to/dir/*.jpg"))): pypi.org/project/natsort Sep 26, 2022 at 8:40
20

If all images are of the same format:

import cv2
import glob

images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]

For reading images of different formats:

import cv2
import glob

imdir = 'path/to/files/'
ext = ['png', 'jpg', 'gif']    # Add image formats here

files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]

images = [cv2.imread(file) for file in files]
3
  • Once I have images instantiated (images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]) how can they be displayed in a window?
    – ThomasATU
    Jul 14, 2020 at 20:25
  • for im in images: plt.figure() plt.imshow(im)
    – Nirmal
    Jul 15, 2020 at 7:37
  • AttributeError: 'numpy.ndarray' object has no attribute 'seek'
    – Dr.jacky
    Oct 20, 2022 at 20:26
12

you can use glob function to do this. see the example

import cv2
import glob
for img in glob.glob("path/to/folder/*.png"):
    cv_img = cv2.imread(img)
10

You can also use matplotlib for this, try this out:

import matplotlib.image as mpimg

def load_images(folder):
    images = []
    for filename in os.listdir(folder):
        img = mpimg.imread(os.path.join(folder, filename))
        if img is not None:
            images.append(img)
    return images
1
  • @Nirmal yeah, for other file formats are also supported though for that you need Pillow to be installed. Mar 26, 2019 at 11:31
6
import os
import cv2
rootdir = "directory path"
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        frame = cv2.imread(os.path.join(subdir, file)) 

1
  • 4
    While this code may provide a solution to the OP's question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. Jan 27, 2020 at 6:05
0

To add onto the answer from Rishabh and make it able to handle files that are not images that are found in the folder.

import matplotlib.image as mpimg

images = []
folder = './your/folder/'
for filename in os.listdir(folder):
    try:
        img = mpimg.imread(os.path.join(folder, filename))
        if img is not None:
            images.append(img)
    except:
        print('Cant import ' + filename)
images = np.asarray(images)
0

Here is a simple script that feature opencv, scikit image, and glob

#!C:\Users\test\anaconda3\envs\data_aquisition\python.exe
import glob
import argparse
from timeit import default_timer as timer
import skimage
from skimage.io import imread_collection
import cv2 


def get_args():
    parser = argparse.ArgumentParser(
        description='script that test the fastest image loading methods')
    parser.add_argument('src_path', help = "diractorry that contains the ims")
    parser.add_argument('extension', help = "extension of the images",choices=['jpg','png','webp'])
    return parser.parse_args()

def load_imgs_scikit_image_collection(path:str):
    #creating a collection with the available images 
    col = imread_collection(path)
    print('loaded: ',len(col),' imgs')
    return col

def load_imgs_scikit_image_glob(path):
    imgs = []
    for img in glob.glob(path):
        imgs.append(skimage.io.imread(img))
    return imgs

def load_image_opencv(path:str):
    imgs = []
    for f in glob.glob(path):
        imgs.extend(cv2.imread(f))
    return imgs  

def load_image_opencv_glob(path:str):
    filenames = glob.glob(path)
    filenames.sort()
    images = [cv2.imread(img) for img in filenames]
    return images

def laod_images_opencv_extisions(path):
    ext = [".jpg",".gif",".png",".tga",".webp"]   # Add image formats here
    files = []
    images = []
    [files.extend(glob.glob(path + '/*' + e)) for e in ext]
    images.extend([cv2.imread(file) for file in files])
    return images

def laod_images_ski_extisions(path):
    ext = [".jpg",".gif",".png",".tga",".webp"]   # Add image formats here
    files = []
    images = []
    [files.extend(glob.glob(path + '/*' + e)) for e in ext]
    images.extend([skimage.io.imread(file) for file in files])
    return images

def show_image(img):
    window_name = 'image'
    cv2.imshow(window_name, img)
    cv2.waitKey(0) 
    cv2.destroyAllWindows() 


def main():

    args = get_args()
    dir = args.src_path+'/*.'+args.extension
    start = timer()
    imgs=load_imgs_scikit_image_collection(dir)
    end = timer()
    print('scikit_image image collection',end - start) #time 0.08381089999999991
    show_image(imgs[2])

    start = timer()
    load_imgs_scikit_image_glob(dir)
    end = timer()
    print('scikit_image and glob',end - start) #time 16.627431599999998
    # dir = args.src_path+'\\.*'+args.extension

    start = timer()
    imgs_opencv = load_image_opencv_glob(dir) #time 10.9856656
    end = timer()
    print('opencv glob',end - start) 
    show_image(imgs_opencv[2]) 

    start = timer()
    valid_imgs_opencv = laod_images_opencv_extisions(args.src_path) #time 11.318516700000004
    end = timer()
    print('opencv glob extensions',end - start) 
    show_image(valid_imgs_opencv[2])

    start = timer()
    valid_imgs_opencv = laod_images_ski_extisions(args.src_path) #time 15.939870800000001
    end = timer()
    print('scikit_image glob extensions',end - start) 
    show_image(valid_imgs_opencv[2])


main()

Command to run script: python best_image_loader.py D:\data\dataset\radar_dome\manual png
png is used to load only png files.

Output

loaded:  876  imgs
scikit_image image collection 0.08248239999999996
scikit_image and glob 14.939381200000001
opencv glob 10.9708085
opencv glob extensions 10.974014100000005
scikit_image glob extensions 14.877048600000002
-1
your_path = 'your_path'

ext = ['*.jpg', '*.png', '*.gif']    # Add image formats here

 images = []
 not_copy = 0
 for item in [your_path + '/' + e for e in ext]:
      images += glob(item)
0
-1

There is a simple way to do this using os.listDir.

import os

img_path = 'your image directory goes here'
image_formats = [".jpg", ".jpeg", ".png"]
images = [file for file in dirListing if os.path.splitext(file) 
[1].lower() in image_formats]
print(images)

That's it. pretty simple, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.