imagenet_dataset.py 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

L
LielinJiang 已提交
15 16 17 18 19 20
import os
import cv2
import math
import random
import numpy as np

L
LielinJiang 已提交
21 22
from paddle.incubate.hapi.datasets import DatasetFolder
from paddle.incubate.hapi.vision.transforms import transforms
L
LielinJiang 已提交
23
from paddle import fluid
L
LielinJiang 已提交
24 25


L
LielinJiang 已提交
26
class ImageNetDataset(DatasetFolder):
L
LielinJiang 已提交
27 28 29 30 31
    def __init__(self,
                 path,
                 mode='train',
                 image_size=224,
                 resize_short_size=256):
L
LielinJiang 已提交
32
        super(ImageNetDataset, self).__init__(path)
L
LielinJiang 已提交
33
        self.mode = mode
L
LielinJiang 已提交
34 35 36

        normalize = transforms.Normalize(
            mean=[123.675, 116.28, 103.53], std=[58.395, 57.120, 57.375])
L
LielinJiang 已提交
37
        if self.mode == 'train':
L
LielinJiang 已提交
38
            self.transform = transforms.Compose([
L
LielinJiang 已提交
39
                transforms.RandomResizedCrop(image_size),
L
LielinJiang 已提交
40 41
                transforms.RandomHorizontalFlip(),
                transforms.Permute(mode='CHW'), normalize
L
LielinJiang 已提交
42 43
            ])
        else:
L
LielinJiang 已提交
44
            self.transform = transforms.Compose([
L
LielinJiang 已提交
45 46
                transforms.Resize(resize_short_size),
                transforms.CenterCrop(image_size),
L
LielinJiang 已提交
47 48
                transforms.Permute(mode='CHW'), normalize
            ])
L
LielinJiang 已提交
49 50

    def __getitem__(self, idx):
L
LielinJiang 已提交
51 52
        img_path, label = self.samples[idx]
        img = cv2.imread(img_path).astype(np.float32)
L
LielinJiang 已提交
53
        label = np.array([label]).astype(np.int64)
L
LielinJiang 已提交
54
        return self.transform(img), label
L
LielinJiang 已提交
55 56 57

    def __len__(self):
        return len(self.samples)