PIXELBANKv9.1.0
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:

(xβ€²yβ€²)=(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β€²=Phβ‹…MTP' = P_h \cdot M^T

where PhP_h is (N, 3) and MTM^T is (3, 2), giving Pβ€²P' 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β€²=1β‹…x+0β‹…y+10=x+10x' = 1 \cdot x + 0 \cdot y + 10 = x + 10 yβ€²=0β‹…x+1β‹…y+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
solution.py

Test Results

0/0
Run code to see test results.
Batch Affine Transform with PyTorch - Medium | PixelBank