File size: 2,226 Bytes
c388140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from __future__ import annotations

import os
from typing import List, Sequence, Tuple

from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision import transforms as T


_IMG_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp")


def _list_images(root: str) -> List[str]:
    paths: List[str] = []
    for dirpath, _, filenames in os.walk(root):
        for fn in filenames:
            if fn.lower().endswith(_IMG_EXTS):
                paths.append(os.path.join(dirpath, fn))
    paths.sort()
    return paths


class TextureFolderDataset(Dataset):
    """
    纹理图片数据集:
    - 读取目录下所有图片(含子目录)
    - 统一转换为 RGB
    - 缩放到 16×16
    - 输出范围为 [-1, 1] 的张量(C,H,W)
    """

    def __init__(
        self,
        root_dir: str,
        image_size: int = 16,
        channels: int = 3,
        random_flip: bool = True,
    ):
        self.root_dir = root_dir
        self.image_size = int(image_size)
        self.channels = int(channels)
        if self.channels not in (3, 4):
            raise ValueError("channels 仅支持 3(RGB) 或 4(RGBA)")

        self.paths = _list_images(root_dir)
        if len(self.paths) == 0:
            raise ValueError(f"数据集目录为空或未找到图片:{root_dir}")

        tfms = [
            T.Resize((self.image_size, self.image_size), interpolation=T.InterpolationMode.NEAREST),
        ]
        if random_flip:
            tfms.append(T.RandomHorizontalFlip(p=0.5))
        tfms.extend(
            [
                T.ToTensor(),  # [0,1]
                # 用 Normalize 替代 lambda,保证 Windows 多进程 DataLoader 可 pickle
                T.Normalize(mean=[0.5] * self.channels, std=[0.5] * self.channels),  # [-1,1]
            ]
        )
        self.transform = T.Compose(tfms)

    def __len__(self) -> int:
        return len(self.paths)

    def __getitem__(self, idx: int) -> torch.Tensor:
        path = self.paths[idx]
        # 使用 nearest resize,尽量保留像素风格边缘
        with Image.open(path) as im:
            im = im.convert("RGBA" if self.channels == 4 else "RGB")
            x = self.transform(im)
        return x