chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:40:42 +08:00
commit e25996e7db
15472 changed files with 3536181 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
# 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.
from .cifar import Cifar10, Cifar100
from .flowers import Flowers
from .folder import DatasetFolder, ImageFolder
from .mnist import MNIST, FashionMNIST
from .voc2012 import VOC2012
__all__ = [
'DatasetFolder',
'ImageFolder',
'MNIST',
'FashionMNIST',
'Flowers',
'Cifar10',
'Cifar100',
'VOC2012',
]
+314
View File
@@ -0,0 +1,314 @@
# 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.
from __future__ import annotations
import os
import pickle
import tarfile
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Literal
import numpy as np
import numpy.typing as npt
from PIL import Image
import paddle
from paddle.dataset.common import _check_exists_and_download, md5file
from paddle.io import Dataset
if TYPE_CHECKING:
import numpy.typing as npt
from paddle._typing.dtype_like import _DTypeLiteral
from paddle.vision.transforms.transforms import _Transform
from ..image import _ImageBackend, _ImageDataType
_DatasetMode = Literal["train", "test"]
__all__ = []
URL_PREFIX = 'https://dataset.bj.bcebos.com/cifar/'
CIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz'
CIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a'
CIFAR100_URL = URL_PREFIX + 'cifar-100-python.tar.gz'
CIFAR100_MD5 = 'eb9058c3a382ffc7106e4002c42a8d85'
MODE_FLAG_MAP = {
'train10': 'data_batch',
'test10': 'test_batch',
'train100': 'train',
'test100': 'test',
}
@lru_cache(maxsize=8)
def _cached_md5file(path, _mtime_ns, _size):
return md5file(path)
def _check_local_cifar_md5(path, expected_md5):
path = os.path.abspath(path)
stat = os.stat(path)
file_md5 = _cached_md5file(path, stat.st_mtime_ns, stat.st_size)
if file_md5 != expected_md5:
raise ValueError(
"Loading unverified local CIFAR pickle archive is disabled. "
f"Please use the official archive with MD5 {expected_md5}."
)
class Cifar10(Dataset[tuple["_ImageDataType", "npt.NDArray[Any]"]]):
"""
Implementation of `Cifar-10 <https://www.cs.toronto.edu/~kriz/cifar.html>`_
dataset, which has 10 categories.
Args:
data_file (str|None, optional): Path to data file, can be set None if
:attr:`download` is True. Default None, default data path: ~/.cache/paddle/dataset/cifar
mode (str, optional): Either train or test mode. Default 'train'.
transform (Callable|None, optional): transform to perform on image, None for no transform. Default: None.
download (bool, optional): download dataset automatically if :attr:`data_file` is None. Default True.
backend (str|None, optional): Specifies which type of image to be returned:
PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_paddle_vision_get_image_backend>`,
default backend is 'pil'. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of Cifar10 dataset.
Examples:
.. code-block:: pycon
>>> # doctest: +TIMEOUT(60)
>>> import itertools
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import Cifar10
>>> cifar10 = Cifar10()
>>> print(len(cifar10))
50000
>>> for i in range(5): # only show first 5 images
... img, label = cifar10[i]
... # do something with img and label
... print(type(img), img.size, label)
... # <class 'PIL.Image.Image'> (32, 32) 6
>>> transform = T.Compose(
... [
... T.Resize(64),
... T.ToTensor(),
... T.Normalize(
... mean=[0.5, 0.5, 0.5],
... std=[0.5, 0.5, 0.5],
... to_rgb=True,
... ),
... ]
... )
>>> cifar10_test = Cifar10(
... mode="test",
... transform=transform, # apply transform to every image
... backend="cv2", # use OpenCV as image transform backend
... )
>>> print(len(cifar10_test))
10000
>>> for img, label in itertools.islice(iter(cifar10_test), 5): # only show first 5 images
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape, label)
... # <class 'paddle.Tensor'> [3, 64, 64] 3
"""
mode: _DatasetMode
backend: _ImageBackend
data_file: str | None
transform: _Transform[Any, Any] | None
dtype: _DTypeLiteral
def __init__(
self,
data_file: str | None = None,
mode: _DatasetMode = 'train',
transform: _Transform[Any, Any] | None = None,
download: bool = True,
backend: _ImageBackend | None = None,
) -> None:
assert mode.lower() in [
'train',
'test',
], f"mode.lower() should be 'train' or 'test', but got {mode}"
self.mode = mode.lower()
if backend is None:
backend = paddle.vision.get_image_backend()
if backend not in ['pil', 'cv2']:
raise ValueError(
f"Expected backend are one of ['pil', 'cv2'], but got {backend}"
)
self.backend = backend
self._init_url_md5_flag()
self.data_file = data_file
if self.data_file is None:
assert download, (
"data_file is not set and downloading automatically is disabled"
)
self.data_file = _check_exists_and_download(
data_file, self.data_url, self.data_md5, 'cifar', download
)
elif not os.path.exists(self.data_file):
raise ValueError(
f"Local CIFAR archive does not exist: {self.data_file}."
)
else:
_check_local_cifar_md5(self.data_file, self.data_md5)
self.transform = transform
# read dataset into memory
self._load_data()
self.dtype = paddle.get_default_dtype()
def _init_url_md5_flag(self):
self.data_url = CIFAR10_URL
self.data_md5 = CIFAR10_MD5
self.flag = MODE_FLAG_MAP[self.mode + '10']
def _load_data(self):
self.data = []
with tarfile.open(self.data_file, mode='r') as f:
names = (
each_item.name for each_item in f if self.flag in each_item.name
)
names = sorted(names)
for name in names:
batch = pickle.load(f.extractfile(name), encoding='bytes')
data = batch[b'data']
labels = batch.get(b'labels', batch.get(b'fine_labels', None))
assert labels is not None
for sample, label in zip(data, labels):
self.data.append((sample, label))
def __getitem__(self, idx: int) -> tuple[_ImageDataType, npt.NDArray[Any]]:
image, label = self.data[idx]
image = np.reshape(image, [3, 32, 32])
image = image.transpose([1, 2, 0])
if self.backend == 'pil':
image = Image.fromarray(image.astype('uint8'))
if self.transform is not None:
image = self.transform(image)
if self.backend == 'pil':
return image, np.array(label).astype('int64')
return image.astype(self.dtype), np.array(label).astype('int64')
def __len__(self):
return len(self.data)
class Cifar100(Cifar10):
"""
Implementation of `Cifar-100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_
dataset, which has 100 categories.
Args:
data_file (str|None, optional): path to data file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/cifar
mode (str, optional): Either train or test mode. Default 'train'.
transform (Callable|None, optional): transform to perform on image, None for no transform. Default: None.
download (bool, optional): download dataset automatically if :attr:`data_file` is None. Default True.
backend (str|None, optional): Specifies which type of image to be returned:
PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_paddle_vision_get_image_backend>`,
default backend is 'pil'. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of Cifar100 dataset.
Examples:
.. code-block:: pycon
>>> # doctest: +TIMEOUT(60)
>>> import itertools
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import Cifar100
>>> cifar100 = Cifar100()
>>> print(len(cifar100))
50000
>>> for i in range(5): # only show first 5 images
... img, label = cifar100[i]
... # do something with img and label
... print(type(img), img.size, label)
... # <class 'PIL.Image.Image'> (32, 32) 19
>>> transform = T.Compose(
... [
... T.Resize(64),
... T.ToTensor(),
... T.Normalize(
... mean=[0.5, 0.5, 0.5],
... std=[0.5, 0.5, 0.5],
... to_rgb=True,
... ),
... ]
... )
>>> cifar100_test = Cifar100(
... mode="test",
... transform=transform, # apply transform to every image
... backend="cv2", # use OpenCV as image transform backend
... )
>>> print(len(cifar100_test))
10000
>>> for img, label in itertools.islice(iter(cifar100_test), 5): # only show first 5 images
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape, label)
... # <class 'paddle.Tensor'> [3, 64, 64] 49
"""
def __init__(
self,
data_file: str | None = None,
mode: _DatasetMode = 'train',
transform: _Transform[Any, Any] | None = None,
download: bool = True,
backend: _ImageBackend | None = None,
) -> None:
super().__init__(data_file, mode, transform, download, backend)
def _init_url_md5_flag(self):
self.data_url = CIFAR100_URL
self.data_md5 = CIFAR100_MD5
self.flag = MODE_FLAG_MAP[self.mode + '100']
+216
View File
@@ -0,0 +1,216 @@
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
import numpy.typing as npt
from paddle.vision.transforms.transforms import _Transform
from ..image import _ImageBackend, _ImageDataType
_DatasetMode = Literal["train", "valid", "test"]
import os
import tarfile
import numpy as np
from PIL import Image
import paddle
from paddle.dataset.common import _check_exists_and_download
from paddle.io import Dataset
from paddle.utils import try_import
from paddle.utils.download import _safe_extract_tar
__all__ = []
DATA_URL = 'http://paddlemodels.bj.bcebos.com/flowers/102flowers.tgz'
LABEL_URL = 'http://paddlemodels.bj.bcebos.com/flowers/imagelabels.mat'
SETID_URL = 'http://paddlemodels.bj.bcebos.com/flowers/setid.mat'
DATA_MD5 = '52808999861908f626f3c1f4e79d11fa'
LABEL_MD5 = 'e0620be6f572b9609742df49c70aed4d'
SETID_MD5 = 'a5357ecc9cb78c4bef273ce3793fc85c'
# In official 'readme', tstid is the flag of test data
# and trnid is the flag of train data. But test data is more than train data.
# So we exchange the train data and test data.
MODE_FLAG_MAP = {'train': 'tstid', 'test': 'trnid', 'valid': 'valid'}
class Flowers(Dataset[tuple["_ImageDataType", "npt.NDArray[np.int64]"]]):
"""
Implementation of `Flowers102 <https://www.robots.ox.ac.uk/~vgg/data/flowers/>`_
dataset.
Args:
data_file (str|None, optional): Path to data file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/flowers/.
label_file (str|None, optional): Path to label file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/flowers/.
setid_file (str|None, optional): Path to subset index file, can be set
None if :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/flowers/.
mode (str, optional): Either train or test mode. Default 'train'.
transform (Callable|None, optional): transform to perform on image, None for no transform. Default: None.
download (bool|None, optional): download dataset automatically if :attr:`data_file` is None. Default: True.
backend (str|None, optional): Specifies which type of image to be returned:
PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_paddle_vision_get_image_backend>`,
default backend is 'pil'. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of Flowers dataset.
Examples:
.. code-block:: pycon
>>> # doctest: +TIMEOUT(60)
>>> import itertools
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import Flowers
>>> flowers = Flowers()
>>> print(len(flowers))
6149
>>> for i in range(5): # only show first 5 images
... img, label = flowers[i]
... # do something with img and label
... print(type(img), img.size, label)
... # <class 'PIL.JpegImagePlugin.JpegImageFile'> (523, 500) [1]
>>> transform = T.Compose(
... [
... T.Resize(64),
... T.ToTensor(),
... T.Normalize(
... mean=[0.5, 0.5, 0.5],
... std=[0.5, 0.5, 0.5],
... to_rgb=True,
... ),
... ]
... )
>>> flowers_test = Flowers(
... mode="test",
... transform=transform, # apply transform to every image
... backend="cv2", # use OpenCV as image transform backend
... )
>>> print(len(flowers_test))
1020
>>> for img, label in itertools.islice(iter(flowers_test), 5): # only show first 5 images
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape, label)
... # <class 'paddle.Tensor'> [3, 64, 96] [1]
"""
backend: _ImageBackend
data_file: str | None
label_file: str | None
setid_file: str | None
mode: _DatasetMode
transform: _Transform[Any, Any] | None
def __init__(
self,
data_file: str | None = None,
label_file: str | None = None,
setid_file: str | None = None,
mode: _DatasetMode = 'train',
transform: _Transform[Any, Any] | None = None,
download: bool = True,
backend: _ImageBackend | None = None,
) -> None:
assert mode.lower() in [
'train',
'valid',
'test',
], f"mode should be 'train', 'valid' or 'test', but got {mode}"
if backend is None:
backend = paddle.vision.get_image_backend()
if backend not in ['pil', 'cv2']:
raise ValueError(
f"Expected backend are one of ['pil', 'cv2'], but got {backend}"
)
self.backend = backend
flag = MODE_FLAG_MAP[mode.lower()]
if not data_file:
assert download, (
"data_file is not set and downloading automatically is disabled"
)
data_file = _check_exists_and_download(
data_file, DATA_URL, DATA_MD5, 'flowers', download
)
if not label_file:
assert download, (
"label_file is not set and downloading automatically is disabled"
)
label_file = _check_exists_and_download(
label_file, LABEL_URL, LABEL_MD5, 'flowers', download
)
if not setid_file:
assert download, (
"setid_file is not set and downloading automatically is disabled"
)
setid_file = _check_exists_and_download(
setid_file, SETID_URL, SETID_MD5, 'flowers', download
)
self.transform = transform
data_tar = tarfile.open(data_file)
self.data_path = data_file.replace(".tgz", "/")
if not os.path.exists(self.data_path):
os.mkdir(self.data_path)
jpg_path = os.path.join(self.data_path, "jpg")
if not os.path.exists(jpg_path):
_safe_extract_tar(data_tar, self.data_path, on_unsafe='raise')
scio = try_import('scipy.io')
self.labels = scio.loadmat(label_file)['labels'][0]
self.indexes = scio.loadmat(setid_file)[flag][0]
def __getitem__(
self, idx: int
) -> tuple[_ImageDataType, npt.NDArray[np.int64]]:
index = self.indexes[idx]
label = np.array([self.labels[index - 1]])
img_name = f"jpg/image_{index:05}.jpg"
image = os.path.join(self.data_path, img_name)
if self.backend == 'pil':
image = Image.open(image)
elif self.backend == 'cv2':
image = np.array(Image.open(image))
if self.transform is not None:
image = self.transform(image)
if self.backend == 'pil':
return image, label.astype('int64')
return image.astype(paddle.get_default_dtype()), label.astype('int64')
def __len__(self):
return len(self.indexes)
+538
View File
@@ -0,0 +1,538 @@
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal, TypeAlias
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from paddle._typing.dtype_like import _DTypeLiteral
from paddle.vision.transforms.transforms import _Transform
from ..image import _ImageDataType
_AllowedExtensions: TypeAlias = Literal[
'.jpg',
'.jpeg',
'.png',
'.ppm',
'.bmp',
'.pgm',
'.tif',
'.tiff',
'.webp',
]
import os
from PIL import Image
import paddle
from paddle.io import Dataset
from paddle.utils import try_import
__all__ = []
def has_valid_extension(filename: str, extensions: Sequence[str]) -> bool:
"""Checks if a file is a valid extension.
Args:
filename (str): path to a file
extensions (list[str]|tuple[str]): extensions to consider
Returns:
bool: True if the filename ends with one of given extensions
"""
assert isinstance(extensions, (list, tuple)), (
"`extensions` must be list or tuple."
)
extensions = tuple([x.lower() for x in extensions])
return filename.lower().endswith(extensions)
def make_dataset(dir, class_to_idx, extensions, is_valid_file=None):
images = []
dir = os.path.expanduser(dir)
if extensions is not None:
def is_valid_file(x):
return has_valid_extension(x, extensions)
for target in sorted(class_to_idx.keys()):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d, followlinks=True)):
for fname in sorted(fnames):
path = os.path.join(root, fname)
if is_valid_file(path):
item = (path, class_to_idx[target])
images.append(item)
return images
class DatasetFolder(Dataset[tuple["_ImageDataType", int]]):
"""A generic data loader where the samples are arranged in this way:
.. code-block:: text
root/class_a/1.ext
root/class_a/2.ext
root/class_a/3.ext
root/class_b/123.ext
root/class_b/456.ext
root/class_b/789.ext
Args:
root (str): Root directory path.
loader (Callable|None, optional): A function to load a sample given its path. Default: None.
extensions (list[str]|tuple[str]|None, optional): A list of allowed extensions.
Both :attr:`extensions` and :attr:`is_valid_file` should not be passed.
If this value is not set, the default is to use ('.jpg', '.jpeg', '.png',
'.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None.
transform (Callable|None, optional): A function/transform that takes in
a sample and returns a transformed version. Default: None.
is_valid_file (Callable|None, optional): A function that takes path of a file
and check if the file is a valid file. Both :attr:`extensions` and
:attr:`is_valid_file` should not be passed. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of DatasetFolder.
Attributes:
classes (list[str]): List of the class names.
class_to_idx (dict[str, int]): Dict with items (class_name, class_index).
samples (list[tuple[str, int]]): List of (sample_path, class_index) tuples.
targets (list[int]): The class_index value for each image in the dataset.
Example:
.. code-block:: pycon
>>> import shutil
>>> import tempfile
>>> import cv2
>>> import numpy as np
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from pathlib import Path
>>> from paddle.vision.datasets import DatasetFolder
>>> def make_fake_file(img_path: str):
... if img_path.endswith((".jpg", ".png", ".jpeg")):
... fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
... cv2.imwrite(img_path, fake_img)
... elif img_path.endswith(".txt"):
... with open(img_path, "w") as f:
... f.write("This is a fake file.")
>>> def make_directory(root, directory_hierarchy, file_maker=make_fake_file):
... root = Path(root)
... root.mkdir(parents=True, exist_ok=True)
... for subpath in directory_hierarchy:
... if isinstance(subpath, str):
... filepath = root / subpath
... file_maker(str(filepath))
... else:
... dirname = list(subpath.keys())[0]
... make_directory(root / dirname, subpath[dirname])
>>> directory_hierarchy = [
... {"class_0": [
... "abc.jpg",
... "def.png"]},
... {"class_1": [
... "ghi.jpeg",
... "jkl.png",
... {"mno": [
... "pqr.jpeg",
... "stu.jpg"]}]},
... "this_will_be_ignored.txt",
... ] # fmt: skip
>>> # You can replace this with any directory to explore the structure
>>> # of generated data. e.g. fake_data_dir = "./temp_dir"
>>> fake_data_dir = tempfile.mkdtemp()
>>> make_directory(fake_data_dir, directory_hierarchy)
>>> data_folder_1 = DatasetFolder(fake_data_dir)
>>> print(data_folder_1.classes)
['class_0', 'class_1']
>>> print(data_folder_1.class_to_idx)
{'class_0': 0, 'class_1': 1}
>>> print(data_folder_1.samples)
>>> # doctest: +SKIP(it's different with windows)
[('./temp_dir/class_0/abc.jpg', 0), ('./temp_dir/class_0/def.png', 0),
('./temp_dir/class_1/ghi.jpeg', 1), ('./temp_dir/class_1/jkl.png', 1),
('./temp_dir/class_1/mno/pqr.jpeg', 1), ('./temp_dir/class_1/mno/stu.jpg', 1)]
>>> # doctest: -SKIP
>>> print(data_folder_1.targets)
[0, 0, 1, 1, 1, 1]
>>> print(len(data_folder_1))
6
>>> for i in range(len(data_folder_1)):
... img, label = data_folder_1[i]
... # do something with img and label
... print(type(img), img.size, label)
... # <class 'PIL.Image.Image'> (32, 32) 0
>>> transform = T.Compose(
... [
... T.Resize(64),
... T.ToTensor(),
... T.Normalize(
... mean=[0.5, 0.5, 0.5],
... std=[0.5, 0.5, 0.5],
... to_rgb=True,
... ),
... ]
... )
>>> def cv2_loader(path: str):
... image = cv2.imread(path)
... assert image is not None
... return image
>>> data_folder_2 = DatasetFolder(
... fake_data_dir,
... loader=cv2_loader, # load image with OpenCV
... extensions=(".jpg",), # only load *.jpg files
... transform=transform, # apply transform to every image
... )
>>> print([img_path for img_path, label in data_folder_2.samples])
>>> # doctest: +SKIP(it's different with windows)
['./temp_dir/class_0/abc.jpg', './temp_dir/class_1/mno/stu.jpg']
>>> # doctest: -SKIP
>>> print(len(data_folder_2))
2
>>> for img, label in iter(data_folder_2):
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape, label)
... # <class 'paddle.Tensor'> [3, 64, 64] 0
>>> shutil.rmtree(fake_data_dir)
"""
loader: Callable[..., _ImageDataType] | None
extensions: Sequence[_AllowedExtensions] | None
transform: _Transform[Any, Any] | None
classes: list[str]
class_to_idx: dict[str, int]
samples: list[tuple[str, int]]
targets: list[str]
dtype: _DTypeLiteral
def __init__(
self,
root: str,
loader: Callable[..., _ImageDataType] | None = None,
extensions: Sequence[_AllowedExtensions] | None = None,
transform: _Transform[Any, Any] | None = None,
is_valid_file: _ImageDataType | None = None,
) -> None:
self.root = root
self.transform = transform
if extensions is None:
extensions = IMG_EXTENSIONS
classes, class_to_idx = self._find_classes(self.root)
samples = make_dataset(
self.root, class_to_idx, extensions, is_valid_file
)
if len(samples) == 0:
raise (
RuntimeError(
"Found 0 directories in subfolders of: " + self.root + "\n"
"Supported extensions are: " + ",".join(extensions)
)
)
self.loader = default_loader if loader is None else loader
self.extensions = extensions
self.classes = classes
self.class_to_idx = class_to_idx
self.samples = samples
self.targets = [s[1] for s in samples]
self.dtype = paddle.get_default_dtype()
def _find_classes(self, dir: str) -> tuple[list[str], dict[str, int]]:
"""
Finds the class folders in a dataset.
Args:
dir (string): Root directory path.
Returns:
tuple: (classes, class_to_idx) where classes are relative to (dir),
and class_to_idx is a dictionary.
"""
classes = [d.name for d in os.scandir(dir) if d.is_dir()]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def __getitem__(self, index: int) -> tuple[_ImageDataType, int]:
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
return sample, target
def __len__(self):
return len(self.samples)
IMG_EXTENSIONS = (
'.jpg',
'.jpeg',
'.png',
'.ppm',
'.bmp',
'.pgm',
'.tif',
'.tiff',
'.webp',
)
def pil_loader(path):
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
def cv2_loader(path):
cv2 = try_import('cv2')
return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)
def default_loader(path):
from paddle.vision import get_image_backend
if get_image_backend() == 'cv2':
return cv2_loader(path)
else:
return pil_loader(path)
class ImageFolder(Dataset[list["_ImageDataType"]]):
"""A generic data loader where the samples are arranged in this way:
.. code-block:: text
root/1.ext
root/2.ext
root/sub_dir/3.ext
Args:
root (str): Root directory path.
loader (Callable|None, optional): A function to load a sample given its path. Default: None.
extensions (list[str]|tuple[str]|None, optional): A list of allowed extensions.
Both :attr:`extensions` and :attr:`is_valid_file` should not be passed.
If this value is not set, the default is to use ('.jpg', '.jpeg', '.png',
'.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None.
transform (Callable|None, optional): A function/transform that takes in
a sample and returns a transformed version. Default: None.
is_valid_file (Callable|None, optional): A function that takes path of a file
and check if the file is a valid file. Both :attr:`extensions` and
:attr:`is_valid_file` should not be passed. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of ImageFolder.
Attributes:
samples (list[str]): List of sample path.
Example:
.. code-block:: pycon
>>> import shutil
>>> import tempfile
>>> import cv2
>>> import numpy as np
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from pathlib import Path
>>> from paddle.vision.datasets import ImageFolder
>>> def make_fake_file(img_path: str):
... if img_path.endswith((".jpg", ".png", ".jpeg")):
... fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)
... cv2.imwrite(img_path, fake_img)
... elif img_path.endswith(".txt"):
... with open(img_path, "w") as f:
... f.write("This is a fake file.")
>>> def make_directory(root, directory_hierarchy, file_maker=make_fake_file):
... root = Path(root)
... root.mkdir(parents=True, exist_ok=True)
... for subpath in directory_hierarchy:
... if isinstance(subpath, str):
... filepath = root / subpath
... file_maker(str(filepath))
... else:
... dirname = list(subpath.keys())[0]
... make_directory(root / dirname, subpath[dirname])
>>> directory_hierarchy = [
... "abc.jpg",
... "def.png",
... {"ghi": [
... "jkl.jpeg",
... {"mno": [
... "pqr.jpg"]}]},
... "this_will_be_ignored.txt",
... ] # fmt: skip
>>> # You can replace this with any directory to explore the structure
>>> # of generated data. e.g. fake_data_dir = "./temp_dir"
>>> fake_data_dir = tempfile.mkdtemp()
>>> make_directory(fake_data_dir, directory_hierarchy)
>>> image_folder_1 = ImageFolder(fake_data_dir)
>>> print(image_folder_1.samples)
>>> # doctest: +SKIP(it's different with windows)
['./temp_dir/abc.jpg', './temp_dir/def.png',
'./temp_dir/ghi/jkl.jpeg', './temp_dir/ghi/mno/pqr.jpg']
>>> # doctest: -SKIP
>>> print(len(image_folder_1))
4
>>> for i in range(len(image_folder_1)):
... (img,) = image_folder_1[i]
... # do something with img
... print(type(img), img.size)
... # <class 'PIL.Image.Image'> (32, 32)
>>> transform = T.Compose(
... [
... T.Resize(64),
... T.ToTensor(),
... T.Normalize(
... mean=[0.5, 0.5, 0.5],
... std=[0.5, 0.5, 0.5],
... to_rgb=True,
... ),
... ]
... )
>>> def cv2_loader(path: str):
... image = cv2.imread(path)
... assert image is not None
... return image
>>> image_folder_2 = ImageFolder(
... fake_data_dir,
... loader=cv2_loader, # load image with OpenCV
... extensions=(".jpg",), # only load *.jpg files
... transform=transform, # apply transform to every image
... )
>>> print(image_folder_2.samples)
>>> # doctest: +SKIP(it's different with windows)
['./temp_dir/abc.jpg', './temp_dir/ghi/mno/pqr.jpg']
>>> # doctest: -SKIP
>>> print(len(image_folder_2))
2
>>> for (img,) in iter(image_folder_2):
... # do something with img
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape)
... # <class 'paddle.Tensor'> [3, 64, 64]
>>> shutil.rmtree(fake_data_dir)
"""
loader: Callable[..., _ImageDataType] | None
extensions: Sequence[_AllowedExtensions] | None
samples: list[str]
transform: _Transform[Any, Any] | None
def __init__(
self,
root: str,
loader: Callable[..., _ImageDataType] | None = None,
extensions: Sequence[_AllowedExtensions] | None = None,
transform: _Transform[Any, Any] | None = None,
is_valid_file: _ImageDataType | None = None,
) -> None:
self.root = root
if extensions is None:
extensions = IMG_EXTENSIONS
samples = []
path = os.path.expanduser(root)
if extensions is not None:
def is_valid_file(x):
return has_valid_extension(x, extensions)
for root, _, fnames in sorted(os.walk(path, followlinks=True)):
for fname in sorted(fnames):
f = os.path.join(root, fname)
if is_valid_file(f):
samples.append(f)
if len(samples) == 0:
raise (
RuntimeError(
"Found 0 files in subfolders of: " + self.root + "\n"
"Supported extensions are: " + ",".join(extensions)
)
)
self.loader = default_loader if loader is None else loader
self.extensions = extensions
self.samples = samples
self.transform = transform
def __getitem__(self, index: int) -> list[_ImageDataType]:
"""
Args:
index (int): Index
Returns:
sample of specific index.
"""
path = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
return [sample]
def __len__(self) -> int:
return len(self.samples)
+339
View File
@@ -0,0 +1,339 @@
# 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
import numpy.typing as npt
from paddle._typing.dtype_like import _DTypeLiteral
from paddle.vision.transforms.transforms import _Transform
from ..image import _ImageBackend, _ImageDataType
_DatasetMode = Literal["train", "test"]
import gzip
import struct
import numpy as np
from PIL import Image
import paddle
from paddle.dataset.common import _check_exists_and_download
from paddle.io import Dataset
__all__ = []
class MNIST(Dataset[tuple["_ImageDataType", "npt.NDArray[np.int64]"]]):
"""
Implementation of `MNIST <http://yann.lecun.com/exdb/mnist/>`_ dataset.
Args:
image_path (str|None, optional): Path to image file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/mnist.
label_path (str|None, optional): Path to label file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/mnist.
mode (str, optional): Either train or test mode. Default 'train'.
transform (Callable|None, optional): Transform to perform on image, None for no transform. Default: None.
download (bool, optional): Download dataset automatically if
:attr:`image_path` :attr:`label_path` is not set. Default: True.
backend (str|None, optional): Specifies which type of image to be returned:
PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_paddle_vision_get_image_backend>`,
default backend is 'pil'. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of MNIST dataset.
Examples:
.. code-block:: pycon
>>> import itertools
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import MNIST
>>> mnist = MNIST()
>>> print(len(mnist))
60000
>>> for i in range(5): # only show first 5 images
... img, label = mnist[i]
... # do something with img and label
... print(type(img), img.size, label)
... # <class 'PIL.Image.Image'> (28, 28) [5]
>>> transform = T.Compose(
... [
... T.ToTensor(),
... T.Normalize(
... mean=[127.5],
... std=[127.5],
... ),
... ]
... )
>>> mnist_test = MNIST(
... mode="test",
... transform=transform, # apply transform to every image
... backend="cv2", # use OpenCV as image transform backend
... )
>>> print(len(mnist_test))
10000
>>> for img, label in itertools.islice(iter(mnist_test), 5): # only show first 5 images
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape, label)
... # <class 'paddle.Tensor'> [1, 28, 28] [7]
"""
NAME = 'mnist'
URL_PREFIX = 'https://dataset.bj.bcebos.com/mnist/'
TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz'
TEST_IMAGE_MD5 = '9fb629c4189551a2d022fa330f9573f3'
TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz'
TEST_LABEL_MD5 = 'ec29112dd5afa0611ce80d1b7f02629c'
TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz'
TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873'
TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz'
TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432'
mode: _DatasetMode
image_path: str | None
label_path: str | None
transform: _Transform[Any, Any] | None
backend: _ImageBackend
dtype: _DTypeLiteral
labels: list
images: list
def __init__(
self,
image_path: str | None = None,
label_path: str | None = None,
mode: _DatasetMode = 'train',
transform: _Transform[Any, Any] | None = None,
download: bool = True,
backend: _ImageBackend | None = None,
) -> None:
assert mode.lower() in [
'train',
'test',
], f"mode should be 'train' or 'test', but got {mode}"
if backend is None:
backend = paddle.vision.get_image_backend()
if backend not in ['pil', 'cv2']:
raise ValueError(
f"Expected backend are one of ['pil', 'cv2'], but got {backend}"
)
self.backend = backend
self.mode = mode.lower()
self.image_path = image_path
if self.image_path is None:
assert download, (
"image_path is not set and downloading automatically is disabled"
)
image_url = (
self.TRAIN_IMAGE_URL if mode == 'train' else self.TEST_IMAGE_URL
)
image_md5 = (
self.TRAIN_IMAGE_MD5 if mode == 'train' else self.TEST_IMAGE_MD5
)
self.image_path = _check_exists_and_download(
image_path, image_url, image_md5, self.NAME, download
)
self.label_path = label_path
if self.label_path is None:
assert download, (
"label_path is not set and downloading automatically is disabled"
)
label_url = (
self.TRAIN_LABEL_URL
if self.mode == 'train'
else self.TEST_LABEL_URL
)
label_md5 = (
self.TRAIN_LABEL_MD5
if self.mode == 'train'
else self.TEST_LABEL_MD5
)
self.label_path = _check_exists_and_download(
label_path, label_url, label_md5, self.NAME, download
)
self.transform = transform
# read dataset into memory
self._parse_dataset()
self.dtype = paddle.get_default_dtype()
def _parse_dataset(self, buffer_size=100):
self.images = []
self.labels = []
with gzip.GzipFile(self.image_path, 'rb') as image_file:
img_buf = image_file.read()
with gzip.GzipFile(self.label_path, 'rb') as label_file:
lab_buf = label_file.read()
step_label = 0
offset_img = 0
# read from Big-endian
# get file info from magic byte
# image file : 16B
magic_byte_img = '>IIII'
magic_img, image_num, rows, cols = struct.unpack_from(
magic_byte_img, img_buf, offset_img
)
offset_img += struct.calcsize(magic_byte_img)
offset_lab = 0
# label file : 8B
magic_byte_lab = '>II'
magic_lab, label_num = struct.unpack_from(
magic_byte_lab, lab_buf, offset_lab
)
offset_lab += struct.calcsize(magic_byte_lab)
while True:
if step_label >= label_num:
break
fmt_label = '>' + str(buffer_size) + 'B'
labels = struct.unpack_from(fmt_label, lab_buf, offset_lab)
offset_lab += struct.calcsize(fmt_label)
step_label += buffer_size
fmt_images = '>' + str(buffer_size * rows * cols) + 'B'
images_temp = struct.unpack_from(
fmt_images, img_buf, offset_img
)
images = np.reshape(
images_temp, (buffer_size, rows * cols)
).astype('float32')
offset_img += struct.calcsize(fmt_images)
for i in range(buffer_size):
self.images.append(images[i, :])
self.labels.append(
np.array([labels[i]]).astype('int64')
)
def __getitem__(
self, idx: int
) -> tuple[_ImageDataType, npt.NDArray[np.int64]]:
image, label = self.images[idx], self.labels[idx]
image = np.reshape(image, [28, 28])
if self.backend == 'pil':
image = Image.fromarray(image.astype('uint8'), mode='L')
if self.transform is not None:
image = self.transform(image)
if self.backend == 'pil':
return image, label.astype('int64')
return image.astype(self.dtype), label.astype('int64')
def __len__(self) -> int:
return len(self.labels)
class FashionMNIST(MNIST):
"""
Implementation of `Fashion-MNIST <https://github.com/zalandoresearch/fashion-mnist>`_ dataset.
Args:
image_path (str, optional): Path to image file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/fashion-mnist.
label_path (str, optional): Path to label file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/fashion-mnist.
mode (str, optional): Either train or test mode. Default 'train'.
transform (Callable, optional): Transform to perform on image, None for no transform. Default: None.
download (bool, optional): Whether to download dataset automatically if
:attr:`image_path` :attr:`label_path` is not set. Default: True.
backend (str, optional): Specifies which type of image to be returned:
PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_paddle_vision_get_image_backend>`,
default backend is 'pil'. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of FashionMNIST dataset.
Examples:
.. code-block:: pycon
>>> import itertools
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import FashionMNIST
>>> fashion_mnist = FashionMNIST()
>>> print(len(fashion_mnist))
60000
>>> for i in range(5): # only show first 5 images
... img, label = fashion_mnist[i]
... # do something with img and label
... print(type(img), img.size, label)
... # <class 'PIL.Image.Image'> (28, 28) [9]
>>> transform = T.Compose(
... [
... T.ToTensor(),
... T.Normalize(
... mean=[127.5],
... std=[127.5],
... ),
... ]
... )
>>> fashion_mnist_test = FashionMNIST(
... mode="test",
... transform=transform, # apply transform to every image
... backend="cv2", # use OpenCV as image transform backend
... )
>>> print(len(fashion_mnist_test))
10000
>>> for img, label in itertools.islice(iter(fashion_mnist_test), 5): # only show first 5 images
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape, label)
... # <class 'paddle.Tensor'> [1, 28, 28] [9]
"""
NAME = 'fashion-mnist'
URL_PREFIX = 'https://dataset.bj.bcebos.com/fashion_mnist/'
TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz'
TEST_IMAGE_MD5 = 'bef4ecab320f06d8554ea6380940ec79'
TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz'
TEST_LABEL_MD5 = 'bb300cfdad3c16e7a12a480ee83cd310'
TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz'
TRAIN_IMAGE_MD5 = '8d4fb7e6c68d591d4c3dfef9ec88bf0d'
TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz'
TRAIN_LABEL_MD5 = '25c81989df183df01b3e8a0aad5dffbe'
+215
View File
@@ -0,0 +1,215 @@
# 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.
from __future__ import annotations
import io
import tarfile
from typing import TYPE_CHECKING, Any, Literal
import numpy as np
from PIL import Image
import paddle
from paddle.dataset.common import _check_exists_and_download
from paddle.io import Dataset
if TYPE_CHECKING:
import numpy.typing as npt
from paddle._typing import DTypeLike
from paddle.vision.transforms.transforms import _Transform
from ..image import _ImageDataType
_ImageBackend = Literal["cv2", "pil"]
_DatasetMode = Literal["train", "valid", "test"]
__all__ = []
VOC_URL = 'https://dataset.bj.bcebos.com/voc/VOCtrainval_11-May-2012.tar'
VOC_MD5 = '6cd6e144f989b92b3379bac3b3de84fd'
SET_FILE = 'VOCdevkit/VOC2012/ImageSets/Segmentation/{}.txt'
DATA_FILE = 'VOCdevkit/VOC2012/JPEGImages/{}.jpg'
LABEL_FILE = 'VOCdevkit/VOC2012/SegmentationClass/{}.png'
CACHE_DIR = 'voc2012'
MODE_FLAG_MAP = {'train': 'trainval', 'test': 'train', 'valid': "val"}
class VOC2012(Dataset[tuple["_ImageDataType", "npt.NDArray[Any]"]]):
"""
Implementation of `VOC2012 <http://host.robots.ox.ac.uk/pascal/VOC/voc2012/>`_ dataset.
Args:
data_file (str|None, optional): Path to data file, can be set None if
:attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/voc2012.
mode (str, optional): Either train or test mode. Default 'train'.
transform (Callable|None, optional): Transform to perform on image, None for no transform. Default: None.
download (bool, optional): Download dataset automatically if :attr:`data_file` is None. Default: True.
backend (str|None, optional): Specifies which type of image to be returned:
PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_paddle_vision_get_image_backend>`,
default backend is 'pil'. Default: None.
Returns:
:ref:`api_paddle_io_Dataset`. An instance of VOC2012 dataset.
Examples:
.. code-block:: pycon
>>> # doctest: +TIMEOUT(120)
>>> import itertools
>>> import paddle
>>> import paddle.vision.transforms as T
>>> from paddle.vision.datasets import VOC2012
>>> voc2012 = VOC2012()
>>> print(len(voc2012))
2913
>>> for i in range(5): # only show first 5 images
... img, label = voc2012[i]
... # do something with img and label
... print(type(img), img.size)
... # <class 'PIL.JpegImagePlugin.JpegImageFile'> (500, 281)
... print(type(label), label.size)
... # <class 'PIL.PngImagePlugin.PngImageFile'> (500, 281)
>>> transform = T.Compose(
... [
... T.ToTensor(),
... T.Normalize(
... mean=[0.5, 0.5, 0.5],
... std=[0.5, 0.5, 0.5],
... to_rgb=True,
... ),
... ]
... )
>>> voc2012_test = VOC2012(
... mode="test",
... transform=transform, # apply transform to every image
... backend="cv2", # use OpenCV as image transform backend
... )
>>> print(len(voc2012_test))
1464
>>> for img, label in itertools.islice(iter(voc2012_test), 5): # only show first 5 images
... # do something with img and label
... assert isinstance(img, paddle.Tensor)
... print(type(img), img.shape)
... # <class 'paddle.Tensor'> [3, 281, 500]
... print(type(label), label.shape)
... # <class 'numpy.ndarray'> (281, 500)
"""
data_file: str | None
mode: _DatasetMode
transform: _Transform[Any, Any] | None
backend: _ImageBackend
flag: str
dtype: DTypeLike
def __init__(
self,
data_file: str | None = None,
mode: _DatasetMode = 'train',
transform: _Transform[Any, Any] | None = None,
download: bool = True,
backend: _ImageBackend | None = None,
) -> None:
assert mode.lower() in [
'train',
'valid',
'test',
], f"mode should be 'train', 'valid' or 'test', but got {mode}"
if backend is None:
backend = paddle.vision.get_image_backend()
if backend not in ['pil', 'cv2']:
raise ValueError(
f"Expected backend are one of ['pil', 'cv2'], but got {backend}"
)
self.backend = backend
self.flag = MODE_FLAG_MAP[mode.lower()]
self.data_file = data_file
if self.data_file is None:
assert download, (
"data_file is not set and downloading automatically is disabled"
)
self.data_file = _check_exists_and_download(
data_file, VOC_URL, VOC_MD5, CACHE_DIR, download
)
self.transform = transform
# read dataset into memory
self._load_anno()
self.dtype = paddle.get_default_dtype()
def _load_anno(self):
self.name2mem = {}
self.data_tar = tarfile.open(self.data_file)
for ele in self.data_tar.getmembers():
self.name2mem[ele.name] = ele
set_file = SET_FILE.format(self.flag)
sets = self.data_tar.extractfile(self.name2mem[set_file])
self.data = []
self.labels = []
for line in sets:
line = line.strip()
data = DATA_FILE.format(line.decode('utf-8'))
label = LABEL_FILE.format(line.decode('utf-8'))
self.data.append(data)
self.labels.append(label)
def __getitem__(self, idx: int) -> tuple[_ImageDataType, npt.NDArray[Any]]:
data_file = self.data[idx]
label_file = self.labels[idx]
data = self.data_tar.extractfile(self.name2mem[data_file]).read()
label = self.data_tar.extractfile(self.name2mem[label_file]).read()
data = Image.open(io.BytesIO(data))
label = Image.open(io.BytesIO(label))
if self.backend == 'cv2':
data = np.array(data)
label = np.array(label)
if self.transform is not None:
data = self.transform(data)
if self.backend == 'cv2':
return data.astype(self.dtype), label.astype(self.dtype)
return data, label
def __len__(self) -> int:
return len(self.data)
def __del__(self) -> None:
if self.data_tar:
self.data_tar.close()