v9.1.1
Menu

Batch Affine Transform with PyTorch

mediumFREEMatrices & TransformationsTransformationsCV: Mathematical Foundations

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).

Return the result as a nested Python list of NN [x', y'] pairs (floats), each value rounded to 4 decimal places.

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
  • Inputs: points holds N=3N = 3 points (x,y)(x, y). transform is the 2×32 \times 3 matrix MM whose left 2×22 \times 2 block is the identity (no rotation or scaling) and whose last column is the translation (tx,ty)=(10,20)(t_x, t_y) = (10, 20).
  • Homogeneous form: each point gains a third coordinate equal to 11, e.g. (1,0)→(1,0,1)(1, 0) \to (1, 0, 1). That 11 multiplies txt_x and tyt_y, folding translation into one matrix product.
  • Worked point (1,0)(1, 0): x′=1⋅1+0⋅0+10⋅1=11x' = 1 \cdot 1 + 0 \cdot 0 + 10 \cdot 1 = 11 and y′=0⋅1+1⋅0+20⋅1=20y' = 0 \cdot 1 + 1 \cdot 0 + 20 \cdot 1 = 20.
  • Other points: (0,1)→(0+10, 1+20)=(10,21)(0, 1) \to (0 + 10,\ 1 + 20) = (10, 21) and (1,1)→(11,21)(1, 1) \to (11, 21).
  • Output: one (x′,y′)(x', y') row per input point, so N×2N \times 2: [[11.0, 20.0], [10.0, 21.0], [11.0, 21.0]]. Floats, rounded to 4 decimal places.
  • Notice: every point moves by exactly (10,20)(10, 20) because the linear part is the identity; a block of 22s on the diagonal with zero translation would double them instead.

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

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.