📘
Batch Affine Transform with PyTorch
MediumTransformations
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′)=(acbdtxty)xy1
Or equivalently: x′=ax+by+tx, y′=cx+dy+ty
Key insight: For N points, convert to homogeneous coordinates (add column of 1s) and multiply with the transformation matrix transposed: P′=Ph⋅MT
where Ph is (N, 3) and MT is (3, 2), giving 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=(10011020)
For each point [x, y], compute: x′=1⋅x+0⋅y+10=x+10 y′=0⋅x+1⋅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
Python 3.13.1
Test Results
0/0Run code to see test results.