License YOLO
Back to Ultralytics Glossary

Affine Transformation

Affine transformation maps image coordinates through rotation, scaling, shear, and translation, supporting augmentation, alignment, and preprocessing.

An affine transformation is a coordinate mapping that combines a linear transformation with a translation. In images, it can rotate, resize, reflect, shear, or shift the pixel grid while preserving straight-line structure. Affine transform and affine map are synonyms. In computer vision, these mappings support alignment, data preprocessing, and data augmentation.

Leonhard Euler introduced the term affine for related curves in 1748, in chapter XVIII of Introductio in analysin infinitorum, volume 2.

What Affine Transformations Preserve#

An invertible affine transformation preserves straight lines, parallelism, and spacing ratios along a line. A midpoint remains a midpoint. Lengths and angles can change: shearing and unequal scaling can turn a rectangle into a parallelogram or a circle into an ellipse.

Rigid transformations preserve distances and angles; similarity transformations additionally allow uniform scaling. Affine transformations also allow unequal scaling and shear. A homography includes perspective effects, such as parallel road edges converging toward a vanishing point. An affine mapping preserves parallelism, fitting global skew and scale changes.

How the Affine Matrix Works#

A two-dimensional affine matrix has six parameters, commonly stored in a 2 x 3 matrix. Four control the linear part, and two specify horizontal and vertical translation. Three point pairs determine the matrix: the three source points must be non-collinear, forming a triangle. In OpenCV, cv2.getAffineTransform estimates the matrix from these correspondences.

Adding a constant third coordinate of 1, called a homogeneous coordinate, incorporates translation into matrix multiplication. The resulting 3 x 3 matrix has a final row of 0, 0, 1. Multiple transformations combine through matrix multiplication; rotating then shifting generally differs from shifting then rotating.

An affine transformation is linear exactly when its translation is zero. In a neural network, a fully connected layer combines learned weights with a bias offset. PyTorch's Linear layer applies an affine mapping by default, typically followed by a nonlinear activation function.

Uses in Vision and Model Training#

Ultralytics YOLO26 detection and segmentation training supports geometric augmentation through degrees, translate, scale, and shear, updating images and annotations together. With perspective=0.0, the mapping is affine; rotation and shear are disabled by default.

Apply an Affine Transformation in Python#

With pip install opencv-python numpy, this example uses OpenCV to rotate and shrink an image around its center:

from urllib.request import urlopen

import cv2
import numpy as np

with urlopen("https://ultralytics.com/images/bus.jpg") as response:
    encoded = np.frombuffer(response.read(), dtype=np.uint8)
image = cv2.imdecode(encoded, cv2.IMREAD_COLOR)
height, width = image.shape[:2]

# Rotation around the center also requires translation.
center = (width / 2, height / 2)
matrix = cv2.getRotationMatrix2D(center, angle=20, scale=0.8)
warped = cv2.warpAffine(image, matrix, (width, height))
cv2.imwrite("affine_result.jpg", warped)

The saved image shows a 20-degree rotation and scaling to 80% of the original dimensions inside an unchanged output canvas.

Resampling and Annotation Errors#

Warping samples a discrete pixel grid. Bilinear interpolation blends neighboring pixels; nearest-neighbor interpolation selects an existing value. Rotation exposes border regions with no source pixels, and a fixed canvas clips content outside its boundaries. Repeated bilinear resampling softens fine detail even when the coordinate mapping is invertible.

For supervised vision, images and annotations share the same mapping. Unchanged labels place targets at incorrect locations. Bounding boxes require transforming all four corners before computing an enclosing axis-aligned rectangle, which can include additional background after rotation. Keypoints outside the canvas require visibility updates. Categorical segmentation masks use nearest-neighbor interpolation to retain discrete class IDs.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Turn drone and aerial imagery into real-time insights for agriculture, aquaculture, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Apply computer vision in aerospace with Ultralytics YOLO for aircraft inspection, runway FOD detection, airport ground operations, and composite defect detection.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning