PIXELBANKv8.2.1
Menu

Batch Affine Transform with PyTorch

Implement batch affine transformations on 2D points using PyTorch tensors.

Given a batch of 2D points and a 2×3 affine transformation matrix, apply the transformation to all points efficiently using matrix operations.

An affine transformation combines linear transformation (rotation, scaling, shearing) with translation:

(xy)=(abtxcdty)(xy1)\begin{pmatrix} x' \\ y' \end{pmatrix} = \begin{pmatrix} a & b & t_x \\ c & d & t_y \end{pmatrix} \begin{pmatrix} x \\ y \\ 1 \end{pmatrix}

Or equivalently: x=ax+by+txx' = ax + by + t_x, y=cx+dy+tyy' = cx + dy + t_y

Key insight: For N points, convert to homogeneous coordinates (add column of 1s) and multiply with the transformation matrix transposed: P=PhMTP' = P_h \cdot M^T

where PhP_h is (N, 3) and MTM^T is (3, 2), giving PP' as (N, 2).

Example:

Input:
points = [[1, 0], [0, 1], [1, 1]]
transform = [[1, 0, 10], [0, 1, 20]]  # Translation by (10, 20)
Output:
[[11.0, 20.0], [10.0, 21.0], [11.0, 21.0]]
Reasoning:

Affine matrix (translation only): M=(10100120)M = \begin{pmatrix} 1 & 0 & 10 \\ 0 & 1 & 20 \end{pmatrix}

For each point [x, y], compute: x=1x+0y+10=x+10x' = 1 \cdot x + 0 \cdot y + 10 = x + 10 y=0x+1y+20=y+20y' = 0 \cdot x + 1 \cdot y + 20 = y + 20

Results:

  • [1, 0] → [1+10, 0+20] = [11, 20]
  • [0, 1] → [0+10, 1+20] = [10, 21]
  • [1, 1] → [1+10, 1+20] = [11, 21]

Constraints:

  • points: Tensor of shape (N, 2) containing 2D points
  • transform: Tensor of shape (2, 3) - affine transformation matrix
  • Return: Transformed points as tensor of shape (N, 2)
  • Round to 4 decimal places
Editor

Test Results

0/0
Run code to see test results.