forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgdal_crs.cpp
1214 lines (1019 loc) · 39.3 KB
/
gdal_crs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: Mapinfo Image Warper
* Purpose: Implementation of the GDALTransformer wrapper around CRS.C
functions
* to build a polynomial transformation based on ground control
* points.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
***************************************************************************
CRS.C - Center for Remote Sensing rectification routines
Written By: Brian J. Buckley
At: The Center for Remote Sensing
Michigan State University
302 Berkey Hall
East Lansing, MI 48824
(517)353-7195
Written: 12/19/91
Last Update: 12/26/91 Brian J. Buckley
Last Update: 1/24/92 Brian J. Buckley
Added printout of trnfile. Triggered by BDEBUG.
Last Update: 1/27/92 Brian J. Buckley
Fixed bug so that only the active control points were used.
Last Update: 6/29/2011 C. F. Stallmann & R. van den Dool (South African
National Space Agency) GCP refinement added
Copyright (c) 1992, Michigan State University
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "gdal_alg.h"
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "cpl_minixml.h"
#include "cpl_string.h"
#include "cpl_atomic_ops.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define MAXORDER 3
namespace
{
struct Control_Points
{
int count;
double *e1;
double *n1;
double *e2;
double *n2;
int *status;
};
} // namespace
struct GCPTransformInfo
{
GDALTransformerInfo sTI{};
double adfToGeoX[20]{};
double adfToGeoY[20]{};
double adfFromGeoX[20]{};
double adfFromGeoY[20]{};
double x1_mean{};
double y1_mean{};
double x2_mean{};
double y2_mean{};
int nOrder{};
int bReversed{};
std::vector<gdal::GCP> asGCPs{};
int bRefine{};
int nMinimumGcps{};
double dfTolerance{};
volatile int nRefCount{};
};
CPL_C_START
CPLXMLNode *GDALSerializeGCPTransformer(void *pTransformArg);
void *GDALDeserializeGCPTransformer(CPLXMLNode *psTree);
CPL_C_END
/* crs.c */
static int CRS_georef(double, double, double *, double *, double[], double[],
int);
static int CRS_compute_georef_equations(GCPTransformInfo *psInfo,
struct Control_Points *, double[],
double[], double[], double[], int);
static int remove_outliers(GCPTransformInfo *);
#define MSUCCESS 1 /* SUCCESS */
#define MNPTERR 0 /* NOT ENOUGH POINTS */
#define MUNSOLVABLE -1 /* NOT SOLVABLE */
#define MMEMERR -2 /* NOT ENOUGH MEMORY */
#define MPARMERR -3 /* PARAMETER ERROR */
#define MINTERR -4 /* INTERNAL ERROR */
static const char *const CRS_error_message[] = {
"Failed to compute GCP transform: Not enough points available",
"Failed to compute GCP transform: Transform is not solvable",
"Failed to compute GCP transform: Not enough memory",
"Failed to compute GCP transform: Parameter error",
"Failed to compute GCP transform: Internal error"};
/************************************************************************/
/* GDALCreateSimilarGCPTransformer() */
/************************************************************************/
static void *GDALCreateSimilarGCPTransformer(void *hTransformArg,
double dfRatioX, double dfRatioY)
{
GCPTransformInfo *psInfo = static_cast<GCPTransformInfo *>(hTransformArg);
VALIDATE_POINTER1(hTransformArg, "GDALCreateSimilarGCPTransformer",
nullptr);
if (dfRatioX == 1.0 && dfRatioY == 1.0)
{
/* We can just use a ref count, since using the source transformation */
/* is thread-safe */
CPLAtomicInc(&(psInfo->nRefCount));
}
else
{
auto newGCPs = psInfo->asGCPs;
for (auto &gcp : newGCPs)
{
gcp.Pixel() /= dfRatioX;
gcp.Line() /= dfRatioY;
}
/* As remove_outliers modifies the provided GCPs we don't need to
* reapply it */
psInfo = static_cast<GCPTransformInfo *>(GDALCreateGCPTransformer(
static_cast<int>(newGCPs.size()), gdal::GCP::c_ptr(newGCPs),
psInfo->nOrder, psInfo->bReversed));
}
return psInfo;
}
/************************************************************************/
/* GDALCreateGCPTransformer() */
/************************************************************************/
static void *GDALCreateGCPTransformerEx(int nGCPCount,
const GDAL_GCP *pasGCPList,
int nReqOrder, bool bReversed,
bool bRefine, double dfTolerance,
int nMinimumGcps)
{
// If no minimumGcp parameter was passed, we use the default value
// according to the model
if (bRefine && nMinimumGcps == -1)
{
nMinimumGcps = ((nReqOrder + 1) * (nReqOrder + 2)) / 2 + 1;
}
GCPTransformInfo *psInfo = nullptr;
double *padfGeoX = nullptr;
double *padfGeoY = nullptr;
double *padfRasterX = nullptr;
double *padfRasterY = nullptr;
int *panStatus = nullptr;
int iGCP = 0;
int nCRSresult = 0;
struct Control_Points sPoints;
double x1_sum = 0;
double y1_sum = 0;
double x2_sum = 0;
double y2_sum = 0;
memset(&sPoints, 0, sizeof(sPoints));
if (nReqOrder == 0)
{
if (nGCPCount >= 10)
nReqOrder = 2; /*for now we avoid 3rd order since it is unstable*/
else if (nGCPCount >= 6)
nReqOrder = 2;
else
nReqOrder = 1;
}
psInfo = new GCPTransformInfo();
psInfo->bReversed = bReversed;
psInfo->nOrder = nReqOrder;
psInfo->bRefine = bRefine;
psInfo->dfTolerance = dfTolerance;
psInfo->nMinimumGcps = nMinimumGcps;
psInfo->nRefCount = 1;
psInfo->asGCPs = gdal::GCP::fromC(pasGCPList, nGCPCount);
if (nGCPCount == 2 && nReqOrder == 1 &&
psInfo->asGCPs[0].X() != psInfo->asGCPs[1].X() &&
psInfo->asGCPs[0].Y() != psInfo->asGCPs[1].Y())
{
// Assumes that the 2 GCPs form opposite corners of a rectangle,
// and synthetize a 3rd corner
gdal::GCP newGCP;
newGCP.X() = psInfo->asGCPs[1].X();
newGCP.Y() = psInfo->asGCPs[0].Y();
newGCP.Pixel() = psInfo->asGCPs[1].Pixel();
newGCP.Line() = psInfo->asGCPs[0].Line();
psInfo->asGCPs.emplace_back(std::move(newGCP));
nGCPCount = 3;
pasGCPList = gdal::GCP::c_ptr(psInfo->asGCPs);
}
memcpy(psInfo->sTI.abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE));
psInfo->sTI.pszClassName = "GDALGCPTransformer";
psInfo->sTI.pfnTransform = GDALGCPTransform;
psInfo->sTI.pfnCleanup = GDALDestroyGCPTransformer;
psInfo->sTI.pfnSerialize = GDALSerializeGCPTransformer;
psInfo->sTI.pfnCreateSimilar = GDALCreateSimilarGCPTransformer;
/* -------------------------------------------------------------------- */
/* Compute the forward and reverse polynomials. */
/* -------------------------------------------------------------------- */
if (nGCPCount == 0)
{
nCRSresult = MNPTERR;
}
else if (bRefine)
{
nCRSresult = remove_outliers(psInfo);
}
else
{
/* --------------------------------------------------------------------
*/
/* Allocate and initialize the working points list. */
/* --------------------------------------------------------------------
*/
try
{
padfGeoX = new double[nGCPCount];
padfGeoY = new double[nGCPCount];
padfRasterX = new double[nGCPCount];
padfRasterY = new double[nGCPCount];
panStatus = new int[nGCPCount];
for (iGCP = 0; iGCP < nGCPCount; iGCP++)
{
panStatus[iGCP] = 1;
padfGeoX[iGCP] = pasGCPList[iGCP].dfGCPX;
padfGeoY[iGCP] = pasGCPList[iGCP].dfGCPY;
padfRasterX[iGCP] = pasGCPList[iGCP].dfGCPPixel;
padfRasterY[iGCP] = pasGCPList[iGCP].dfGCPLine;
x1_sum += pasGCPList[iGCP].dfGCPPixel;
y1_sum += pasGCPList[iGCP].dfGCPLine;
x2_sum += pasGCPList[iGCP].dfGCPX;
y2_sum += pasGCPList[iGCP].dfGCPY;
}
psInfo->x1_mean = x1_sum / nGCPCount;
psInfo->y1_mean = y1_sum / nGCPCount;
psInfo->x2_mean = x2_sum / nGCPCount;
psInfo->y2_mean = y2_sum / nGCPCount;
sPoints.count = nGCPCount;
sPoints.e1 = padfRasterX;
sPoints.n1 = padfRasterY;
sPoints.e2 = padfGeoX;
sPoints.n2 = padfGeoY;
sPoints.status = panStatus;
nCRSresult = CRS_compute_georef_equations(
psInfo, &sPoints, psInfo->adfToGeoX, psInfo->adfToGeoY,
psInfo->adfFromGeoX, psInfo->adfFromGeoY, nReqOrder);
}
catch (const std::exception &e)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what());
nCRSresult = MINTERR;
}
delete[] padfGeoX;
delete[] padfGeoY;
delete[] padfRasterX;
delete[] padfRasterY;
delete[] panStatus;
}
if (nCRSresult != 1)
{
CPLError(CE_Failure, CPLE_AppDefined, "%s",
CRS_error_message[-nCRSresult]);
GDALDestroyGCPTransformer(psInfo);
return nullptr;
}
else
{
return psInfo;
}
}
/**
* Create GCP based polynomial transformer.
*
* Computes least squares fit polynomials from a provided set of GCPs,
* and stores the coefficients for later transformation of points between
* pixel/line and georeferenced coordinates.
*
* The return value should be used as a TransformArg in combination with
* the transformation function GDALGCPTransform which fits the
* GDALTransformerFunc signature. The returned transform argument should
* be deallocated with GDALDestroyGCPTransformer when no longer needed.
*
* This function may fail (returning nullptr) if the provided set of GCPs
* are inadequate for the requested order, the determinate is zero or they
* are otherwise "ill conditioned".
*
* Note that 2nd order requires at least 6 GCPs, and 3rd order requires at
* least 10 gcps. If nReqOrder is 0 the highest order possible (limited to 2)
* with the provided gcp count will be used.
*
* @param nGCPCount the number of GCPs in pasGCPList.
* @param pasGCPList an array of GCPs to be used as input.
* @param nReqOrder the requested polynomial order. It should be 1, 2 or 3.
* Using 3 is not recommended due to potential numeric instabilities issues.
* @param bReversed set it to TRUE to compute the reversed transformation.
*
* @return the transform argument or nullptr if creation fails.
*/
void *GDALCreateGCPTransformer(int nGCPCount, const GDAL_GCP *pasGCPList,
int nReqOrder, int bReversed)
{
return GDALCreateGCPTransformerEx(nGCPCount, pasGCPList, nReqOrder,
CPL_TO_BOOL(bReversed), false, -1, -1);
}
/** Create GCP based polynomial transformer, with a tolerance threshold to
* discard GCPs that transform badly.
*/
void *GDALCreateGCPRefineTransformer(int nGCPCount, const GDAL_GCP *pasGCPList,
int nReqOrder, int bReversed,
double dfTolerance, int nMinimumGcps)
{
return GDALCreateGCPTransformerEx(nGCPCount, pasGCPList, nReqOrder,
CPL_TO_BOOL(bReversed), true, dfTolerance,
nMinimumGcps);
}
/************************************************************************/
/* GDALDestroyGCPTransformer() */
/************************************************************************/
/**
* Destroy GCP transformer.
*
* This function is used to destroy information about a GCP based
* polynomial transformation created with GDALCreateGCPTransformer().
*
* @param pTransformArg the transform arg previously returned by
* GDALCreateGCPTransformer().
*/
void GDALDestroyGCPTransformer(void *pTransformArg)
{
if (pTransformArg == nullptr)
return;
GCPTransformInfo *psInfo = static_cast<GCPTransformInfo *>(pTransformArg);
if (CPLAtomicDec(&(psInfo->nRefCount)) == 0)
{
delete psInfo;
}
}
/************************************************************************/
/* GDALGCPTransform() */
/************************************************************************/
/**
* Transforms point based on GCP derived polynomial model.
*
* This function matches the GDALTransformerFunc signature, and can be
* used to transform one or more points from pixel/line coordinates to
* georeferenced coordinates (SrcToDst) or vice versa (DstToSrc).
*
* @param pTransformArg return value from GDALCreateGCPTransformer().
* @param bDstToSrc TRUE if transformation is from the destination
* (georeferenced) coordinates to pixel/line or FALSE when transforming
* from pixel/line to georeferenced coordinates.
* @param nPointCount the number of values in the x, y and z arrays.
* @param x array containing the X values to be transformed.
* @param y array containing the Y values to be transformed.
* @param z array containing the Z values to be transformed.
* @param panSuccess array in which a flag indicating success (TRUE) or
* failure (FALSE) of the transformation are placed.
*
* @return TRUE.
*/
int GDALGCPTransform(void *pTransformArg, int bDstToSrc, int nPointCount,
double *x, double *y, CPL_UNUSED double *z,
int *panSuccess)
{
int i = 0;
GCPTransformInfo *psInfo = static_cast<GCPTransformInfo *>(pTransformArg);
if (psInfo->bReversed)
bDstToSrc = !bDstToSrc;
for (i = 0; i < nPointCount; i++)
{
if (x[i] == HUGE_VAL || y[i] == HUGE_VAL)
{
panSuccess[i] = FALSE;
continue;
}
if (bDstToSrc)
{
CRS_georef(x[i] - psInfo->x2_mean, y[i] - psInfo->y2_mean, x + i,
y + i, psInfo->adfFromGeoX, psInfo->adfFromGeoY,
psInfo->nOrder);
}
else
{
CRS_georef(x[i] - psInfo->x1_mean, y[i] - psInfo->y1_mean, x + i,
y + i, psInfo->adfToGeoX, psInfo->adfToGeoY,
psInfo->nOrder);
}
panSuccess[i] = TRUE;
}
return TRUE;
}
/************************************************************************/
/* GDALSerializeGCPTransformer() */
/************************************************************************/
CPLXMLNode *GDALSerializeGCPTransformer(void *pTransformArg)
{
CPLXMLNode *psTree = nullptr;
GCPTransformInfo *psInfo = static_cast<GCPTransformInfo *>(pTransformArg);
VALIDATE_POINTER1(pTransformArg, "GDALSerializeGCPTransformer", nullptr);
psTree = CPLCreateXMLNode(nullptr, CXT_Element, "GCPTransformer");
/* -------------------------------------------------------------------- */
/* Serialize Order and bReversed. */
/* -------------------------------------------------------------------- */
CPLCreateXMLElementAndValue(psTree, "Order",
CPLSPrintf("%d", psInfo->nOrder));
CPLCreateXMLElementAndValue(psTree, "Reversed",
CPLSPrintf("%d", psInfo->bReversed));
if (psInfo->bRefine)
{
CPLCreateXMLElementAndValue(psTree, "Refine",
CPLSPrintf("%d", psInfo->bRefine));
CPLCreateXMLElementAndValue(psTree, "MinimumGcps",
CPLSPrintf("%d", psInfo->nMinimumGcps));
CPLCreateXMLElementAndValue(psTree, "Tolerance",
CPLSPrintf("%f", psInfo->dfTolerance));
}
/* -------------------------------------------------------------------- */
/* Attach GCP List. */
/* -------------------------------------------------------------------- */
if (!psInfo->asGCPs.empty())
{
if (psInfo->bRefine)
{
remove_outliers(psInfo);
}
GDALSerializeGCPListToXML(psTree, psInfo->asGCPs, nullptr);
}
return psTree;
}
/************************************************************************/
/* GDALDeserializeReprojectionTransformer() */
/************************************************************************/
void *GDALDeserializeGCPTransformer(CPLXMLNode *psTree)
{
std::vector<gdal::GCP> asGCPs;
void *pResult = nullptr;
int nReqOrder = 0;
int bReversed = 0;
int bRefine = 0;
int nMinimumGcps = 0;
double dfTolerance = 0.0;
/* -------------------------------------------------------------------- */
/* Check for GCPs. */
/* -------------------------------------------------------------------- */
CPLXMLNode *psGCPList = CPLGetXMLNode(psTree, "GCPList");
if (psGCPList != nullptr)
{
GDALDeserializeGCPListFromXML(psGCPList, asGCPs, nullptr);
}
/* -------------------------------------------------------------------- */
/* Get other flags. */
/* -------------------------------------------------------------------- */
nReqOrder = atoi(CPLGetXMLValue(psTree, "Order", "3"));
bReversed = atoi(CPLGetXMLValue(psTree, "Reversed", "0"));
bRefine = atoi(CPLGetXMLValue(psTree, "Refine", "0"));
nMinimumGcps = atoi(CPLGetXMLValue(psTree, "MinimumGcps", "6"));
dfTolerance = CPLAtof(CPLGetXMLValue(psTree, "Tolerance", "1.0"));
/* -------------------------------------------------------------------- */
/* Generate transformation. */
/* -------------------------------------------------------------------- */
if (bRefine)
{
pResult = GDALCreateGCPRefineTransformer(
static_cast<int>(asGCPs.size()), gdal::GCP::c_ptr(asGCPs),
nReqOrder, bReversed, dfTolerance, nMinimumGcps);
}
else
{
pResult = GDALCreateGCPTransformer(static_cast<int>(asGCPs.size()),
gdal::GCP::c_ptr(asGCPs), nReqOrder,
bReversed);
}
return pResult;
}
/************************************************************************/
/* ==================================================================== */
/* Everything below this point derived from the CRS.C from GRASS. */
/* ==================================================================== */
/************************************************************************/
/* STRUCTURE FOR USE INTERNALLY WITH THESE FUNCTIONS. THESE FUNCTIONS EXPECT
SQUARE MATRICES SO ONLY ONE VARIABLE IS GIVEN (N) FOR THE MATRIX SIZE */
struct MATRIX
{
int n; /* SIZE OF THIS MATRIX (N x N) */
double *v;
};
/* CALCULATE OFFSET INTO ARRAY BASED ON R/C */
#define M(row, col) m->v[(((row)-1) * (m->n)) + (col)-1]
/***************************************************************************/
/*
FUNCTION PROTOTYPES FOR STATIC (INTERNAL) FUNCTIONS
*/
/***************************************************************************/
static int calccoef(struct Control_Points *, double, double, double *, double *,
int);
static int calcls(struct Control_Points *, struct MATRIX *, double, double,
double *, double *, double *, double *);
static int exactdet(struct Control_Points *, struct MATRIX *, double, double,
double *, double *, double *, double *);
static int solvemat(struct MATRIX *, double *, double *, double *, double *);
static double term(int, double, double);
/***************************************************************************/
/*
TRANSFORM A SINGLE COORDINATE PAIR.
*/
/***************************************************************************/
static int
CRS_georef(double e1, /* EASTINGS TO BE TRANSFORMED */
double n1, /* NORTHINGS TO BE TRANSFORMED */
double *e, /* EASTINGS TO BE TRANSFORMED */
double *n, /* NORTHINGS TO BE TRANSFORMED */
double E[], /* EASTING COEFFICIENTS */
double N[], /* NORTHING COEFFICIENTS */
int order /* ORDER OF TRANSFORMATION TO BE PERFORMED, MUST MATCH THE
ORDER USED TO CALCULATE THE COEFFICIENTS */
)
{
double e3 = 0.0;
double e2n = 0.0;
double en2 = 0.0;
double n3 = 0.0;
double e2 = 0.0;
double en = 0.0;
double n2 = 0.0;
switch (order)
{
case 1:
*e = E[0] + E[1] * e1 + E[2] * n1;
*n = N[0] + N[1] * e1 + N[2] * n1;
break;
case 2:
e2 = e1 * e1;
n2 = n1 * n1;
en = e1 * n1;
*e = E[0] + E[1] * e1 + E[2] * n1 + E[3] * e2 + E[4] * en +
E[5] * n2;
*n = N[0] + N[1] * e1 + N[2] * n1 + N[3] * e2 + N[4] * en +
N[5] * n2;
break;
case 3:
e2 = e1 * e1;
en = e1 * n1;
n2 = n1 * n1;
e3 = e1 * e2;
e2n = e2 * n1;
en2 = e1 * n2;
n3 = n1 * n2;
*e = E[0] + E[1] * e1 + E[2] * n1 + E[3] * e2 + E[4] * en +
E[5] * n2 + E[6] * e3 + E[7] * e2n + E[8] * en2 + E[9] * n3;
*n = N[0] + N[1] * e1 + N[2] * n1 + N[3] * e2 + N[4] * en +
N[5] * n2 + N[6] * e3 + N[7] * e2n + N[8] * en2 + N[9] * n3;
break;
default:
return (MPARMERR);
}
return (MSUCCESS);
}
/***************************************************************************/
/*
COMPUTE THE GEOREFFERENCING COEFFICIENTS BASED ON A SET OF CONTROL POINTS
*/
/***************************************************************************/
static int CRS_compute_georef_equations(GCPTransformInfo *psInfo,
struct Control_Points *cp, double E12[],
double N12[], double E21[],
double N21[], int order)
{
double *tempptr = nullptr;
int status = 0;
if (order < 1 || order > MAXORDER)
return (MPARMERR);
/* CALCULATE THE FORWARD TRANSFORMATION COEFFICIENTS */
status = calccoef(cp, psInfo->x1_mean, psInfo->y1_mean, E12, N12, order);
if (status != MSUCCESS)
return (status);
/* SWITCH THE 1 AND 2 EASTING AND NORTHING ARRAYS */
tempptr = cp->e1;
cp->e1 = cp->e2;
cp->e2 = tempptr;
tempptr = cp->n1;
cp->n1 = cp->n2;
cp->n2 = tempptr;
/* CALCULATE THE BACKWARD TRANSFORMATION COEFFICIENTS */
status = calccoef(cp, psInfo->x2_mean, psInfo->y2_mean, E21, N21, order);
/* SWITCH THE 1 AND 2 EASTING AND NORTHING ARRAYS BACK */
tempptr = cp->e1;
cp->e1 = cp->e2;
cp->e2 = tempptr;
tempptr = cp->n1;
cp->n1 = cp->n2;
cp->n2 = tempptr;
return (status);
}
/***************************************************************************/
/*
COMPUTE THE GEOREFFERENCING COEFFICIENTS BASED ON A SET OF CONTROL POINTS
*/
/***************************************************************************/
static int calccoef(struct Control_Points *cp, double x_mean, double y_mean,
double E[], double N[], int order)
{
struct MATRIX m;
double *a = nullptr;
double *b = nullptr;
int numactive = 0; /* NUMBER OF ACTIVE CONTROL POINTS */
int status = 0;
int i = 0;
memset(&m, 0, sizeof(m));
/* CALCULATE THE NUMBER OF VALID CONTROL POINTS */
for (i = numactive = 0; i < cp->count; i++)
{
if (cp->status[i] > 0)
numactive++;
}
/* CALCULATE THE MINIMUM NUMBER OF CONTROL POINTS NEEDED TO DETERMINE
A TRANSFORMATION OF THIS ORDER */
m.n = ((order + 1) * (order + 2)) / 2;
if (numactive < m.n)
return (MNPTERR);
/* INITIALIZE MATRIX */
m.v = static_cast<double *>(
VSICalloc(cpl::fits_on<int>(m.n * m.n), sizeof(double)));
if (m.v == nullptr)
{
return (MMEMERR);
}
a = static_cast<double *>(VSICalloc(m.n, sizeof(double)));
if (a == nullptr)
{
CPLFree(m.v);
return (MMEMERR);
}
b = static_cast<double *>(VSICalloc(m.n, sizeof(double)));
if (b == nullptr)
{
CPLFree(m.v);
CPLFree(a);
return (MMEMERR);
}
if (numactive == m.n)
status = exactdet(cp, &m, x_mean, y_mean, a, b, E, N);
else
status = calcls(cp, &m, x_mean, y_mean, a, b, E, N);
CPLFree(m.v);
CPLFree(a);
CPLFree(b);
return (status);
}
/***************************************************************************/
/*
CALCULATE THE TRANSFORMATION COEFFICIENTS WITH EXACTLY THE MINIMUM
NUMBER OF CONTROL POINTS REQUIRED FOR THIS TRANSFORMATION.
*/
/***************************************************************************/
static int exactdet(struct Control_Points *cp, struct MATRIX *m, double x_mean,
double y_mean, double a[], double b[],
double E[], /* EASTING COEFFICIENTS */
double N[] /* NORTHING COEFFICIENTS */
)
{
int currow = 1;
for (int pntnow = 0; pntnow < cp->count; pntnow++)
{
if (cp->status[pntnow] > 0)
{
/* POPULATE MATRIX M */
for (int j = 1; j <= m->n; j++)
{
M(currow, j) =
term(j, cp->e1[pntnow] - x_mean, cp->n1[pntnow] - y_mean);
}
/* POPULATE MATRIX A AND B */
a[currow - 1] = cp->e2[pntnow];
b[currow - 1] = cp->n2[pntnow];
currow++;
}
}
if (currow - 1 != m->n)
return (MINTERR);
return (solvemat(m, a, b, E, N));
}
/***************************************************************************/
/*
CALCULATE THE TRANSFORMATION COEFFICIENTS WITH MORE THAN THE MINIMUM
NUMBER OF CONTROL POINTS REQUIRED FOR THIS TRANSFORMATION. THIS
ROUTINE USES THE LEAST SQUARES METHOD TO COMPUTE THE COEFFICIENTS.
*/
/***************************************************************************/
static int calcls(struct Control_Points *cp, struct MATRIX *m, double x_mean,
double y_mean, double a[], double b[],
double E[], /* EASTING COEFFICIENTS */
double N[] /* NORTHING COEFFICIENTS */
)
{
int numactive = 0;
/* INITIALIZE THE UPPER HALF OF THE MATRIX AND THE TWO COLUMN VECTORS */
for (int i = 1; i <= m->n; i++)
{
for (int j = i; j <= m->n; j++)
M(i, j) = 0.0;
a[i - 1] = b[i - 1] = 0.0;
}
/* SUM THE UPPER HALF OF THE MATRIX AND THE COLUMN VECTORS ACCORDING TO
THE LEAST SQUARES METHOD OF SOLVING OVER DETERMINED SYSTEMS */
for (int n = 0; n < cp->count; n++)
{
if (cp->status[n] > 0)
{
numactive++;
for (int i = 1; i <= m->n; i++)
{
for (int j = i; j <= m->n; j++)
M(i, j) += term(i, cp->e1[n] - x_mean, cp->n1[n] - y_mean) *
term(j, cp->e1[n] - x_mean, cp->n1[n] - y_mean);
a[i - 1] +=
cp->e2[n] * term(i, cp->e1[n] - x_mean, cp->n1[n] - y_mean);
b[i - 1] +=
cp->n2[n] * term(i, cp->e1[n] - x_mean, cp->n1[n] - y_mean);
}
}
}
if (numactive <= m->n)
return (MINTERR);
/* TRANSPOSE VALUES IN UPPER HALF OF M TO OTHER HALF */
for (int i = 2; i <= m->n; i++)
{
for (int j = 1; j < i; j++)
M(i, j) = M(j, i);
}
return (solvemat(m, a, b, E, N));
}
/***************************************************************************/
/*
CALCULATE THE X/Y TERM BASED ON THE TERM NUMBER
ORDER\TERM 1 2 3 4 5 6 7 8 9 10
1 e0n0 e1n0 e0n1
2 e0n0 e1n0 e0n1 e2n0 e1n1 e0n2
3 e0n0 e1n0 e0n1 e2n0 e1n1 e0n2 e3n0 e2n1 e1n2 e0n3
*/
/***************************************************************************/
static double term(int nTerm, double e, double n)
{
switch (nTerm)
{
case 1:
return (1.0);
case 2:
return (e);
case 3:
return (n);
case 4:
return ((e * e));
case 5:
return ((e * n));
case 6:
return ((n * n));
case 7:
return ((e * e * e));
case 8:
return ((e * e * n));
case 9:
return ((e * n * n));
case 10:
return ((n * n * n));
}
return 0.0;
}
/***************************************************************************/
/*
SOLVE FOR THE 'E' AND 'N' COEFFICIENTS BY USING A SOMEWHAT MODIFIED
GAUSSIAN ELIMINATION METHOD.
| M11 M12 ... M1n | | E0 | | a0 |
| M21 M22 ... M2n | | E1 | = | a1 |
| . . . . | | . | | . |
| Mn1 Mn2 ... Mnn | | En-1 | | an-1 |
and
| M11 M12 ... M1n | | N0 | | b0 |
| M21 M22 ... M2n | | N1 | = | b1 |
| . . . . | | . | | . |
| Mn1 Mn2 ... Mnn | | Nn-1 | | bn-1 |
*/
/***************************************************************************/
static int solvemat(struct MATRIX *m, double a[], double b[], double E[],
double N[])
{
for (int i = 1; i <= m->n; i++)
{
int j = i;
/* find row with largest magnitude value for pivot value */
double pivot =
M(i, j); /* ACTUAL VALUE OF THE LARGEST PIVOT CANDIDATE */
int imark = i;
for (int i2 = i + 1; i2 <= m->n; i2++)
{
if (fabs(M(i2, j)) > fabs(pivot))
{
pivot = M(i2, j);
imark = i2;
}
}
/* if the pivot is very small then the points are nearly co-linear */
/* co-linear points result in an undefined matrix, and nearly */
/* co-linear points results in a solution with rounding error */
if (pivot == 0.0)
return (MUNSOLVABLE);
/* if row with highest pivot is not the current row, switch them */
if (imark != i)
{
for (int j2 = 1; j2 <= m->n; j2++)
{
std::swap(M(imark, j2), M(i, j2));
}
std::swap(a[imark - 1], a[i - 1]);
std::swap(b[imark - 1], b[i - 1]);
}
/* compute zeros above and below the pivot, and compute
values for the rest of the row as well */
for (int i2 = 1; i2 <= m->n; i2++)
{
if (i2 != i)
{
const double factor = M(i2, j) / pivot;
for (int j2 = j; j2 <= m->n; j2++)
M(i2, j2) -= factor * M(i, j2);
a[i2 - 1] -= factor * a[i - 1];