API Reference

Resampling()

Image resizing and padding.

Atlas([min_size, max_size, force_square])

Texture atlas packing and sampling.

SurfaceOps()

Geometric surface processing.

Smoothstep(interpolant[, n])

Smoothstep interpolation.

SpectralNoise()

Spectral-domain procedural noise generators.

SpatialNoise()

Spatial-domain procedural noise generators.

Voronoi()

Voronoi-based generators.

SDF()

Signed distance field computation and rendering.

Tiling()

Tiling and tile blending.

Wavelet()

Wavelet transforms and coefficient culling.

Warping()

Warping and coordinate system translation.

class tinytex.Resampling[source]

Bases: object

Image resizing and padding.

classmethod compute_lod_offsets(height)[source]

Compute the vertical offsets for each mip level in a mip pyramid.

Parameters:

height (int) – Height of the base image, determines the number of mip levels and their vertical offsets.

Returns:

List of vertical offsets (in pixels) for each mip level. The base level is not included.

Return type:

List[int]

classmethod crop(im, shape, start=(0, 0))[source]

Crop image tensor to maximum target shape, if and only if a crop box target dimension is smaller than the boxed image dimension. Returned tensor can be smaller than target shape, depending on input image shape - i.e. no automatic padding.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W].

  • shape (tuple) – Target shape as (height, width) tuple.

  • start (tuple) – Top-left corner coordinates of the crop box as (top, left) tuple.

Returns:

Cropped image tensor sized [C, H, W] or [N, C, H, W].

classmethod generate_mip_pyramid(im)[source]

Generate a mipmap pyramid from input image and store it in a single image tensor. Pyramid is stored by placing the base image in the left portion and stacking each downsampled mip level vertically in the right portion.

Parameters:

im (torch.Tensor) – Input image tensor shape [C, H, W]

Returns:

Pyramid tensor of shape [C, H, W + W//2]

Return type:

torch.Tensor

classmethod pad_rb(im, shape, mode='replicate')[source]

Pad image tensor to the right and bottom to target shape.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W].

  • mode (str) – Padding algorithm (‘constant’ | ‘reflect’ | ‘replicate’ | ‘circular’).

  • shape (tuple)

Returns:

Padded image tensor sized [C, H, W] or [N, C, H, W].

Return type:

torch.Tensor

classmethod pad_to_next_pot(im, mode='replicate')[source]

Pad image tensor to next highest power-of-two square dimensions.

Parameters:
  • im (torch.Tensor) – image tensor sized [C, H, W] or [N, C, H, W]

  • mode (str) – padding algorithm (‘constant’ | ‘reflect’ | ‘replicate’ | ‘circular’)

Returns:

padded image tensor sized [C, H, W] or [N, C, H, W] where H = W

Return type:

torch.Tensor

classmethod resize(im, shape, mode='bilinear', iterative_downsample=False)[source]

Resize image tensor to target shape.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W].

  • shape (tuple) – Target shape as (height, width) tuple.

  • mode (str) – Resampleing algorithm (‘nearest’ | ‘linear’ | ‘bilinear’ | ‘bicubic’ | ‘area’).

  • iterative_downsample – Iteratively average pixels if image dimension must be reduced 2x or more.

Returns:

Resampled image tensor sized [C, H, W] or [N, C, H, W].

classmethod resize_le(im, size, mode='bilinear', iterative_downsample=False)[source]

Resize image tensor by longest edge, constraining proportions.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W]

  • size (int) – Target size for longest edge

  • mode (str) – Resampleing algorithm (‘nearest’ | ‘linear’ | ‘bilinear’ | ‘bicubic’ | ‘area’)

  • iterative_downsample – Iteratively average pixels if image dimension must be reduced 2x or more.

Returns:

Resampled image tensor sized [C, H, W] or [N, C, H, W]

Return type:

torch.Tensor

resize_le_to_next_pot(mode='bilinear')[source]

Resize image tensor by longest edge up to next higher power-of-two, constraining proportions.

Parameters:
  • im (torch.tensor) – Image tensor sized [C, H, W] or [N, C, H, W].

  • mode (str)

Returns:

Resampled image tensor sized [C, H, W] or [N, C, H, W].

classmethod resize_se(im, size, mode='bilinear', iterative_downsample=False)[source]

