Affine
Affine is a Python library providing matrices that describe two-dimensional affine transformations of the plane. It is commonly used in geospatial contexts, such as with raster data, to transform between image and world coordinates. The current stable version is 2.4.0, with a major rewrite for version 3.0 currently in release candidate stages.
Warnings
- breaking In `affine` 3.0 (alpha/beta/rc releases), the `Affine` class is no longer a named tuple. This means direct JSON serialization without a custom adapter will break, and any code relying on `namedtuple` specific behaviors will need adjustment.
- breaking The precision for properties like `is_conformal` has changed from a global module attribute to an `Affine` class or instance attribute in version 3.0. Additionally, the `is_degenerate` property is now exact, removing previous precision considerations.
- breaking The sense of rotation has been reversed in `affine` 3.0. A positive angle now rotates a point counter-clockwise about the pivot point, which might be a change from previous versions' behavior.
- breaking For `affine` 3.0 and later, Python 3.9 or newer is required. Previous versions (like 2.4.0) supported Python 3.7+.
- gotcha When working with geospatial raster data, it's crucial to remember that the `affine` library (like GDAL and Rasterio) typically uses an origin (0,0) at the upper-left corner of the image, with Y increasing downwards. This differs from a standard Cartesian coordinate system where Y typically increases upwards.
Install
-
pip install affine -
pip install --pre affine
Imports
- Affine
from affine import Affine
Quickstart
from affine import Affine
# Create an identity affine transform
identity = Affine.identity()
print(f"Identity: {identity}")
# Create a translation transform (move by 10 units in x, 20 in y)
translation = Affine.translation(10, 20)
print(f"Translation: {translation}")
# Create a scaling transform (scale by 2x)
scaling = Affine.scale(2.0)
print(f"Scaling: {scaling}")
# Combine transforms by multiplication (scaling then translation)
combined = translation * scaling
print(f"Combined (scale then translate): {combined}")
# Apply the combined transform to a point (0, 0)
x, y = 0, 0
x_prime, y_prime = combined * (x, y)
print(f"Original point ({x}, {y}) transformed to ({x_prime}, {y_prime})")
# Example of rotation (rotate by 45 degrees)
rotation = Affine.rotation(45.0)
print(f"Rotation 45 deg: {rotation}")
# Apply rotation to a point (1, 0)
x_rot, y_rot = rotation * (1, 0)
print(f"Point (1,0) rotated 45 deg: ({x_rot:.2f}, {y_rot:.2f})")