DCTorch: Discrete Cosine Transforms for PyTorch

0.1.2 · active · verified Fri Apr 17

DCTorch is a Python library providing fast discrete cosine transform (DCT) and inverse discrete cosine transform (IDCT) implementations optimized for PyTorch tensors. It enables efficient frequency domain analysis and manipulation within deep learning models, supporting 2D and 3D transforms. The current version is 0.1.2, and it appears to be actively maintained with recent commits.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform 2D Discrete Cosine Transform (DCT) and its inverse (IDCT) on a PyTorch tensor. It includes device selection for GPU acceleration and verifies the reconstruction accuracy.

import torch
from dctorch import dct_2d, idct_2d

# Determine device (CPU or CUDA if available)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

# Create a random tensor (Batch size, Channels, Height, Width)
x = torch.randn(1, 3, 224, 224, device=device)
print(f"Original tensor shape: {x.shape}")

# Perform 2D Discrete Cosine Transform
y = dct_2d(x)
print(f"DCT transformed tensor shape: {y.shape}")

# Perform Inverse 2D Discrete Cosine Transform
x_recon = idct_2d(y)
print(f"Reconstructed tensor shape: {x_recon.shape}")

# Verify reconstruction accuracy
reconstruction_error = torch.norm(x - x_recon).item()
print(f"Reconstruction error (L2 norm): {reconstruction_error:.6f}")

# Note: Error is typically very small due to floating point precision
assert reconstruction_error < 1e-4

view raw JSON →