Yields patches from data read from an image dataset. The patches are generated by a user-specified callable `patch_func`, and are optionally post-processed by `transform`. For example, to generate random patch samples from an image dataset: .. code-block:: python impor
| 364 | |
| 365 | |
| 366 | class PatchDataset(IterableDataset): |
| 367 | """ |
| 368 | Yields patches from data read from an image dataset. |
| 369 | The patches are generated by a user-specified callable `patch_func`, |
| 370 | and are optionally post-processed by `transform`. |
| 371 | For example, to generate random patch samples from an image dataset: |
| 372 | |
| 373 | .. code-block:: python |
| 374 | |
| 375 | import numpy as np |
| 376 | |
| 377 | from monai.data import PatchDataset, DataLoader |
| 378 | from monai.transforms import RandSpatialCropSamples, RandShiftIntensity |
| 379 | |
| 380 | # image dataset |
| 381 | images = [np.arange(16, dtype=float).reshape(1, 4, 4), |
| 382 | np.arange(16, dtype=float).reshape(1, 4, 4)] |
| 383 | # image patch sampler |
| 384 | n_samples = 5 |
| 385 | sampler = RandSpatialCropSamples(roi_size=(3, 3), num_samples=n_samples, |
| 386 | random_center=True, random_size=False) |
| 387 | # patch-level intensity shifts |
| 388 | patch_intensity = RandShiftIntensity(offsets=1.0, prob=1.0) |
| 389 | # construct the patch dataset |
| 390 | ds = PatchDataset(dataset=images, |
| 391 | patch_func=sampler, |
| 392 | samples_per_image=n_samples, |
| 393 | transform=patch_intensity) |
| 394 | |
| 395 | # use the patch dataset, length: len(images) x samplers_per_image |
| 396 | print(len(ds)) |
| 397 | |
| 398 | >>> 10 |
| 399 | |
| 400 | for item in DataLoader(ds, batch_size=2, shuffle=True, num_workers=2): |
| 401 | print(item.shape) |
| 402 | |
| 403 | >>> torch.Size([2, 1, 3, 3]) |
| 404 | |
| 405 | """ |
| 406 | |
| 407 | def __init__( |
| 408 | self, data: Sequence, patch_func: Callable, samples_per_image: int = 1, transform: Callable | None = None |
| 409 | ) -> None: |
| 410 | """ |
| 411 | Args: |
| 412 | data: an image dataset to extract patches from. |
| 413 | patch_func: converts an input image (item from dataset) into a sequence of image patches. |
| 414 | patch_func(dataset[idx]) must return a sequence of patches (length `samples_per_image`). |
| 415 | samples_per_image: `patch_func` should return a sequence of `samples_per_image` elements. |
| 416 | transform: transform applied to each patch. |
| 417 | """ |
| 418 | super().__init__(data=data, transform=None) |
| 419 | |
| 420 | self.patch_func = patch_func |
| 421 | if samples_per_image <= 0: |
| 422 | raise ValueError("sampler_per_image must be a positive integer.") |
| 423 | self.samples_per_image = int(samples_per_image) |
no outgoing calls
searching dependent graphs…