Skip to main content

oa/image/
transform.rs

1//! Host-side geometric transform-matrix helpers.
2//!
3//! These produce the small 2x3 affine and 3x3 perspective matrices consumed
4//! by [`crate::image::warp_affine`] and [`crate::image::warp_perspective`],
5//! mirroring `getRotationMatrix2D`, `getPerspectiveTransform`,
6//! `invertAffineTransform`, and `estimateAffine2D`. All math runs on the host
7//! in f64 and returns plain F32 matrices, so the helpers compose with
8//! captured plans without recording device work.
9
10use crate::linalg::solve;
11use crate::matrix::Matrix;
12use crate::{Error, Result};
13
14/// Build the 2x3 rotation+scale matrix mapping about `center`, matching
15/// `getRotationMatrix2D`: `alpha = scale * cos(angle)`, `beta =
16/// scale * sin(angle)` with `angle` in degrees counterclockwise.
17///
18/// # Errors
19///
20/// Returns an error when any parameter is non-finite.
21pub fn rotation_matrix_2d(center_x: f32, center_y: f32, angle: f32, scale: f32) -> Result<Matrix> {
22	for (name, value) in [
23		("center_x", center_x),
24		("center_y", center_y),
25		("angle", angle),
26		("scale", scale),
27	] {
28		if !value.is_finite() {
29			return Err(Error::invalid_argument(format!(
30				"rotation_matrix_2d {name} must be finite"
31			)));
32		}
33	}
34	let radians = (angle as f64).to_radians();
35	let alpha = scale as f64 * radians.cos();
36	let beta = scale as f64 * radians.sin();
37	let (cx, cy) = (center_x as f64, center_y as f64);
38	let values = [
39		alpha,
40		beta,
41		(1.0 - alpha) * cx - beta * cy,
42		-beta,
43		alpha,
44		beta * cx + (1.0 - alpha) * cy,
45	];
46	Matrix::new_from_f32([2, 3], &values.map(|value| value as f32))
47}
48
49/// Invert a 2x3 affine transform matrix, matching `invertAffineTransform`.
50/// The input must be a `[2, 3]` F32 matrix with a nonsingular linear block.
51///
52/// # Errors
53///
54/// Returns an error unless `matrix` is a `[2, 3]` F32 matrix whose 2x2
55/// linear block is nonsingular.
56pub fn invert_affine(matrix: &Matrix) -> Result<Matrix> {
57	let [a, b, c, d, e, f] = read_affine(matrix, "invert_affine")?;
58	let determinant = a * e - b * d;
59	if determinant == 0.0 {
60		return Err(Error::invalid_argument(
61			"invert_affine requires a nonsingular 2x2 linear block",
62		));
63	}
64	let inverse = 1.0 / determinant;
65	let (ia, ib, id, ie) = (e * inverse, -b * inverse, -d * inverse, a * inverse);
66	let values = [ia, ib, -(ia * c + ib * f), id, ie, -(id * c + ie * f)];
67	Matrix::new_from_f32([2, 3], &values.map(|value| value as f32))
68}
69
70/// Solve the 3x3 perspective transform mapping four `[x, y]` source points
71/// to four destination points, matching `getPerspectiveTransform`. Both
72/// inputs must be `[4, 2]` F32 matrices.
73///
74/// # Errors
75///
76/// Returns an error unless both inputs are `[4, 2]` F32 matrices yielding a
77/// nonsingular 8x8 system (no three collinear source points).
78pub fn perspective_transform(source: &Matrix, destination: &Matrix) -> Result<Matrix> {
79	let source = read_points(source, 4, "perspective_transform")?;
80	let destination = read_points(destination, 4, "perspective_transform")?;
81	let mut a = [[0.0f64; 8]; 8];
82	let mut b = [0.0f64; 8];
83	for pair in 0..4 {
84		let [x, y] = source[pair];
85		let [u, v] = destination[pair];
86		a[2 * pair] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y];
87		b[2 * pair] = u;
88		a[2 * pair + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y];
89		b[2 * pair + 1] = v;
90	}
91	let h = solve(&mut a, &mut b, 8)
92		.ok_or_else(|| Error::invalid_argument("perspective_transform point set is degenerate"))?;
93	let values: Vec<f32> = h.iter().map(|value| *value as f32).chain([1.0]).collect();
94	Matrix::new_from_f32([3, 3], &values)
95}
96
97/// Least-squares estimate the 2x3 affine transform mapping `source` points
98/// to `destination` points, matching `estimateAffine2D` without refinement.
99/// Both inputs must be `[N, 2]` F32 matrices with `N >= 3` equal rows.
100///
101/// # Errors
102///
103/// Returns an error unless both inputs share an `[N, 2]` F32 shape with
104/// `N >= 3` and the normal equations are nonsingular.
105pub fn estimate_affine_2d(source: &Matrix, destination: &Matrix) -> Result<Matrix> {
106	if source.shape() != destination.shape() {
107		return Err(Error::invalid_argument(
108			"estimate_affine_2d source and destination shapes must match",
109		));
110	}
111	let source = read_points(source, 3, "estimate_affine_2d")?;
112	let destination = read_points(destination, 3, "estimate_affine_2d")?;
113	let mut normal = [[0.0f64; 6]; 6];
114	let mut rhs = [0.0f64; 6];
115	for pair in 0..source.len() {
116		let [x, y] = source[pair];
117		for (row, target) in [
118			([x, y, 1.0, 0.0, 0.0, 0.0], destination[pair][0]),
119			([0.0, 0.0, 0.0, x, y, 1.0], destination[pair][1]),
120		] {
121			for i in 0..6 {
122				rhs[i] += row[i] * target;
123				for j in 0..6 {
124					normal[i][j] += row[i] * row[j];
125				}
126			}
127		}
128	}
129	let parameters = solve(&mut normal, &mut rhs, 6)
130		.ok_or_else(|| Error::invalid_argument("estimate_affine_2d point set is degenerate"))?;
131	let values: Vec<f32> = parameters.iter().map(|value| *value as f32).collect();
132	Matrix::new_from_f32([2, 3], &values)
133}
134
135fn read_affine(matrix: &Matrix, operation: &str) -> Result<[f64; 6]> {
136	if matrix.shape() != [2, 3] {
137		return Err(Error::invalid_argument(format!(
138			"{operation} requires a [2, 3] matrix"
139		)));
140	}
141	let values = matrix.read_f32()?;
142	let mut affine = [0.0f64; 6];
143	for (index, value) in affine.iter_mut().enumerate() {
144		*value = values[index] as f64;
145	}
146	Ok(affine)
147}
148
149fn read_points(matrix: &Matrix, minimum: usize, operation: &str) -> Result<Vec<[f64; 2]>> {
150	let shape = matrix.shape();
151	if shape.len() != 2 || shape[1] != 2 || shape[0] < minimum {
152		return Err(Error::invalid_argument(format!(
153			"{operation} requires an [N, 2] matrix with N >= {minimum}"
154		)));
155	}
156	let values = matrix.read_f32()?;
157	Ok(
158		values
159			.as_chunks::<2>()
160			.0
161			.iter()
162			.map(|pair| [pair[0] as f64, pair[1] as f64])
163			.collect(),
164	)
165}