Skip to content

Commit

Permalink
Add Affine.to_cairo, to output data in column major order, suitable
Browse files Browse the repository at this point in the history
for cairo.Matrix(...)
  • Loading branch information
stuaxo committed Feb 22, 2024
1 parent d790bdd commit d64f930
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions affine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,18 @@ def to_gdal(self):
"""
return (self.c, self.a, self.b, self.f, self.d, self.e)

def to_cairo(self):
"""Return a transformation matrix compatible with PyCairo.
PyCairo expects a 2x3 matrix in a column-major order.
Rearrange Affines (row-major) matrix to match.
>>> cairo.Matrix(*affine.to_cairo())
:rtype: tuple
"""
return (self.a, self.d, self.b, self.e, self.c, self.f)

def to_shapely(self):
"""Return an affine transformation matrix compatible with shapely
Expand Down Expand Up @@ -341,10 +353,10 @@ def _scaling(self):
# The singular values are the square root of the eigenvalues
# of the matrix times its transpose, M M*
# Computing trace and determinant of M M*
trace = a ** 2 + b ** 2 + d ** 2 + e ** 2
trace = a**2 + b**2 + d**2 + e**2
det = (a * e - b * d) ** 2

delta = trace ** 2 / 4 - det
delta = trace**2 / 4 - det
if delta < 1e-12:
delta = 0

Expand All @@ -362,7 +374,7 @@ def eccentricity(self) -> float:
Raises NotImplementedError for improper transformations.
"""
l1, l2 = self._scaling
return math.sqrt(l1 ** 2 - l2 ** 2) / l1
return math.sqrt(l1**2 - l2**2) / l1

@property
def rotation_angle(self) -> float:
Expand Down

0 comments on commit d64f930

Please sign in to comment.