Resize image tensor by shortest edge, constraining proportions.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W]

  • size (int) – Target size for shortest edge

  • mode (str) – Resampleing algorithm (‘nearest’ | ‘linear’ | ‘bilinear’ | ‘bicubic’ | ‘area’)

  • iterative_downsample – Iteratively average pixels if image dimension must be reduced 2x or more.

Returns:

Resampled image tensor sized [C, H, W] or [N, C, H, W]

Return type:

torch.Tensor

classmethod sample_lod_bilinear(pyramid, height, width, lod)[source]

Resample a mip pyramid using standard bilinear interpolation at a given LOD.

Parameters:
  • pyramid (torch.Tensor) – Input mip pyramid tensor of shape [C, H, W], with stacked mips along height.

  • height (int) – Output image height.

  • width (int) – Output image width.

  • lod (float) – Level-of-detail value to sample from (can be fractional).

Returns:

Resampled image tensor of shape [C, height, width].

classmethod sample_lod_bspline_dither(height, width, lod)[source]

Resample a mip pyramid using stochastic B-spline dithering.

Converts the B-spline weights into a probability distribution and samples values probabilistically.

Parameters:
  • pyramid – Input mip pyramid tensor of shape [C, H, W], with stacked mips along height.

  • height (int) – Output image height.

  • width (int) – Output image width.

  • lod (float) – Level-of-detail value to sample from (can be fractional).

Returns:

Resampled image tensor of shape [C, height, width].

classmethod sample_lod_bspline_hybrid(pyramid, height, width, lod)[source]

Resample a mip pyramid using a hybrid (4-tap bilinear) B-spline filter approximation.

Parameters:
  • pyramid (torch.Tensor) – Input mip pyramid tensor of shape [C, H, W], with stacked mips along height.

  • height (int) – Output image height.

  • width (int) – Output image width.

  • lod (float) – Level-of-detail value to sample from (can be fractional).

Returns:

Resampled image tensor of shape [C, height, width].

classmethod tile(im, shape)[source]

Tile/repeat image tensor to match target shape.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W].

  • shape (tuple) – Target shape as (height, width) tuple.

Returns:

Padded image tensor sized [C, H, W] or [N, C, H, W].

Return type:

torch.Tensor

classmethod tile_n(im, repeat_h, repeat_w)[source]

Tile/repeat image tensor by number of repetitions.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W]

  • repeat_h (int) – Number of times to repeat image vertically.

  • repeat_w (int) – Number of times to repeat image horizontally.

Returns:

Padded image tensor sized [C, H, W] or [N, C, H, W].

classmethod tile_to_square(im, target_size)[source]

Tile image tensor to square dimensions of target size.

Parameters:
  • im (torch.Tensor) – Image tensor sized [C, H, W] or [N, C, H, W].

  • target_size (int)

Returns:

Padded image tensor sized [C, H, W] or [N, C, H, W] where H = W.

Return type:

torch.Tensor

class tinytex.Atlas(min_size=64, max_size=8192, force_square=False)[source]

Bases: object

Texture atlas packing and sampling.

add(key, tensor)[source]

Add a named texture to the atlas.

Parameters:
  • key (str) – Identifier for the texture.

  • tensor (torch.Tensor) – Image tensor in CHW format.

Return type:

None

classmethod from_dir(path, ext='.png', channels=3, allow_mismatch=True, max_h=0, max_w=0, crop=True, row=False, sort='height')[source]

Load all matching image files from a directory and pack them.

Parameters:
  • path (str) – Path to image directory.

  • ext (str) – File extension to match.

  • channels (int) – Expected channel count.

  • allow_mismatch (bool) – Auto pad/trim to match channels.

  • max_h (int) – Optional max height for atlas.

  • max_w (int) – Optional max width for atlas.

  • crop (bool) – Whether to crop excess space after packing.

  • row (bool) – Whether to use row packing.

  • sort (str) – Sorting mode.

Returns:

Packed Atlas instance.

Return type:

Atlas

generate_mask(shape, scale=1.0, samples=2)[source]

Generate a tiling mask by randomly overlaying textures.

Parameters:
  • shape (tuple) – Output (H, W) of the canvas.

  • scale (float) – Relative size of overlays.

  • samples (int) – Density multiplier for overlays.

Returns:

