ImageFolder假设所有的文件按文件夹保存,每个文件夹下存储同一个类别的图片,文件夹名为类名,其构造函数如下
ImageFolder(root, transform = None, target_transform = None, loader = default_loader)
root -- 在root指定的路径下寻找图片
transform -- 对PIL Image 进行转换操作, transform的输入是使用load读入图片的返回对象
target_transform -- 对label进行转换
loader -- 指定加载图片的函数,默认操作是读取PIL Image对象
其中label是按照文件名顺序排序后存成字典的,即{类名:类序号(从0开始)}
可以通过self.class_to_idx属性了解label和文件名的映射关系
报错
RuntimeError: Found 0 files in subfolders of: D:/pycharm/PyTorch/dogcatdataset/dogcat/
Supported extensions are: .jpg,.jpeg,.png,.ppm,.bmp,.pgm,.tif
解决方法
路径问题
root下应该包含对应标签的子文件夹`
举例:
In:
from torchvision.datasets import ImageFolder
dataset = ImageFolder("D:/pycharm/PyTorch/dogcatdataset/dogcat/")
print(dataset.class_to_idx)
Out:
{'cat': 0, 'dog': 1}
In:
dataset.imgs
Out:
[('D:/pycharm/PyTorch/dogcatdataset/dogcat/cat\\cat.4001.jpg', 0),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/cat\\cat.4002.jpg', 0),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/cat\\cat.4003.jpg', 0),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/cat\\cat.4004.jpg', 0),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/dog\\dog.4001.jpg', 1),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/dog\\dog.4002.jpg', 1),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/dog\\dog.4003.jpg', 1),
('D:/pycharm/PyTorch/dogcatdataset/dogcat/dog\\dog.4004.jpg', 1)]
In:
dataset[0][1] # 第一维表示第几张图片,第二维是1返回的是label
Out:
0
dataset[0][0] # 第二维是0,返回的是图片
加上transform
Transform = T.Compose([
T.RandomCrop(224),
T.RandomHorizontalFlip(), # transforms.RandomHorizontalFlip(p=0.5) 依概率p垂直翻转
T.ToTensor(),
normalize
])
dataset = ImageFolder("D:/pycharm/PyTorch/dogcatdataset/dogcat/", transform = Transform)
In:
dataset[0][0].size()
Out:
torch.Size([3, 224, 224])