Margarine.Image (Margarine v0.2.3)

View Source

Image encoding and decoding utilities for Margarine.

Handles conversion between Nx tensors and PNG image format using Vix.

Image Format

Images are represented as Nx tensors with:

  • Type: {:u, 8} (unsigned 8-bit integers, 0-255)
  • Shape: {height, width, 3} (HWC format, RGB channels)
  • Or: {batch, height, width, 3} (BHWC format for batched images)

Examples

# Create a simple image tensor
tensor = Nx.tensor([
  [[255, 0, 0], [0, 255, 0]],  # Red and green pixels
  [[0, 0, 255], [255, 255, 255]]  # Blue and white pixels
]) |> Nx.as_type(:u8)

# Save as PNG
Margarine.Image.save(tensor, "output.png")

# Load PNG back
{:ok, loaded} = Margarine.Image.load("output.png")

# Convert tensor to PNG binary
{:ok, png_binary} = Margarine.Image.from_nx(tensor)

# Convert PNG binary back to tensor
{:ok, tensor} = Margarine.Image.to_nx(png_binary)

Summary

Functions

Converts an Nx tensor to PNG binary.

Loads a PNG file as an Nx tensor.

Normalizes tensor shape to 3D (HWC) by removing batch dimension if present.

Preprocesses an image for VAE encoding.

Resizes an image tensor to target dimensions using Vix.

Saves an Nx tensor as a PNG file.

Converts PNG binary to Nx tensor.

Validates that a tensor is suitable for image operations.

Types

png_binary()

@type png_binary() :: binary()

tensor()

@type tensor() :: Nx.Tensor.t()

Functions

from_nx(tensor)

@spec from_nx(tensor()) :: {:ok, png_binary()} | {:error, String.t()}

Converts an Nx tensor to PNG binary.

Parameters

  • tensor - Nx tensor with shape {H, W, 3} or {B, H, W, 3} and type {:u, 8}

Examples

tensor = Nx.tensor([[[255, 0, 0]]]) |> Nx.as_type(:u8)
{:ok, png_binary} = Margarine.Image.from_nx(tensor)

load(path)

@spec load(String.t()) :: {:ok, tensor()} | {:error, String.t()}

Loads a PNG file as an Nx tensor.

Parameters

  • path - File path to load from

Examples

{:ok, tensor} = Margarine.Image.load("/tmp/image.png")

normalize_shape(tensor)

@spec normalize_shape(tensor()) :: tensor()

Normalizes tensor shape to 3D (HWC) by removing batch dimension if present.

Examples

# 4D -> 3D
tensor = Nx.tensor([[[[255, 0, 0]]]]) |> Nx.as_type(:u8)
normalized = Margarine.Image.normalize_shape(tensor)  # {1, 1, 3}

# 3D -> 3D (no change)
tensor = Nx.tensor([[[255, 0, 0]]]) |> Nx.as_type(:u8)
normalized = Margarine.Image.normalize_shape(tensor)  # {1, 1, 3}

preprocess_for_vae(tensor, arg)

@spec preprocess_for_vae(
  tensor(),
  {pos_integer(), pos_integer()}
) :: {:ok, tensor()} | {:error, String.t()}

Preprocesses an image for VAE encoding.

Takes an image tensor (HWC uint8) and prepares it for the VAE encoder:

  1. Resizes to target dimensions
  2. Converts from uint8 [0,255] to float32 [-1,1]
  3. Converts from HWC to BCHW format

Parameters

  • tensor - Image tensor with shape {H, W, 3} and type {:u, 8}
  • target_size - Target {height, width} tuple

Returns

  • {:ok, preprocessed} - Preprocessed tensor [1, 3, height, width] float32 in range [-1, 1]
  • {:error, reason} - Preprocessing failed

Examples

{:ok, image} = Margarine.Image.load("photo.png")
{:ok, preprocessed} = Margarine.Image.preprocess_for_vae(image, {512, 512})
# preprocessed is now [1, 3, 512, 512] float32 in range [-1, 1]

resize(tensor, target_height, target_width)

@spec resize(tensor(), pos_integer(), pos_integer()) ::
  {:ok, tensor()} | {:error, String.t()}

Resizes an image tensor to target dimensions using Vix.

Parameters

  • tensor - Image tensor with shape {H, W, 3} and type {:u, 8}
  • target_height - Target height in pixels
  • target_width - Target width in pixels

Returns

  • {:ok, resized} - Resized tensor with shape {target_height, target_width, 3}
  • {:error, reason} - Resize failed

save(tensor, path)

@spec save(tensor(), String.t()) :: :ok | {:error, String.t()}

Saves an Nx tensor as a PNG file.

Creates parent directories if they don't exist.

Parameters

  • tensor - Nx tensor with shape {H, W, 3} or {B, H, W, 3} and type {:u, 8}
  • path - File path to save to

Examples

tensor = Nx.tensor([[[255, 0, 0]]]) |> Nx.as_type(:u8)
:ok = Margarine.Image.save(tensor, "/tmp/red_pixel.png")

to_nx(png_binary)

@spec to_nx(png_binary()) :: {:ok, tensor()} | {:error, String.t()}

Converts PNG binary to Nx tensor.

Parameters

  • png_binary - Binary data of a PNG image

Examples

{:ok, png_binary} = File.read("image.png")
{:ok, tensor} = Margarine.Image.to_nx(png_binary)

validate_tensor(tensor)

@spec validate_tensor(tensor()) :: :ok | {:error, String.t()}

Validates that a tensor is suitable for image operations.

Checks:

  • Type is {:u, 8}
  • Shape is either {H, W, 3} or {B, H, W, 3}
  • Dimensions are positive integers

Examples

tensor = Nx.tensor([[[255, 0, 0]]]) |> Nx.as_type(:u8)
:ok = Margarine.Image.validate_tensor(tensor)