Output image tensor.

Return type:

torch.Tensor

pack(max_h=0, max_w=0, crop=True, row=False, sort='height')[source]

Pack added textures into a single atlas image.

Parameters:
  • max_h (int) – Max atlas height. If 0, auto-expand.

  • max_w (int) – Max atlas width. If 0, auto-expand.

  • crop (bool) – Crop output to tight bounding box.

  • row (bool) – Use row-based packing instead of rectangle packing.

  • sort (str) – Sorting mode for texture order (‘height’, ‘width’, ‘area’).

Returns:

(Atlas tensor, index dictionary with coordinates per texture).

Return type:

tuple

sample(key)[source]

Retrieve a single texture by name or index.

Parameters:

key (str | int) – Texture name or integer index.

Returns:

Image tensor sliced from the atlas.

Return type:

torch.Tensor

sample_random()[source]

Retrieve a randomly chosen texture from the atlas.

Returns:

Image tensor sliced from the atlas.

Return type:

torch.Tensor

class tinytex.SurfaceOps[source]

Bases: object

Geometric surface processing. Where applicable, assumes a right-handed y-up, x-right, z-back coordinate system and OpenGL-style normal maps.

classmethod angles_to_normals(angle_map, recompute_z=False, normalize=False, rescaled=False)[source]

Convert scaled spherical coordinates to tangent-space normal vectors.

Parameters:
  • angle_map (torch.Tensor) – Scaled spherical coordinates tensor sized [N, C=2, H, W] or [C=2, H, W], in range [0, 1].

  • reompute_z – Discard and recompute normal map’s z-channel after conversion.

  • normalize (bool) – Normalize vectors after conversion.

  • rescaled (bool) – Input and returned tensors should be in [0, 1] value range.

  • recompute_z (bool)

Returns:

Tensor of normals as unit vectors sized [N, C=3, H, W] or [C=3, H, W].

Return type:

torch.Tensor

classmethod blend_normals(normals_base, normals_detail, rescaled=False, eps=1e-08)[source]

Blend two normal maps with reoriented normal map algorithm.

Parameters:
  • normals_base (torch.Tensor) – Base normals tensor sized [N, C=3, H, W] or [C=3, H, W] as unit vectors of surface normals

  • normals_detail (torch.Tensor) – Detail normals tensor sized [N, C=3, H, W] or [C=3, H, W] as unit vectors of surface normals

  • rescaled (bool) – Input and returned unit vector tensors should be in [0, 1] value range.

  • eps (float) – epsilon

Returns:

blended normals tensor sized [N, C=3, H, W] or [C=3, H, W] as unit vectors of surface normals

classmethod compute_occlusion(normal_map=None, height_map=None, height_scale=1.0, radius=0.08, n_samples=256, rescaled=False)[source]

Compute ambient occlusion and bent normals from normal map and/or height map.

Parameters:
  • height_map (torch.Tensor) – Height map tensor sized [N, C=1, H, W] or [C=1, H, W] in [0, 1] range.

  • normal_map (torch.Tensor) – Normal map tensor sized [N, C=3, H, W] or [C=3, H, W] as unit vectors. of surface normals

  • height_scale (torch.Tensor | float) – Height scale as tensor sized [N, C=1] or [C=1], or as float.

  • radius (float) – Occlusion radius.

  • n_samples (int) – Number of occlusion samples per pixel.

  • rescaled (bool) – Input and returned unit vector tensors should be in [0, 1] value range.

Returns:

Ambient occlusion tensor sized [N, C=1, H, W] or [C=1, H, W], bent normals tensor sized [N, C=3, H, W] or [C=3, H, W].

Return type:

(torch.Tensor, torch.Tensor)

classmethod height_to_curvature(height_map, blur_kernel_size=0.0078125, blur_iter=1)[source]

Estimate mean curvature from a height map.

Parameters:
  • height_map (torch.Tensor) – [N, 1, H, W] or [1, H, W] tensor.

  • blur_kernel_size (float) – Relative kernel size for Gaussian blur.

  • blur_iter (int) – Number of blur passes.

Returns:

(curvature, cavities, peaks) — each [N, 1, H, W]

Return type:

tuple

classmethod height_to_normals(height_map, rescaled=False, eps=0.0001)[source]

Compute tangent-space normals form height.

Parameters:
  • height_map (torch.Tensor) – Height map tensor sized [N, C=1, H, W] or [C=1, H, W] in [0, 1] range

  • rescaled (bool) – Return unit vector tensor in [0, 1] value range.

  • eps (float) – Epsilon

Returns:

normals tensor sized [N, C=3, H, W] or [C=3, H, W] as unit vectors of surface normals.

Return type:

torch.Tensor

classmethod normalize(normal_map, rescaled=False)[source]

Normalize xyz vectors to unit length.

Parameters:
  • normal_map (torch.Tensor) – Tensor of normal vectors sized [N, C=3, H, W] or [C=3, H, W].

  • rescaled (bool) – Input and returned unit vector tensors should be in [0, 1] value range.

Returns:

Normalized tensor sized [N, C=3, H, W] or [C=3, H, W].

Return type:

torch.Tensor

classmethod normals_to_angles(normal_map, recompute_z=False, normalize=False, rescaled=False)[source]

Convert tangent-space normal vectors to scaled spherical coordinates.

Parameters:
  • normal_map (torch.Tensor) – Input normal map sized [N, C=3, H, W] or [C=3, H, W].

  • recompute_z (bool) – Discard and recompute normals’ z-channel before conversion.

  • normalize (bool) – Normalize vectors before conversion.

  • rescaled (bool) – Input and returned tensors should be in [0, 1] value range.

Returns:

Scaled z-axis and y-axis angles tensor sized [N, C=2, H, W] or [C=2, H, W], in range [0, 1].

classmethod normals_to_height(normal_map, self_tiling=False, rescaled=False, eps=torch.finfo.eps)[source]

Compute height from normals. Frankot-Chellappa algorithm.

Parameters:
  • normal_map (torch.Tensor) – Normal map tensor sized [N, C=3, H, W] or [C=3, H, W] as unit vectors of surface normals.

  • self_tiling (bool) – Treat surface as self-tiling.

  • rescaled (bool) – Accept unit vector tensor in [0, 1] value range.

  • eps (float)

Returns:

Height tensor sized [N, C=1, H, W] or [C=1, H, W] in [0, 1] range and height scale tensor sized [N, C=1] or [C=1] in [0, inf] range.

Return type:

(torch.Tensor, torch.Tensor)

classmethod recompute_z(normal_map, rescaled=False)[source]

Discard and recompute the z component of xyz vectors for a tangent-space normal map.

Parameters:
  • normal_map (torch.Tensor) – Tensor of normal vectors sized [N, C=3, H, W] or [C=3, H, W].

  • rescaled (bool) – Input and returned unit vector tensors should be in [0, 1] value range.

Returns:

Normals tensor with reconstructed z-channel sized [N, C=3, H, W] or [C=3, H, W].

Return type:

torch.Tensor

class tinytex.Smoothstep(interpolant, n=None)[source]

Bases: object

Smoothstep interpolation.

Parameters:
class Interpolant(value)[source]

Bases: IntEnum

Interpolant. See: https://iquilezles.org/articles/smoothsteps/

Table 1 Available Interpolants:

Identifier

Inverse Identifier

Continuity

CUBIC_POLYNOMIAL

INV_CUBIC_POLYNOMIAL

C1

QUARTIC_POLYNOMIAL

INV_QUARTIC_POLYNOMIAL

C1

QUINTIC_POLYNOMIAL

C2

QUADRATIC_RATIONAL

INV_QUADRATIC_RATIONAL

C1

CUBIC_RATIONAL

INV_CUBIC_RATIONAL

C2

RATIONAL

INV_RATIONAL

CV

PIECEWISE_QUADRATIC

INV_PIECEWISE_QUADRATIC

C1

PIECEWISE_POLYNOMIAL

INV_PIECEWISE_POLYNOMIAL

CV

TRIGONOMETRIC

INV_TRIGONOMETRIC

C1

classmethod apply(f, e0, e1, x, n=None)[source]

Static smoothstep evaluation with interpolant.

Parameters:
  • f (Interpolant | str) – Interpolant.

  • e0 (float) – Lower edge (min).

  • e1 (float) – Upper edge (max).

  • x (float | torch.Tensor) – Value.

  • n (int) – Order (if applicable).

Returns:

Interpolated result.

Return type:

