Loading all images using imread from a given folder

后端 未结 8 1992
长发绾君心
长发绾君心 2021-01-30 21:48

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

相关标签:
8条回答
  • 2021-01-30 22:01
    import glob
    cv_img = []
    for img in glob.glob("Path/to/dir/*.jpg"):
        n= cv2.imread(img)
        cv_img.append(n)`
    
    0 讨论(0)
  • 2021-01-30 22:03
    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)) 
    
    
    0 讨论(0)
  • 2021-01-30 22:13

    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]
    
    0 讨论(0)
  • 2021-01-30 22:18

    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 讨论(0)
  • 2021-01-30 22:19

    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 讨论(0)
  • 2021-01-30 22:19

    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)
    
    0 讨论(0)
提交回复
热议问题