QGIS API Documentation 3.99.0-Master (21b3aa880ba)
Loading...
Searching...
No Matches
qgsleastsquares.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsleastsquares.cpp
3 --------------------------------------
4 Date : Sun Sep 16 12:03:37 AKDT 2007
5 Copyright : (C) 2007 by Gary E. Sherman
6 Email : sherman at mrcc dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsconfig.h"
17#include "qgsleastsquares.h"
18
19#include <cmath>
20#include <stdexcept>
21
22#include "qgsexception.h"
23
24#include <QObject>
25
26#ifdef HAVE_GSL
27#include <gsl/gsl_linalg.h>
28#include <gsl/gsl_blas.h>
29#endif
30
31void QgsLeastSquares::linear( const QVector<QgsPointXY> &sourceCoordinates, const QVector<QgsPointXY> &destinationCoordinates, QgsPointXY &origin, double &pixelXSize, double &pixelYSize )
32{
33 const int n = destinationCoordinates.size();
34 if ( n < 2 )
35 {
36 throw std::domain_error( QObject::tr( "Fit to a linear transform requires at least 2 points." ).toLocal8Bit().constData() );
37 }
38
39 double sumPx( 0 ), sumPy( 0 ), sumPx2( 0 ), sumPy2( 0 ), sumPxMx( 0 ), sumPyMy( 0 ), sumMx( 0 ), sumMy( 0 );
40 for ( int i = 0; i < n; ++i )
41 {
42 sumPx += sourceCoordinates.at( i ).x();
43 sumPy += sourceCoordinates.at( i ).y();
44 sumPx2 += std::pow( sourceCoordinates.at( i ).x(), 2 );
45 sumPy2 += std::pow( sourceCoordinates.at( i ).y(), 2 );
46 sumPxMx += sourceCoordinates.at( i ).x() * destinationCoordinates.at( i ).x();
47 sumPyMy += sourceCoordinates.at( i ).y() * destinationCoordinates.at( i ).y();
48 sumMx += destinationCoordinates.at( i ).x();
49 sumMy += destinationCoordinates.at( i ).y();
50 }
51
52 const double deltaX = n * sumPx2 - std::pow( sumPx, 2 );
53 const double deltaY = n * sumPy2 - std::pow( sumPy, 2 );
54
55 const double aX = ( sumPx2 * sumMx - sumPx * sumPxMx ) / deltaX;
56 const double aY = ( sumPy2 * sumMy - sumPy * sumPyMy ) / deltaY;
57 const double bX = ( n * sumPxMx - sumPx * sumMx ) / deltaX;
58 const double bY = ( n * sumPyMy - sumPy * sumMy ) / deltaY;
59
60 origin.setX( aX );
61 origin.setY( aY );
62
63 pixelXSize = std::fabs( bX );
64 pixelYSize = std::fabs( bY );
65}
66
67
68void QgsLeastSquares::helmert( const QVector<QgsPointXY> &sourceCoordinates, const QVector<QgsPointXY> &destinationCoordinates, QgsPointXY &origin, double &pixelSize, double &rotation )
69{
70#ifndef HAVE_GSL
71 ( void ) sourceCoordinates;
72 ( void ) destinationCoordinates;
73 ( void ) origin;
74 ( void ) pixelSize;
75 ( void ) rotation;
76 throw QgsNotSupportedException( QObject::tr( "Calculating a helmert transformation requires a QGIS build based GSL" ) );
77#else
78 const int n = destinationCoordinates.size();
79 if ( n < 2 )
80 {
81 throw std::domain_error( QObject::tr( "Fit to a Helmert transform requires at least 2 points." ).toLocal8Bit().constData() );
82 }
83
84 double A = 0;
85 double B = 0;
86 double C = 0;
87 double D = 0;
88 double E = 0;
89 double F = 0;
90 double G = 0;
91 double H = 0;
92 double I = 0;
93 double J = 0;
94 for ( int i = 0; i < n; ++i )
95 {
96 A += sourceCoordinates.at( i ).x();
97 B += sourceCoordinates.at( i ).y();
98 C += destinationCoordinates.at( i ).x();
99 D += destinationCoordinates.at( i ).y();
100 E += destinationCoordinates.at( i ).x() * sourceCoordinates.at( i ).x();
101 F += destinationCoordinates.at( i ).y() * sourceCoordinates.at( i ).y();
102 G += std::pow( sourceCoordinates.at( i ).x(), 2 );
103 H += std::pow( sourceCoordinates.at( i ).y(), 2 );
104 I += destinationCoordinates.at( i ).x() * sourceCoordinates.at( i ).y();
105 J += sourceCoordinates.at( i ).x() * destinationCoordinates.at( i ).y();
106 }
107
108 /* The least squares fit for the parameters { a, b, x0, y0 } is the solution
109 to the matrix equation Mx = b, where M and b is given below. I *think*
110 that this is correct but I derived it myself late at night. Look at
111 helmert.jpg if you suspect bugs. */
112
113 double MData[] = { A, -B, ( double ) n, 0., B, A, 0., ( double ) n, G + H, 0., A, B, 0., G + H, -B, A };
114
115 double bData[] = { C, D, E + F, J - I };
116
117 // we want to solve the equation M*x = b, where x = [a b x0 y0]
118 gsl_matrix_view M = gsl_matrix_view_array( MData, 4, 4 );
119 const gsl_vector_view b = gsl_vector_view_array( bData, 4 );
120 gsl_vector *x = gsl_vector_alloc( 4 );
121 gsl_permutation *p = gsl_permutation_alloc( 4 );
122 int s;
123 gsl_linalg_LU_decomp( &M.matrix, p, &s );
124 gsl_linalg_LU_solve( &M.matrix, p, &b.vector, x );
125 gsl_permutation_free( p );
126
127 origin.setX( gsl_vector_get( x, 2 ) );
128 origin.setY( gsl_vector_get( x, 3 ) );
129 pixelSize = std::sqrt( std::pow( gsl_vector_get( x, 0 ), 2 ) + std::pow( gsl_vector_get( x, 1 ), 2 ) );
130 rotation = std::atan2( gsl_vector_get( x, 1 ), gsl_vector_get( x, 0 ) );
131
132 gsl_vector_free( x );
133#endif
134}
135
136#if 0
137void QgsLeastSquares::affine( QVector<QgsPointXY> mapCoords,
138 QVector<QgsPointXY> pixelCoords )
139{
140 int n = mapCoords.size();
141 if ( n < 4 )
142 {
143 throw std::domain_error( QObject::tr( "Fit to an affine transform requires at least 4 points." ).toLocal8Bit().constData() );
144 }
145
146 double A = 0, B = 0, C = 0, D = 0, E = 0, F = 0,
147 G = 0, H = 0, I = 0, J = 0, K = 0;
148 for ( int i = 0; i < n; ++i )
149 {
150 A += pixelCoords[i].x();
151 B += pixelCoords[i].y();
152 C += mapCoords[i].x();
153 D += mapCoords[i].y();
154 E += std::pow( pixelCoords[i].x(), 2 );
155 F += std::pow( pixelCoords[i].y(), 2 );
156 G += pixelCoords[i].x() * pixelCoords[i].y();
157 H += pixelCoords[i].x() * mapCoords[i].x();
158 I += pixelCoords[i].y() * mapCoords[i].y();
159 J += pixelCoords[i].x() * mapCoords[i].y();
160 K += mapCoords[i].x() * pixelCoords[i].y();
161 }
162
163 /* The least squares fit for the parameters { a, b, c, d, x0, y0 } is the
164 solution to the matrix equation Mx = b, where M and b is given below.
165 I *think* that this is correct but I derived it myself late at night.
166 Look at affine.jpg if you suspect bugs. */
167
168 double MData[] = { A, B, 0, 0, ( double ) n, 0,
169 0, 0, A, B, 0, ( double ) n,
170 E, G, 0, 0, A, 0,
171 G, F, 0, 0, B, 0,
172 0, 0, E, G, 0, A,
173 0, 0, G, F, 0, B
174 };
175
176 double bData[] = { C, D, H, K, J, I };
177
178 // we want to solve the equation M*x = b, where x = [a b c d x0 y0]
179 gsl_matrix_view M = gsl_matrix_view_array( MData, 6, 6 );
180 gsl_vector_view b = gsl_vector_view_array( bData, 6 );
181 gsl_vector *x = gsl_vector_alloc( 6 );
182 gsl_permutation *p = gsl_permutation_alloc( 6 );
183 int s;
184 gsl_linalg_LU_decomp( &M.matrix, p, &s );
185 gsl_linalg_LU_solve( &M.matrix, p, &b.vector, x );
186 gsl_permutation_free( p );
187
188}
189#endif
190
196void normalizeCoordinates( const QVector<QgsPointXY> &coords, QVector<QgsPointXY> &normalizedCoords, double normalizeMatrix[9], double denormalizeMatrix[9] )
197{
198 // Calculate center of gravity
199 double cogX = 0.0, cogY = 0.0;
200 for ( int i = 0; i < coords.size(); i++ )
201 {
202 cogX += coords[i].x();
203 cogY += coords[i].y();
204 }
205 cogX *= 1.0 / coords.size();
206 cogY *= 1.0 / coords.size();
207
208 // Calculate mean distance to origin
209 double meanDist = 0.0;
210 for ( int i = 0; i < coords.size(); i++ )
211 {
212 const double X = ( coords[i].x() - cogX );
213 const double Y = ( coords[i].y() - cogY );
214 meanDist += std::sqrt( X * X + Y * Y );
215 }
216 meanDist *= 1.0 / coords.size();
217
218 const double OOD = meanDist * M_SQRT1_2;
219 const double D = 1.0 / OOD;
220 normalizedCoords.resize( coords.size() );
221 for ( int i = 0; i < coords.size(); i++ )
222 {
223 normalizedCoords[i] = QgsPointXY( ( coords[i].x() - cogX ) * D, ( coords[i].y() - cogY ) * D );
224 }
225
226 normalizeMatrix[0] = D;
227 normalizeMatrix[1] = 0.0;
228 normalizeMatrix[2] = -cogX * D;
229 normalizeMatrix[3] = 0.0;
230 normalizeMatrix[4] = D;
231 normalizeMatrix[5] = -cogY * D;
232 normalizeMatrix[6] = 0.0;
233 normalizeMatrix[7] = 0.0;
234 normalizeMatrix[8] = 1.0;
235
236 denormalizeMatrix[0] = OOD;
237 denormalizeMatrix[1] = 0.0;
238 denormalizeMatrix[2] = cogX;
239 denormalizeMatrix[3] = 0.0;
240 denormalizeMatrix[4] = OOD;
241 denormalizeMatrix[5] = cogY;
242 denormalizeMatrix[6] = 0.0;
243 denormalizeMatrix[7] = 0.0;
244 denormalizeMatrix[8] = 1.0;
245}
246
247// Fits a homography to the given corresponding points, and
248// return it in H (row-major format).
249void QgsLeastSquares::projective( const QVector<QgsPointXY> &sourceCoordinates, const QVector<QgsPointXY> &destinationCoordinates, double H[9] )
250{
251#ifndef HAVE_GSL
252 ( void ) sourceCoordinates;
253 ( void ) destinationCoordinates;
254 ( void ) H;
255 throw QgsNotSupportedException( QObject::tr( "Calculating a projective transformation requires a QGIS build based GSL" ) );
256#else
257 Q_ASSERT( sourceCoordinates.size() == destinationCoordinates.size() );
258
259 if ( destinationCoordinates.size() < 4 )
260 {
261 throw std::domain_error( QObject::tr( "Fitting a projective transform requires at least 4 corresponding points." ).toLocal8Bit().constData() );
262 }
263
264 QVector<QgsPointXY> sourceCoordinatesNormalized;
265 QVector<QgsPointXY> destinationCoordinatesNormalized;
266
267 double normSource[9], denormSource[9];
268 double normDest[9], denormDest[9];
269 normalizeCoordinates( sourceCoordinates, sourceCoordinatesNormalized, normSource, denormSource );
270 normalizeCoordinates( destinationCoordinates, destinationCoordinatesNormalized, normDest, denormDest );
271
272 // GSL does not support a full SVD, so we artificially add a linear dependent row
273 // to the matrix in case the system is underconstrained.
274 const uint m = std::max( 9u, ( uint ) destinationCoordinatesNormalized.size() * 2u );
275 const uint n = 9;
276 gsl_matrix *S = gsl_matrix_alloc( m, n );
277
278 for ( int i = 0; i < destinationCoordinatesNormalized.size(); i++ )
279 {
280 gsl_matrix_set( S, i * 2, 0, sourceCoordinatesNormalized[i].x() );
281 gsl_matrix_set( S, i * 2, 1, sourceCoordinatesNormalized[i].y() );
282 gsl_matrix_set( S, i * 2, 2, 1.0 );
283
284 gsl_matrix_set( S, i * 2, 3, 0.0 );
285 gsl_matrix_set( S, i * 2, 4, 0.0 );
286 gsl_matrix_set( S, i * 2, 5, 0.0 );
287
288 gsl_matrix_set( S, i * 2, 6, -destinationCoordinatesNormalized[i].x() * sourceCoordinatesNormalized[i].x() );
289 gsl_matrix_set( S, i * 2, 7, -destinationCoordinatesNormalized[i].x() * sourceCoordinatesNormalized[i].y() );
290 gsl_matrix_set( S, i * 2, 8, -destinationCoordinatesNormalized[i].x() * 1.0 );
291
292 gsl_matrix_set( S, i * 2 + 1, 0, 0.0 );
293 gsl_matrix_set( S, i * 2 + 1, 1, 0.0 );
294 gsl_matrix_set( S, i * 2 + 1, 2, 0.0 );
295
296 gsl_matrix_set( S, i * 2 + 1, 3, sourceCoordinatesNormalized[i].x() );
297 gsl_matrix_set( S, i * 2 + 1, 4, sourceCoordinatesNormalized[i].y() );
298 gsl_matrix_set( S, i * 2 + 1, 5, 1.0 );
299
300 gsl_matrix_set( S, i * 2 + 1, 6, -destinationCoordinatesNormalized[i].y() * sourceCoordinatesNormalized[i].x() );
301 gsl_matrix_set( S, i * 2 + 1, 7, -destinationCoordinatesNormalized[i].y() * sourceCoordinatesNormalized[i].y() );
302 gsl_matrix_set( S, i * 2 + 1, 8, -destinationCoordinatesNormalized[i].y() * 1.0 );
303 }
304
305 if ( destinationCoordinatesNormalized.size() == 4 )
306 {
307 // The GSL SVD routine only supports matrices with rows >= columns (m >= n)
308 // Unfortunately, we can't use the SVD of the transpose (i.e. S^T = (U D V^T)^T = V D U^T)
309 // to work around this, because the solution lies in the right nullspace of S, and
310 // gsl only supports a thin SVD of S^T, which does not return these vectors.
311
312 // HACK: duplicate last row to get a 9x9 equation system
313 for ( int j = 0; j < 9; j++ )
314 {
315 gsl_matrix_set( S, 8, j, gsl_matrix_get( S, 7, j ) );
316 }
317 }
318
319 // Solve Sh = 0 in the total least squares sense, i.e.
320 // with Sh = min and |h|=1. The solution "h" is given by the
321 // right singular eigenvector of S corresponding, to the smallest
322 // singular value (via SVD).
323 gsl_matrix *V = gsl_matrix_alloc( n, n );
324 gsl_vector *singular_values = gsl_vector_alloc( n );
325 gsl_vector *work = gsl_vector_alloc( n );
326
327 // V = n x n
328 // U = m x n (thin SVD) U D V^T
329 gsl_linalg_SV_decomp( S, V, singular_values, work );
330
331 // Columns of V store the right singular vectors of S
332 for ( unsigned int i = 0; i < n; i++ )
333 {
334 H[i] = gsl_matrix_get( V, i, n - 1 );
335 }
336
337 gsl_matrix *prodMatrix = gsl_matrix_alloc( 3, 3 );
338
339 gsl_matrix_view Hmatrix = gsl_matrix_view_array( H, 3, 3 );
340 const gsl_matrix_view normSourceMatrix = gsl_matrix_view_array( normSource, 3, 3 );
341 const gsl_matrix_view denormDestMatrix = gsl_matrix_view_array( denormDest, 3, 3 );
342
343 // Change coordinate frame of image and pre-image from normalized to destination and source coordinates.
344 // H' = denormalizeMapCoords*H*normalizePixelCoords
345 gsl_blas_dgemm( CblasNoTrans, CblasNoTrans, 1.0, &Hmatrix.matrix, &normSourceMatrix.matrix, 0.0, prodMatrix );
346 gsl_blas_dgemm( CblasNoTrans, CblasNoTrans, 1.0, &denormDestMatrix.matrix, prodMatrix, 0.0, &Hmatrix.matrix );
347
348 gsl_matrix_free( prodMatrix );
349 gsl_matrix_free( S );
350 gsl_matrix_free( V );
351 gsl_vector_free( singular_values );
352 gsl_vector_free( work );
353#endif
354}
static void helmert(const QVector< QgsPointXY > &sourceCoordinates, const QVector< QgsPointXY > &destinationCoordinates, QgsPointXY &origin, double &pixelSize, double &rotation)
Transforms the point at origin in-place, using a helmert transformation calculated from the list of s...
static void projective(const QVector< QgsPointXY > &sourceCoordinates, const QVector< QgsPointXY > &destinationCoordinates, double H[9])
Calculates projective parameters from the list of source and destination Ground Control Points (GCPs)...
static void linear(const QVector< QgsPointXY > &sourceCoordinates, const QVector< QgsPointXY > &destinationCoordinates, QgsPointXY &origin, double &pixelXSize, double &pixelYSize)
Transforms the point at origin in-place, using a linear transformation calculated from the list of so...
Custom exception class which is raised when an operation is not supported.
Represents a 2D point.
Definition qgspointxy.h:60
void setY(double y)
Sets the y value of the point.
Definition qgspointxy.h:129
void setX(double x)
Sets the x value of the point.
Definition qgspointxy.h:119
void normalizeCoordinates(const QVector< QgsPointXY > &coords, QVector< QgsPointXY > &normalizedCoords, double normalizeMatrix[9], double denormalizeMatrix[9])
Scales the given coordinates so that the center of gravity is at the origin and the mean distance to ...