(<class ‘float’>, torch.Tensor)

classmethod cubic_polynomial(x)[source]

Cubic polynomial - Hermite interpolation.

classmethod cubic_rational(x)[source]

Cubic rational interpolation.

forward(e0, e1, x)[source]

Apply forward smoothstep interpolation.

Parameters:
  • e0 – Lower bound.

  • e1 – Upper bound.

  • x – Input value(s).

Returns:

Interpolated output.

classmethod interpolate(f, x, n=None)[source]

Dispatch interpolation function based on interpolant.

Parameters:
  • f (Interpolant | str) – Interpolant.

  • x (float | torch.Tensor) – Normalized input.

  • n (int) – Order (if applicable).

Returns:

Interpolated output.

classmethod inv_cubic_polynomial(x)[source]

Inverse cubic polynomial interpolation.

classmethod inv_cubic_rational(x)[source]

Inverse cubic rational interpolation.

classmethod inv_piecewise_polynomial(x, n)[source]

Inverse piecewise polynomial interpolation.

classmethod inv_piecewise_quadratic(x)[source]

Inverse piecewise quadratic interpolation.

classmethod inv_quadratic_rational(x)[source]

Inverse quadratic rational interpolation.

classmethod inv_quartic_polynomial(x)[source]

Inverse quartic polynomial interpolation.

classmethod inv_rational(x, n)[source]

Inverse rational interpolation.

classmethod inv_trigonometric(x)[source]

Inverse trigonometric interpolation.

inverse(y)[source]

Apply inverse interpolation.

Parameters:

y – Interpolated value.

Returns:

Original input value.

classmethod piecewise_polynomial(x, n)[source]

Piecewise polynomial interpolation.

classmethod piecewise_quadratic(x)[source]

Piecewise quadratic interpolation.

classmethod quadratic_rational(x)[source]

Quadratic rational interpolation.

classmethod quartic_polynomial(x)[source]

Quartic polynomial interpolation.

classmethod quintic_polynomial(x)[source]

Quintic polynomial interpolation.

classmethod rational(x, n)[source]

Rational interpolation.

classmethod trigonometric(x)[source]

Trigonometric interpolation.

class tinytex.SpectralNoise[source]

Bases: object

Spectral-domain procedural noise generators.

classmethod blue(height, width)[source]

Generate 2D blue noise (f spectrum).

Parameters:
  • height (int) – Output height.

  • width (int) – Output width.

Returns:

2D tensor of blue noise with shape (height, width).

Return type:

torch.Tensor

classmethod brownian(height, width)[source]

Generate 2D brownian (red) noise (1/f² spectrum).

Parameters:
  • height (int) – Output height.

  • width (int) – Output width.

Returns:

2D tensor of brownian noise with shape (height, width).

Return type:

torch.Tensor

classmethod noise_psd_2d(height, width, psd=<function SpectralNoise.<lambda>>)[source]

Generate spectral 2D noise field. Shape (height, width) with a spectral shaping function psd.

