简体   繁体   中英

How do I create a list of all my folder ('train') images in OpenCV

I have 399 images in my folder called 'train_images', I'd like to create a list of all these images in my openCV like ('cv2.imread(list)')

TRAIN_DIR = 'train_data/'
TEST_DIR = 'test_data/'

train_path = glob.glob("train_data/*.ppm")

train_path.sort()

train_images = [cv2.imread(img) for img in train_path]


train_images = train_images.reshape(train_images.shape[0], 512, 512, 1).astype('float32')

cv2.imshow('image',train_images[0])
cv2.waitKey(0)
cv2.destroyAllWindows()

In this part of the code:

train_images = [cv2.imread(img) for img in train_path]
train_images = train_images.reshape(train_images.shape[0], 512, 512, 1).astype('float32')

Problem is that train_images is a list, not a numpy array. Only numpy arrays have the reshape and astype methods. But the solution is quite simple, just convert train_images into a numpy array:

import numpy as np

train_images = [cv2.imread(img) for img in train_path]
train_images = np.array(train_images)

train_images = train_images.reshape(train_images.shape[0], 512, 512, 1).astype('float32')

Why do you want to load all images into memory? A better way would be if you read the directory and create a list with the path of all images.

def ReadFiles(Path):
    ImageList = list()
    LabelList = list()

    # Get all subdirectories
    FolderList = os.listdir(Path)

    # Loop over each directory
    for File in FolderList:
        if(os.path.isdir(Path + os.path.sep + File)):
            for Image in os.listdir(Path + os.path.sep + File):
                # Add the image path to the list
                ImageList.append(Path + os.path.sep + File + os.path.sep + Image)

                # Add a label for each image and remove the file extension
                LabelList.append(File.split(".")[0])
        else:
            ImageList.append(Path + os.path.sep + File)

            # Add a label for each image and remove the file extension
            LabelList.append(File.split(".")[0])

    return ImageList, LabelList

Now you can store all images into an HDF5 file and/or use a generator to load the files in small batches into the network. The advantage is that you can use image databases for the training which are larger than your physical RAM. See here and here if you need more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM