BasicSR

Форк
0
/
single_image_dataset.py 
68 строк · 2.6 Кб
1
from os import path as osp
2
from torch.utils import data as data
3
from torchvision.transforms.functional import normalize
4

5
from basicsr.data.data_util import paths_from_lmdb
6
from basicsr.utils import FileClient, imfrombytes, img2tensor, rgb2ycbcr, scandir
7
from basicsr.utils.registry import DATASET_REGISTRY
8

9

10
@DATASET_REGISTRY.register()
11
class SingleImageDataset(data.Dataset):
12
    """Read only lq images in the test phase.
13

14
    Read LQ (Low Quality, e.g. LR (Low Resolution), blurry, noisy, etc).
15

16
    There are two modes:
17
    1. 'meta_info_file': Use meta information file to generate paths.
18
    2. 'folder': Scan folders to generate paths.
19

20
    Args:
21
        opt (dict): Config for train datasets. It contains the following keys:
22
            dataroot_lq (str): Data root path for lq.
23
            meta_info_file (str): Path for meta information file.
24
            io_backend (dict): IO backend type and other kwarg.
25
    """
26

27
    def __init__(self, opt):
28
        super(SingleImageDataset, self).__init__()
29
        self.opt = opt
30
        # file client (io backend)
31
        self.file_client = None
32
        self.io_backend_opt = opt['io_backend']
33
        self.mean = opt['mean'] if 'mean' in opt else None
34
        self.std = opt['std'] if 'std' in opt else None
35
        self.lq_folder = opt['dataroot_lq']
36

37
        if self.io_backend_opt['type'] == 'lmdb':
38
            self.io_backend_opt['db_paths'] = [self.lq_folder]
39
            self.io_backend_opt['client_keys'] = ['lq']
40
            self.paths = paths_from_lmdb(self.lq_folder)
41
        elif 'meta_info_file' in self.opt:
42
            with open(self.opt['meta_info_file'], 'r') as fin:
43
                self.paths = [osp.join(self.lq_folder, line.rstrip().split(' ')[0]) for line in fin]
44
        else:
45
            self.paths = sorted(list(scandir(self.lq_folder, full_path=True)))
46

47
    def __getitem__(self, index):
48
        if self.file_client is None:
49
            self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)
50

51
        # load lq image
52
        lq_path = self.paths[index]
53
        img_bytes = self.file_client.get(lq_path, 'lq')
54
        img_lq = imfrombytes(img_bytes, float32=True)
55

56
        # color space transform
57
        if 'color' in self.opt and self.opt['color'] == 'y':
58
            img_lq = rgb2ycbcr(img_lq, y_only=True)[..., None]
59

60
        # BGR to RGB, HWC to CHW, numpy to tensor
61
        img_lq = img2tensor(img_lq, bgr2rgb=True, float32=True)
62
        # normalize
63
        if self.mean is not None or self.std is not None:
64
            normalize(img_lq, self.mean, self.std, inplace=True)
65
        return {'lq': img_lq, 'lq_path': lq_path}
66

67
    def __len__(self):
68
        return len(self.paths)
69

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.