Datasets¶
Coordinate datasets and their conventions are described on the conventions page.
datasets
¶
Image, volume and MRI datasets for implicit neural representations (INRs).
A dataset has length one and ignores the item index. Its item is a dictionary with
id, input, target and _original, the reference signal for metrics.
Coordinate inputs lie in [-1, 1].
Dataset methods follow load(path, ...), save(x, path, ...), preprocess(x)
(raw signal to target) and postprocess(x) (model output to reconstruction). Deep
Image Prior uses a fixed noise input instead of coordinates. Super-resolution observes
the image through a separable linear degradation, written out by resize_matrix
and applied by downsample.
ImageCoordinateDataset
¶
ImageCoordinateDataset(image: str | PathLike[str] | Image | Tensor, grid_size: tuple[int, int] | None = None, mode: str = 'RGB', max_samples: int | None = None, subsample: float = 1.0, item_id: str | None = None, seed: int = 0)
Image as coordinate-pixel pairs, with optional random subsampling.
Subsampling flattens input and target to (N, 2) and (N, channels)
with shared indices, a new uniformly random subset of the pixels on each access.
Parameters:
-
image(str | PathLike[str] | Image | Tensor) –Path, PIL image, or uint8 tensor
(channels, H, W). -
grid_size(tuple[int, int] | None, default:None) –Size of the coordinate grid;
Noneuses the signal's size. Any other size serves evaluation at that resolution, without subsampling. -
mode(str, default:'RGB') –PIL conversion mode of paths and PIL images; ignored for tensors.
-
max_samples(int | None, default:None) –Cap on the coordinates drawn on each access;
Nonesets no cap. -
subsample(float, default:1.0) –Fraction of the coordinates drawn on each access, in
(0, 1]. -
item_id(str | None, default:None) –Item identifier;
Noneuses the path stem, or an empty string without a path. -
seed(int, default:0) –Seed of Python's global RNG; sampling uses PyTorch's and ignores it.
Shape
input:(H, W, 2), coordinates in[-1, 1].target:(H, W, channels), pixels in[-1, 1]._original:(channels, H, W), uint8 image.
Examples:
>>> image = torch.zeros(3, 4, 6, dtype=torch.uint8)
>>> item = ImageCoordinateDataset(image)[0]
>>> item["input"].shape, item["target"].shape
(torch.Size([4, 6, 2]), torch.Size([4, 6, 3]))
>>> ImageCoordinateDataset(image, subsample=0.5)[0]["input"].shape
torch.Size([12, 2])
Source code in inro/datasets.py
to
¶
Move the training tensors to device in place and return self.
The reference original stays on the CPU.
Parameters:
-
device(str | device) –Device to move them to.
Source code in inro/datasets.py
load
staticmethod
¶
Load an image as a tensor, uint8 for eight-bit modes.
Parameters:
-
path(str | PathLike[str]) –Image file.
-
**kwargs(Any, default:{}) –Passed to PIL's
convert, such asmode="RGB".
Returns:
-
Tensor–Image
(channels, H, W).
Source code in inro/datasets.py
save
staticmethod
¶
Save an image as PNG.
Parameters:
-
x(Tensor) –Image
(channels, H, W). -
path(str | PathLike[str]) –Output path;
.pngis appended if needed.
create_input
¶
preprocess
staticmethod
¶
Map uint8 pixels to float values in [-1, 1], channels last.
Parameters:
-
x(Tensor) –Image
(channels, H, W).
Returns:
-
Tensor–Target
(H, W, channels).
Source code in inro/datasets.py
postprocess
staticmethod
¶
Map float predictions to uint8 pixels, clamping them to [-1, 1] first.
Parameters:
-
x(Tensor) –Predictions
(H, W, channels).
Returns:
-
Tensor–Image
(channels, H, W).
Source code in inro/datasets.py
MaskedImageCoordinateDataset
¶
MaskedImageCoordinateDataset(image: str | PathLike[str] | Image | Tensor, side: str | PathLike[str] | Image | Tensor | None = None, mask: str | PathLike[str] | Image | Tensor | None = None, subsample: float = 1.0, item_id: str | None = None, seed: int = 0)
Image as coordinate-pixel pairs, with an optional guide image and binary mask.
The preprocessed guide extends the coordinates as extra input channels, and a custom
loss can use the mask and its thick boundary. Inputs always use the image
resolution. Subsampling flattens every tensor but _original with shared indices.
Parameters:
-
image(str | PathLike[str] | Image | Tensor) –Path, PIL image (converted to RGB), or uint8 tensor
(channels, H, W). -
side(str | PathLike[str] | Image | Tensor | None, default:None) –Guide image as a path, PIL image (converted to grayscale), or uint8 tensor
(side_channels, H, W);Noneuses no guide. -
mask(str | PathLike[str] | Image | Tensor | None, default:None) –Binary mask as a path, PIL image (converted to grayscale), or tensor
(1, H, W)or(H, W), nonzero values being true;Noneuses no mask. -
subsample(float, default:1.0) –Fraction of the coordinates drawn on each access, in
(0, 1]. -
item_id(str | None, default:None) –Item identifier;
Noneuses the path stem, or an empty string without a path. -
seed(int, default:0) –Seed of Python's global RNG; sampling uses PyTorch's and ignores it.
Shape
input:(H, W, 2), or(H, W, 2 + side_channels)with a guide.target:(H, W, channels), pixels in[-1, 1].side:(H, W, side_channels), guide in[-1, 1], with a guide only.mask,boundary:(H, W), bool, with a mask only._original:(channels, H, W), uint8 image.
Examples:
>>> image = torch.zeros(3, 4, 6, dtype=torch.uint8)
>>> item = MaskedImageCoordinateDataset(image, mask=torch.ones(4, 6))[0]
>>> item["input"].shape, item["mask"].shape, item["boundary"].dtype
(torch.Size([4, 6, 2]), torch.Size([4, 6]), torch.bool)
Source code in inro/datasets.py
create_input
¶
create_input(side: Tensor | None, mask: Tensor | None) -> tuple[Tensor, Tensor | None, Tensor | None, Tensor | None]
Return (input, side, mask, boundary) at the image resolution.
Parameters:
-
side(Tensor | None) –Uint8 guide
(side_channels, H, W), orNone. -
mask(Tensor | None) –Mask
(1, H, W)or(H, W), orNone.
Returns:
-
tuple[Tensor, Tensor | None, Tensor | None, Tensor | None]–Coordinates with the preprocessed guide appended, that guide, the bool mask and its thick boundary; an absent guide or mask gives
None.
Source code in inro/datasets.py
SuperResolutionDataset
¶
SuperResolutionDataset(image: str | PathLike[str] | Image | Tensor, kernels: Sequence[Tensor], num_blocks: int, block_size: int = 8, item_id: str | None = None)
Low-resolution image as blocks of pixels and the coordinates under them.
An INR is fitted to the low-resolution (LR) image through its degradation from high
resolution (HR), one matrix per axis. Each access draws B random square blocks
of S LR pixels a side, with the global PyTorch RNG, and
super_resolution_loss renders their footprints of L HR pixels a
side. Neighboring pixels share most of their footprint: at 4x, an 8 x 8 block takes
30 INR evaluations per pixel against 256 for a single pixel.
Parameters:
-
image(str | PathLike[str] | Image | Tensor) –LR image as a path, PIL image (converted to RGB), or uint8 tensor
(channels, h, w). -
kernels(Sequence[Tensor]) –Degradation matrices
(h, H)and(w, W), such as those ofresize_matrix. They set the HR grid and the device of the training tensors. -
num_blocks(int) –Blocks
Bdrawn on each access. -
block_size(int, default:8) –LR pixels
Son a side of a block. -
item_id(str | None, default:None) –Item identifier;
Noneuses the path stem, or an empty string without a path.
Shape
input:(B, L, L, 2), HR coordinates of each block's footprint.weight_y,weight_x:(B, S, L), kernel rows of each block on its footprint.target:(B, S, S, channels), LR pixels in[-1, 1]._original:(channels, h, w), uint8 LR image.
Examples:
>>> image = torch.zeros(3, 8, 8, dtype=torch.uint8)
>>> kernels = resize_matrix(32, 8), resize_matrix(32, 8)
>>> dataset = SuperResolutionDataset(image, kernels, num_blocks=2, block_size=2)
>>> item = dataset[0]
>>> item["input"].shape, item["weight_y"].shape, item["target"].shape
(torch.Size([2, 20, 20, 2]), torch.Size([2, 2, 20]), torch.Size([2, 2, 2, 3]))
Source code in inro/datasets.py
to
¶
Move the training tensors and kernels to device in place and return self.
The reference original stays on the CPU.
Parameters:
-
device(str | device) –Device to move them to.
Source code in inro/datasets.py
OccupancyCoordinateDataset
¶
OccupancyCoordinateDataset(path: str | PathLike[str], resolution: int = 256, grid_size: tuple[int, int, int] | None = None, max_samples: int | None = None, subsample: float = 1.0, item_id: str | None = None, seed: int = 0)
Voxelized shape as coordinate-occupancy pairs.
Normalization and voxelization follow FINER and BACON. The volume is cropped to its
occupied bounds and cached beside the source in .cache/<stem>_<resolution>.pt,
which is reused even if the source changes. Subsampling flattens input and
target to (N, 3) and (N, 1) with shared indices.
Parameters:
-
path(str | PathLike[str]) –.xyzpoint cloud (columnsx y z nx ny nz) or a mesh readable by trimesh. -
resolution(int, default:256) –Samples per unit length after normalization into
[-0.45, 0.45]^3. -
grid_size(tuple[int, int, int] | None, default:None) –Size of the coordinate grid;
Noneuses the signal's size. Any other size serves evaluation at that resolution, without subsampling. -
max_samples(int | None, default:None) –Cap on the coordinates drawn on each access;
Nonesets no cap. -
subsample(float, default:1.0) –Fraction of the coordinates drawn on each access, in
(0, 1]. -
item_id(str | None, default:None) –Item identifier;
Noneuses the path stem, or an empty string without a path. -
seed(int, default:0) –Seed of Python's global RNG; sampling uses PyTorch's and ignores it.
Shape
input:(depth, H, W, 3), coordinates in[-1, 1].target:(depth, H, W, 1), floats in{-1, 1}._original:(1, depth, H, W), float occupancy in{0, 1}.
Examples:
References
Liu et al., "FINER: Flexible Spectral-bias Tuning in Implicit NEural Representation by Variable-periodic Activation Functions", CVPR 2024. Lindell et al., "BACON: Band-limited Coordinate Networks for Multiscale Scene Representation", CVPR 2022.
Source code in inro/datasets.py
load
¶
Load, or build and cache, a float occupancy volume.
Point clouds use a KD-tree SDF and meshes trimesh (3d extra).
Parameters:
-
path(str | PathLike[str]) –.xyzpoint cloud (columnsx y z nx ny nz) or a mesh readable by trimesh. -
resolution(int) –Samples per unit length after normalization into
[-0.45, 0.45]^3.
Returns:
-
Tensor–Occupancy
(1, depth, H, W), cropped to its occupied bounds.
Source code in inro/datasets.py
save
¶
save(x: Tensor, path: str | PathLike[str], smooth: bool = True, size: int = 1024, up: int = 1, mesh: bool = True) -> None
Export occupancy as a .dae mesh and a .png render (3d extra).
The render needs no display; where the renderer cannot start, a warning replaces
the .png. Its camera is fitted to the grid rather than the mesh, so that
reconstructions of one shape are framed alike.
Parameters:
-
x(Tensor) –Occupancy
(1, depth, H, W)or(depth, H, W). -
path(str | PathLike[str]) –Output path, whose suffix
.daeand.pngreplace. -
smooth(bool, default:True) –Whether to apply Gaussian smoothing (sigma 1) before marching cubes at iso-level zero.
-
size(int, default:1024) –Side of the square render, in pixels.
-
up(int, default:1) –Grid axis drawn upwards; the view looks down the shortest of the other two, which shows the widest silhouette.
-
mesh(bool, default:True) –Whether to write the
.dae.
Source code in inro/datasets.py
preprocess
staticmethod
¶
Map occupancy in {0, 1} to float targets in {-1, 1}, channels last.
Parameters:
-
x(Tensor) –Occupancy
(1, depth, H, W).
Returns:
-
Tensor–Target
(depth, H, W, 1).
Source code in inro/datasets.py
postprocess
staticmethod
¶
Threshold predictions at zero into a float occupancy in {0, 1}.
Parameters:
-
x(Tensor) –Predictions
(depth, H, W, 1).
Returns:
-
Tensor–Occupancy
(1, depth, H, W).
Source code in inro/datasets.py
DIPImageDataset
¶
DIPImageDataset(image: str | PathLike[str] | Image | Tensor, noise_shape: tuple[int, ...] | None = None, noise_channels: int = 16, reg_noise_std: float = 1 / 30, item_id: str | None = None, seed: int = 0)
Image paired with fixed noise for Deep Image Prior.
The noise is 0.1 * randn(noise_shape), and each access perturbs it anew.
Parameters:
-
image(str | PathLike[str] | Image | Tensor) –Path, PIL image (converted to RGB), or uint8 tensor
(channels, H, W). -
noise_shape(tuple[int, ...] | None, default:None) –Shape of the noise;
Noneuses(noise_channels, H, W). -
noise_channels(int, default:16) –Channels of the noise when
noise_shapeisNone. -
reg_noise_std(float, default:1 / 30) –Standard deviation of the Gaussian perturbation, drawn with the global PyTorch RNG; zero disables it, as for evaluation.
-
item_id(str | None, default:None) –Item identifier;
Noneuses the path stem, or an empty string without a path. -
seed(int, default:0) –Seed of the noise's own generator; the global RNGs are untouched.
Shape
input:(noise_channels, H, W)ornoise_shape, which may exceed the image, as for super-resolution.target:(channels, H, W), floats in[0, 1]._original:(channels, H, W), uint8 image.
Examples:
>>> item = DIPImageDataset(torch.zeros(3, 4, 6, dtype=torch.uint8))[0]
>>> item["input"].shape, item["target"].shape
(torch.Size([16, 4, 6]), torch.Size([3, 4, 6]))
References
Ulyanov et al., "Deep Image Prior", CVPR 2018.
Source code in inro/datasets.py
to
¶
Move the training tensors to device in place and return self.
The reference original stays on the CPU.
Parameters:
-
device(str | device) –Device to move them to.
Source code in inro/datasets.py
save
staticmethod
¶
Save an image as PNG.
Parameters:
-
x(Tensor) –Image
(channels, H, W). -
path(str | PathLike[str]) –Output path;
.pngis appended if needed.
preprocess
staticmethod
¶
Map uint8 pixels to float values in [0, 1], keeping the shape.
Parameters:
-
x(Tensor) –Image
(channels, H, W).
postprocess
staticmethod
¶
Map float predictions to uint8 pixels, clamping them to [0, 1] first.
Parameters:
-
x(Tensor) –Predictions
(channels, H, W).
MRICoordinateDataset
¶
MRICoordinateDataset(kspace: str | PathLike[str] | Tensor, crop_size: tuple[int, int] | None = None, mask: Tensor | None = None, acceleration: float = 4.0, pattern: Literal['uniform', 'random'] = 'random', center_fraction: float = 0.08, slice_index: int | None = None, item_id: str | None = None, seed: int = 0)
Undersampled multi-coil MRI k-space for coordinate-based reconstruction.
The model predicts interleaved real and imaginary coil images with num_coils * 2
channels. A custom loss pads these to the k-space size, Fourier-transforms them and
compares acquired lines against target.
Parameters:
-
kspace(str | PathLike[str] | Tensor) –Complex tensor
(num_coils, H, W)or fastMRI HDF5 path; a file also providesreconstruction_rsswhen it has one. -
crop_size(tuple[int, int] | None, default:None) –Reconstruction field of view
(crop_H, crop_W);Noneuses the size of the reference RSS image. Required for tensor inputs. -
mask(Tensor | None, default:None) –Mask of
Welements, reshaped to bool(1, 1, W);Nonegenerates one. -
acceleration(float, default:4.0) –Target acceleration of the generated mask.
-
pattern(Literal['uniform', 'random'], default:'random') –Line pattern of the generated mask,
"random"or"uniform". -
center_fraction(float, default:0.08) –Fraction of lines the generated mask keeps at the center.
-
slice_index(int | None, default:None) –Slice of the file to load;
Noneuses the middle one. -
item_id(str | None, default:None) –Item identifier;
Noneuses the path stem, or an empty string without a path. -
seed(int, default:0) –Seed of the mask's own generator.
Shape
input:(crop_H, crop_W, 2), coordinates in[-1, 1].target:(num_coils, H, W), complex masked, normalized k-space.mask:(1, 1, W), bool sampling mask.scale_factor: Scalar normalization factor frompreprocess.zero_filled:(crop_H, crop_W), RSS reconstruction in original units._original:(crop_H, crop_W), reference RSS image, when one is loaded.
Examples:
>>> kspace = torch.randn(2, 8, 8, dtype=torch.complex64)
>>> item = MRICoordinateDataset(kspace, crop_size=(4, 4))[0]
>>> item["input"].shape, item["target"].shape, item["mask"].shape
(torch.Size([4, 4, 2]), torch.Size([2, 8, 8]), torch.Size([1, 1, 8]))
References
Zbontar et al., "fastMRI: An Open Dataset and Benchmarks for Accelerated MRI", arXiv 2018.
Source code in inro/datasets.py
load
staticmethod
¶
Load one fastMRI slice (requires h5py).
Parameters:
-
path(str | PathLike[str]) –fastMRI HDF5 file.
-
slice_index(int | None, default:None) –Slice of the file to load;
Noneuses the middle one.
Returns:
-
tuple[Tensor, Tensor | None]–K-space
(num_coils, H, W)and the reference RSS image(crop_H, crop_W),Nonewhen the file has none.
Source code in inro/datasets.py
save
staticmethod
¶
Min-max normalize a magnitude image and save it as an 8-bit PNG.
Parameters:
-
x(Tensor) –Magnitude image
(H, W). -
path(str | PathLike[str]) –Output path;
.pngis appended if needed.
Source code in inro/datasets.py
create_undersampling_mask
staticmethod
¶
create_undersampling_mask(num_cols: int, acceleration: float, pattern: Literal['uniform', 'random'] = 'random', center_fraction: float = 0.08, seed: int = 0) -> Tensor
Return a bool Cartesian sampling mask of shape (num_cols,).
Center lines are always kept. "random" adds lines up to
round(num_cols / acceleration) in total, unless the center alone exceeds it.
"uniform" adds every round(acceleration)-th line from a random offset,
on top of the center.
Parameters:
-
num_cols(int) –Number of lines.
-
acceleration(float) –Target acceleration of the generated mask.
-
pattern(Literal['uniform', 'random'], default:'random') –Line pattern of the generated mask,
"random"or"uniform". -
center_fraction(float, default:0.08) –Fraction of lines the generated mask keeps at the center.
-
seed(int, default:0) –Seed of the mask's own generator.
Source code in inro/datasets.py
zero_filled_reconstruction
staticmethod
¶
zero_filled_reconstruction(kspace: Tensor, mask: Tensor, crop_size: tuple[int, int] | None = None) -> Tensor
Return the RSS magnitude of masked k-space, optionally center-cropped.
The orthonormal inverse FFT is centered: ifftshift before it and
fftshift after, which differ for odd sizes.
Parameters:
-
kspace(Tensor) –Complex k-space
(num_coils, H, W). -
mask(Tensor) –Mask that broadcasts to
kspace. -
crop_size(tuple[int, int] | None, default:None) –Reconstruction field of view
(crop_H, crop_W);Nonekeeps(H, W).
Source code in inro/datasets.py
preprocess
¶
preprocess(x: Tensor, mask: Tensor, crop_size: tuple[int, int], eps: float = 1e-16) -> tuple[Tensor, Tensor]
Return normalized k-space and its scalar scale factor.
Divides k-space by the maximum of its masked, cropped zero-filled RSS image. By linearity of the FFT, the same scale applies in both domains.
Parameters:
-
x(Tensor) –Complex k-space
(num_coils, H, W). -
mask(Tensor) –Mask that broadcasts to
x. -
crop_size(tuple[int, int]) –Reconstruction field of view
(crop_H, crop_W). -
eps(float, default:1e-16) –Lower bound of the scale factor.
Source code in inro/datasets.py
postprocess
¶
Convert interleaved coil predictions to RSS magnitude in original units.
The norm over the last dimension gives the RSS without complex tensors. It is
clamped to [0, 1], then multiplied by scale_factor.
Parameters:
-
x(Tensor) –Predictions
(crop_H, crop_W, num_coils * 2).
Returns:
-
Tensor–Magnitude
(crop_H, crop_W).
Source code in inro/datasets.py
create_coordinates
¶
create_coordinates(size: tuple[int, ...], domain: tuple[float, float] = (-1.0, 1.0), **kwargs: Any) -> Tensor
Return an evenly spaced coordinate grid of shape (*size, len(size)).
Coordinate c varies along axis c, as with indexing="ij".
Parameters:
-
size(tuple[int, ...]) –Number of points on each axis.
-
domain(tuple[float, float], default:(-1.0, 1.0)) –Endpoints of every axis, both included.
-
**kwargs(Any, default:{}) –Passed to
torch.linspace, such asdtypeanddevice.
Examples:
Source code in inro/datasets.py
mask_to_boundary
¶
mask_to_boundary(mask: Tensor, kernel_size: int = 3, mode: Literal['inner', 'outer', 'thick'] = 'thick') -> Tensor
Extract the boundary of a binary mask by dilation and erosion.
Parameters:
-
mask(Tensor) –Binary tensor
(H, W),(B, H, W)or(B, 1, H, W). -
kernel_size(int, default:3) –Odd side of the pooling neighborhood.
-
mode(Literal['inner', 'outer', 'thick'], default:'thick') –"inner"(mask minus erosion),"outer"(dilation minus mask) or"thick"(dilation minus erosion).
Returns:
-
Tensor–Binary boundary with the shape, dtype and device of
mask.
Examples:
>>> mask = torch.zeros(5, 5, dtype=torch.bool)
>>> mask[1:4, 1:4] = True
>>> mask_to_boundary(mask, mode="inner").sum().item()
8
Source code in inro/datasets.py
resize_matrix
¶
Return the matrix of antialiased bicubic resizing on one axis.
It is the operator of F.interpolate(..., mode="bicubic", antialias=True), whose
kernel is that of MATLAB's imresize and PIL's bicubic filter, with which
super-resolution benchmarks such as DIV2K make their low-resolution images.
Parameters:
-
size_in(int) –Size of the input axis.
-
size_out(int) –Size of the output axis.
-
device(str | device | None, default:None) –Device of the matrix;
Noneuses the default device.
Returns:
-
Tensor–Matrix
(size_out, size_in).
Examples:
>>> kernel = resize_matrix(64, 16)
>>> kernel.shape
torch.Size([16, 64])
>>> (kernel != 0).sum(1).max().item() # taps of one low-resolution pixel
16
Source code in inro/datasets.py
downsample
¶
Apply one kernel per axis to an image.
Parameters:
-
image(Tensor) –Image
(..., H, W, channels). -
kernels(Sequence[Tensor]) –Matrices
(..., h, H)and(..., w, W): those ofresize_matrix, or batches of their rows, such as each block ofSuperResolutionDatasetcarries.
Returns:
-
Tensor–Image
(..., h, w, channels).
Examples:
>>> kernels = resize_matrix(8, 4), resize_matrix(16, 4)
>>> downsample(torch.ones(8, 16, 3), kernels).shape
torch.Size([4, 4, 3])