Parameters:
  • height (int) – Field height.

  • width (int) – Field width.

  • psd – a function that accepts a tensor f of shape (height, width//2+1) of frequency magnitudes and returns a tensor of the same shape.

classmethod pink(height, width)[source]

Generate 2D pink noise (1/f spectrum).

Parameters:
  • height (int) – Output height.

  • width (int) – Output width.

Returns:

2D tensor of pink noise with shape (height, width).

Return type:

torch.Tensor

classmethod violet(height, width)[source]

Generate 2D violet noise (f² spectrum).

Parameters:
  • height (int) – Output height.

  • width (int) – Output width.

Returns:

2D tensor of violet noise with shape (height, width).

Return type:

torch.Tensor

classmethod white(height, width)[source]

Generate 2D white noise (flat power spectrum).

Parameters:
  • height (int) – Output height.

  • width (int) – Output width.

Returns:

2D tensor of white noise with shape (height, width).

Return type:

torch.Tensor

class tinytex.SpatialNoise[source]

Bases: object

Spatial-domain procedural noise generators.

classmethod fractal(shape, density=5.0, octaves=5, persistence=0.5, lacunarity=2, tileable=(True, True), interpolant='quintic_polynomial')[source]

Generate 2D fractal noise using layered Perlin noise.

Parameters:
  • shape (tuple) – Output shape as (height, width).

  • density (float) – Base frequency scale.

  • octaves (int) – Number of noise layers.

  • persistence (float) – Amplitude falloff per octave.

  • lacunarity (int) – Frequency multiplier per octave.

  • tileable (tuple) – Whether noise should tile along each axis.

  • interpolant (str) – Interpolation function name.

Returns:

Tensor of shape [1, H, W] with values in [0, 1].

Return type:

torch.Tensor

classmethod perlin(shape, density=5.0, tileable=(True, True), interpolant='quintic_polynomial')[source]

Generate 2D Perlin noise.

Parameters:
  • shape (tuple) – Output shape as (height, width).

  • density (float) – Controls frequency of the noise pattern.

  • tileable (tuple) – Whether noise should tile along each axis.

  • interpolant (str) – Interpolation function name (e.g., ‘linear’, ‘quintic_polynomial’).

Returns:

Tensor of shape [1, H, W] with values in [0, 1].

Return type:

torch.Tensor

classmethod turbulence(shape, density=5.0, octaves=5, persistence=0.5, lacunarity=2, tileable=(True, True), interpolant='quintic_polynomial', ridge=False)[source]

Generate 2D turbulence noise (absolute layered Perlin).

Parameters:
  • shape (tuple) – Output shape as (height, width).

  • density (float) – Base frequency scale.

  • octaves (int) – Number of noise layers.

  • persistence (float) – Amplitude falloff per octave.

  • lacunarity (int) – Frequency multiplier per octave.

  • tileable (tuple) – Whether noise should tile along each axis.

  • interpolant (str) – Interpolation function name.

  • ridge (bool) – If True, applies ridge-remapping for sharper features.

Returns:

Tensor of shape [1, H, W] with values in [0, 1].

Return type:

torch.Tensor

classmethod worley(shape, density=5.0, intensity=1.0, tileable=(True, True))[source]

Generate 2D Worley (cellular) noise.

Parameters:
  • shape (tuple) – Output shape as (height, width).

  • density (float) – Number of feature points per axis.

  • intensity (float) – Multiplier for the distance field.

  • tileable (tuple) – Whether noise should tile along each axis.

Returns:

Tensor of shape [1, H, W] with values in [0, 1].

Return type:

torch.Tensor

class tinytex.Voronoi[source]

Bases: object

Voronoi-based generators.

classmethod snap_nearest_as(uv_screen, vn_scale, scale, zoom_to, aspect, seed)[source]

Perturb UVs with a Voronoi field.

Parameters:
  • uv_screen (torch.Tensor) – UV coordinates of shape [2, H, W] in the range [0, 1]

  • vn_scale (float) – Voronoi scale factor that controls the size of the cells

  • scale (float) – Scene scale (zoom) factor

  • zoom_to (torch.Tensor) – Zoom center as a tensor of shape [2,] in normalized space

  • aspect (float) – Aspect ratio (width/height) of the scene

  • seed (int) – Random seed used to generate the Voronoi field

Returns:

A tensor of shape [6, H, W] where:

  • Channel 0: Perturbed UVs (u)

  • Channel 1: Perturbed UVs (v)

  • Channel 2: Voronoi cell ID (cell_id_x)

  • Channel 3: Voronoi cell ID (cell_id_y)

  • Channel 4: Distance from the edge of the Voronoi cell (edge_dist)

  • Channel 5: Distance from the center of the Voronoi cell (center_dist)

Return type:

torch.Tensor

classmethod snap_offset(x, seed)[source]

Vectorized Voronoi offset and distances. Given 2D position x and seed, returns F1, F2, best_offset_x, best_offset_y.

Parameters:
  • x (torch.Tensor)

  • seed (int)

class tinytex.SDF[source]

Bases: object

Signed distance field computation and rendering.

classmethod box(size=64, box_shape=(32, 32), length_factor=0.1, tile_to=None)[source]

Generate a rectangular SDF centered in the image.

Parameters:
  • size (int) – Output image size (square).

  • box_shape (tuple) – (height, width) of the rectangle.

  • length_factor (float) – Distance scaling factor.

  • tile_to (int | None) – Optional output tiling target.

Returns:

SDF tensor of shape [1, size, size].

Return type:

torch.Tensor

classmethod circle(size=64, radius=20, length_factor=0.1, tile_to=None)[source]

Generate a circular SDF centered in the image.

Parameters:
  • size (int) – Output image size (square).

  • radius (int) – Radius of the circle.

  • length_factor (float) – Distance scaling factor.

  • tile_to (int | None) – Optional output tiling target.

Returns:

SDF tensor of shape [1, size, size].

Return type:

torch.Tensor

classmethod compute(im, periodic=True, length_factor=0.1, threshold=None, tile_to=None)[source]

Compute a signed distance field from a binary image.

Parameters:
  • im (torch.Tensor) – Input tensor of shape [1, H, W].

  • periodic (bool) – Whether to use periodic boundary conditions.

  • length_factor (float) – Scales the maximum measurable distance.

  • threshold (float | None) – Binarization threshold if im isn’t binary.

  • tile_to (tuple | None) – Optional tiling target shape (H, W).

Returns:

Tensor of shape [1, H, W] with values in [0, 1].

Return type:

torch.Tensor

classmethod max(sdf1, sdf2)[source]

Return the maximum of two SDFs (intersection).

Parameters:
  • sdf1 (torch.Tensor)

  • sdf2 (torch.Tensor)

Return type:

torch.Tensor

classmethod min(sdf1, sdf2)[source]

Return the minimum of two SDFs (union).

Parameters:
  • sdf1 (torch.Tensor)

  • sdf2 (torch.Tensor)

Return type:

torch.Tensor

classmethod render(sdf, shape, edge0=0.496, edge1=0.498, value0=0.0, value1=1.0, interpolant='quintic_polynomial', mode='bilinear')[source]

Render an SDF to a grayscale field using soft-thresholding.

Parameters:
  • sdf (torch.Tensor) – Input SDF tensor of shape [1, H, W].

  • shape (tuple) – Output size (height, width).

  • edge0 (float) – Lower edge of the soft transition zone.

  • edge1 (float) – Upper edge of the soft transition zone.

  • value0 (float) – Output value below edge0.

  • value1 (float) – Output value above edge1.

  • interpolant (str) – Interpolation curve used between edge0 and edge1.

  • mode (str) – Interpolation method for resizing.

Returns:

Rendered tensor of shape [1, H, W].

Return type:

torch.Tensor

classmethod segment(size=64, a=(32, 0), b=(32, 64), length_factor=0.1, tile_to=None)[source]

Generate an SDF for a finite line segment.

Parameters:
  • size (int) – Output image size (square).

  • a (tuple) – Starting point of the segment.

  • b (tuple) – Ending point of the segment.

  • length_factor (float) – Distance scaling factor.

  • tile_to (int | None) – Optional output tiling target.

Returns:

SDF tensor of shape [1, size, size].

Return type:

torch.Tensor

class tinytex.Tiling[source]

Bases: object

Tiling and tile blending.

classmethod blend(tiles, rows=1, cols=1, wrap=True, vector_data=False)[source]

Blend tiles to remove seams. Uses Poisson solver to match image gradients.

Note

This is a computationally expensive task. For much faster performance, install AMGCL or PyAMG and they will be used over SciPy’s spsolve automatically.

Parameters:
  • tiles (torch.Tensor) – Tiles as pytorch image tensor sized [N, C, H, W] or [C, H, W].

  • rows (int) – Total number of rows in tile grid.

  • cols (int) – Total number of columns in tile grid.

  • wrap (bool) – Wrap tile grid border (allows self-tiling).

  • vector_data (bool) – Tiles contain directional unit vectors in [-1, 1] range - i.e. a normal map. If True, vectors will be converted to angles for blending so that component gradients can be matched independently.

Returns:

Blended tiles sized [N, C, H, W] or [C, H, W].

Return type:

torch.Tensor

classmethod get_tile_index(r, c, cols)[source]

Get tile index, by row and column position.

Parameters:
  • idx – Tile index.

  • r (int) – Tile’s row position.

  • c (int) – Tile’s column position.

  • cols (int) – Total number of columns in tile grid.

Returns:

row and column position, respectively

Return type:

int

classmethod get_tile_neighbors(r, c, rows, cols, wrap=False)[source]

Get indices of adjacent tiles from tile’s row and column position.

Parameters:
  • r (int) – Tile’s row position.

  • c (int) – Tile’s column position.

  • rows (int) – Total number of rows in tile grid.

  • cols (int) – Total number of columns in tile grid.

  • wrap (bool) – Wrap around edge tiles to opposite side of grid.

Returns:

Tile indices of top, right, bottom, and left neighboring tiles, respectively, or -1 if no neighboring tile (when wrap is False).

Return type:

(<class ‘int’>, <class ‘int’>, <class ‘int’>, <class ‘int’>)

classmethod get_tile_position(idx, cols)[source]

Get row and column position of tile in tile grid, by tile index.

Parameters:
  • idx (int) – tile index

  • cols (int) – total number of columns in tile grid

Returns:

row and column position, respectively

Return type:

(<class ‘int’>, <class ‘int’>)

classmethod merge(tiles, rows, cols)[source]

Combine non-overlapping tiles into composite image tensor. Tiles are expected to be ordered left-to-right and top-to-bottom:

| 0 | 1 | 2 |
-------------
| 3 | 4 | 5 |
-------------
| 6 | 7 | 8 |
Parameters:
  • tiles (torch.Tensor) – Tiles as pytorch image tensor sized [N, C, H, W].

  • rows (int) – Total number of rows in tile grid.

  • cols (int) – Total number of columns in tile grid.

Returns:

Combined image tensor sized [C, H, W].

Return type:

torch.Tensor

classmethod split(im, shape)[source]

Split image tensor into non-overlapping square tiles. Tiles are ordered left-to-right and top-to-bottom:

| 0 | 1 | 2 |
-------------
| 3 | 4 | 5 |
-------------
| 6 | 7 | 8 |

Warning

If image dimensions are not evenly divisible by tile size, image will be effectively cropped, based on how many tiles can fit.

Parameters:
  • im (torch.Tensor) – Image tensor sized [N=1, C, H, W] or [C, H, W].

  • shape (tuple) – Tile shape (height, width) in pixels.

Returns:

Image tensor sized [N, C, H, W], number of rows, number of columns.

Return type:

(torch.Tensor, <class ‘int’>, <class ‘int’>)

class tinytex.Wavelet[source]

Bases: object

Wavelet transforms and coefficient culling.

classmethod cull_haar_2d_aw(a, ratio)[source]

Keep only the strongest Haar coefficients in a 2D image by area-weighted magnitude.

Parameters:
  • a (torch.Tensor) – 2D Haar wavelet coefficients tensor sized [H, W] or [N, H, W], where N is batch count, H is height and W is width.

  • ratio (float) – Ratio of coefficients to cull, in range [0, 1].

Return type:

torch.Tensor

classmethod cull_haar_magnitude(a, ratio)[source]

Keep only the strongest Haar coefficients by magnitude.

Parameters:
  • a (torch.Tensor) – Haar wavelet coefficients tensor sized [F] or [N, F], where N is batch count and F is coefficient count.

  • ratio (float) – Ratio of coefficients to cull, in range [0, 1].

Return type:

torch.Tensor

classmethod haar(a)[source]

1D Haar transform.

Parameters:

a (torch.Tensor)

Return type:

torch.Tensor

classmethod haar_2d(im)[source]

2D Haar transform.

Parameters:

im (torch.Tensor)

Return type:

torch.Tensor

classmethod haar_bipolar(im)[source]

Scales Haar coefficients to range [0, 1]. Returns [C=3, H, W] sized tensor where negative values are red, positive values are blue, and zero is black.

Parameters:

im (torch.Tensor)

Return type:

torch.Tensor

classmethod inverse_haar(a)[source]

1D inverse Haar transform.

Parameters:

a (torch.Tensor)

Return type:

torch.Tensor

classmethod inverse_haar_2d(coeffs)[source]

2D inverse Haar transform.

Parameters:

coeffs (torch.Tensor)

Return type:

torch.Tensor

class tinytex.Warping[source]

Bases: object

Warping and coordinate system translation.

classmethod inverse_log_polar(im)[source]

Inverse log polar transform

Parameters:

im (torch.Tensor)

Return type:

torch.Tensor

classmethod log_polar(im, start_from=1, n_angular=None, n_radial=None)[source]

Log polar transform

Parameters:
  • im (torch.Tensor)

  • start_from (int)

Return type:

torch.Tensor