首页 > 解决方案 > 将加载的图像复制到测试、训练和验证文件夹

问题描述

在这里,我编写了一个加载图像的代码,然后我应该怎么做才能将这些图像分成三个文件夹;分别使用 70%、15% 和 15% 的比率进行训练、测试和验证。

      from os import listdir
        from PIL import Image as PImage
        import split_folders
        import os, os.path
        import numpy as np
        #imgs.append(Image.open(os.path.join(path,image))

        def loadImages(path):
            imagesList = listdir(path)
            loadedImages = []
            for image in imagesList:
                with open(os.path.join(path, image), 'rb') as i:
                    img = PImage.open(i)
                    loadedImages.append(img)
            return loadedImages

        path = "./Inputs/"
        imgs = loadImages(path)

        for img in imgs:
            print(img)




train, validate, test = np.split(imgs.sample(frac=1), [int(.7*len(imgs)), int(.85*len(imgs))])

这是错误的,因为它不支持列表对象

那么有什么解决办法吗?

标签: pythonimage-processing

解决方案


据我了解,函数loadImages返回 pythonlist对象。由于没有list.sample()方法,字符串

train, validate, test = np.split(imgs.sample(frac=1), [int(.7*len(imgs)), int(.85*len(imgs))])

是无效的。所以,有一些方法可以打乱所有数据;例如,您可以使用 intonumpy.random.shuffle就地重新排序列表值:

np.random.shuffle(imgs)  # now this list is shuffled
train, validate, test = np.split(imgs, [int(.7*len(imgs)), int(.85*len(imgs))])

注意, np.random.shuffle 保持对象的类型不变(如果它是一个列表)。我猜代码的其他部分是正确的。

lst = [1,2,3]
type(lst)
Out:
<class'list'>

np.random.shuffle(lst)

type(lst)
Out:
<class'list'>

另外,sample方法是pandas数据重采样的包默认方法之一,但我想你不需要pandas这里


推荐阅读