This file is indexed.

/usr/lib/perl5/PDL/Image2D.pm is in pdl 1:2.4.7+dfsg-2ubuntu5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
#
# GENERATED WITH PDL::PP! Don't modify!
#
package PDL::Image2D;

@EXPORT_OK  = qw( PDL::PP conv2d PDL::PP med2d PDL::PP med2df PDL::PP box2d PDL::PP patch2d PDL::PP patchbad2d PDL::PP max2d_ind PDL::PP centroid2d PDL::PP cc8compt PDL::PP polyfill  polyfillv  rotnewsz PDL::PP rot2d PDL::PP bilin2d PDL::PP rescale2d  fitwarp2d applywarp2d PDL::PP warp2d  warp2d_kernel PDL::PP warp2d_kernel );
%EXPORT_TAGS = (Func=>[@EXPORT_OK]);

use PDL::Core;
use PDL::Exporter;
use DynaLoader;



   
   @ISA    = ( 'PDL::Exporter','DynaLoader' );
   push @PDL::Core::PP, __PACKAGE__;
   bootstrap PDL::Image2D ;





=head1 NAME

PDL::Image2D - Miscellaneous 2D image processing functions

=head1 DESCRIPTION

Miscellaneous 2D image processing functions - for want
of anywhere else to put them.  

=head1 SYNOPSIS

 use PDL::Image2D;

=cut

use PDL;  # ensure qsort routine available
use PDL::Math;
use Carp;

use strict;







=head1 FUNCTIONS



=cut






=head2 conv2d

=for sig

  Signature: (a(m,n); kern(p,q); [o]b(m,n); int opt)

=for ref

2D convolution of an array with a kernel (smoothing)

For large kernels, using a FFT routine,
such as L<fftconvolve()|PDL::FFT/fftconvolve()> in C<PDL::FFT>,
will be quicker.

=for usage

 $new = conv2d $old, $kernel, {OPTIONS}

=for example

 $smoothed = conv2d $image, ones(3,3), {Boundary => Reflect}

=for options

 Boundary - controls what values are assumed for the image when kernel
            crosses its edge:
 	    => Default  - periodic boundary conditions 
                          (i.e. wrap around axis)
 	    => Reflect  - reflect at boundary
 	    => Truncate - truncate at boundary



=for bad

Unlike the FFT routines, conv2d is able to process bad values.

=cut






sub PDL::conv2d {
   my $opt; $opt = pop @_ if ref($_[$#_]) eq 'HASH';
   die 'Usage: conv2d( a(m,n), kern(p,q), [o]b(m,n), {Options} )'
      if $#_<1 || $#_>2;
   my($a,$kern) = @_;
   my $c = $#_ == 2 ? $_[2] : $a->nullcreate;
   &PDL::_conv2d_int($a,$kern,$c,
	(!(defined $opt && exists $$opt{Boundary}))?0:
	(($$opt{Boundary} eq "Reflect") +
	2*($$opt{Boundary} eq "Truncate")));
   return $c;
}



*conv2d = \&PDL::conv2d;




=head2 med2d

=for sig

  Signature: (a(m,n); kern(p,q); [o]b(m,n); int opt)

=for ref

2D median-convolution of an array with a kernel (smoothing)

Note: only points in the kernel E<gt>0 are included in the median, other
points are weighted by the kernel value (medianing lots of zeroes
is rather pointless)

=for usage

 $new = med2d $old, $kernel, {OPTIONS}

=for example

 $smoothed = med2d $image, ones(3,3), {Boundary => Reflect}

=for options

 Boundary - controls what values are assumed for the image when kernel
            crosses its edge:
 	    => Default  - periodic boundary conditions (i.e. wrap around axis)
 	    => Reflect  - reflect at boundary
 	    => Truncate - truncate at boundary



=for bad

Bad values are ignored in the calculation. If all elements within the 
kernel are bad, the output is set bad.

=cut






sub PDL::med2d {
   my $opt; $opt = pop @_ if ref($_[$#_]) eq 'HASH';
   die 'Usage: med2d( a(m,n), kern(p,q), [o]b(m,n), {Options} )'
      if $#_<1 || $#_>2;
   my($a,$kern) = @_;
   croak "med2d: kernel must contain some positive elements.\n" 
       if all( $kern <= 0 );
   my $c = $#_ == 2 ? $_[2] : $a->nullcreate;
   &PDL::_med2d_int($a,$kern,$c,
	(!(defined $opt && exists $opt->{Boundary}))?0:
	(($$opt{Boundary} eq "Reflect") +
	2*($$opt{Boundary} eq "Truncate")));
   return $c;
}



*med2d = \&PDL::med2d;




=head2 med2df

=for sig

  Signature: (a(m,n); [o]b(m,n); int __p_size; int __q_size; int opt)

=for ref

2D median-convolution of an array in a pxq window (smoothing)

Note: this routine does the median over all points in a rectangular
      window and is not quite as flexible as C<med2d> in this regard
      but slightly faster instead

=for usage

 $new = med2df $old, $xwidth, $ywidth, {OPTIONS}

=for example

 $smoothed = med2df $image, 3, 3, {Boundary => Reflect}

=for options

 Boundary - controls what values are assumed for the image when kernel
            crosses its edge:
 	    => Default  - periodic boundary conditions (i.e. wrap around axis)
 	    => Reflect  - reflect at boundary
 	    => Truncate - truncate at boundary



=for bad

med2df does not process bad values.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






sub PDL::med2df {
   my $opt; $opt = pop @_ if ref($_[$#_]) eq 'HASH';
   die 'Usage: med2df( a(m,n), [o]b(m,n), p, q, {Options} )'
      if $#_<2 || $#_>3;
   my($a,$p,$q) = @_;
   croak "med2df: kernel must contain some positive elements.\n" 
       if $p == 0 && $q == 0;
   my $c = $#_ == 3 ? $_[3] : $a->nullcreate;
   &PDL::_med2df_int($a,$c,$p,$q,
	(!(defined $opt && exists $opt->{Boundary}))?0:
	(($$opt{Boundary} eq "Reflect") +
	2*($$opt{Boundary} eq "Truncate")));
   return $c;
}



*med2df = \&PDL::med2df;




=head2 box2d

=for sig

  Signature: (a(n,m); [o] b(n,m); int wx; int wy; int edgezero)

=for ref

fast 2D boxcar average

=for example

  $smoothim = $im->box2d($wx,$wy,$edgezero=1);

The edgezero argument controls if edge is set to zero (edgezero=1)
or just keeps the original (unfiltered) values.

C<box2d> should be updated to support similar edge options
as C<conv2d> and C<med2d> etc.

Boxcar averaging is a pretty crude way of filtering. For serious stuff
better filters are around (e.g., use L<conv2d|conv2d> with the appropriate
kernel). On the other hand it is fast and computational cost grows only
approximately linearly with window size.


=for bad

box2d does not process bad values.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






*box2d = \&PDL::box2d;




=head2 patch2d

=for sig

  Signature: (a(m,n); int bad(m,n); [o]b(m,n))

=for ref

patch bad pixels out of 2D images using a mask

=for usage

 $patched = patch2d $data, $bad;

C<$bad> is a 2D mask array where 1=bad pixel 0=good pixel. 
Pixels are replaced by the average of their non-bad neighbours;
if all neighbours are bad, the original data value is
copied across.



=for bad

This routine does not handle bad values - use L<patchbad2d|/patchbad2d> instead

=cut






*patch2d = \&PDL::patch2d;




=head2 patchbad2d

=for sig

  Signature: (a(m,n); [o]b(m,n))

=for ref

patch bad pixels out of 2D images containing bad values

=for usage

 $patched = patchbad2d $data;

Pixels are replaced by the average of their non-bad neighbours;
if all neighbours are bad, the output is set bad.
If the input piddle contains I<no> bad values, then a straight copy
is performed (see L<patch2d|/patch2d>).



=for bad

patchbad2d handles bad values. The output piddle I<may> contain
bad values, depending on the pattern of bad values in the input piddle.

=cut






*patchbad2d = \&PDL::patchbad2d;




=head2 max2d_ind

=for sig

  Signature: (a(m,n); [o]val(); int [o]x(); int[o]y())

=for ref

Return value/position of maximum value in 2D image

Contributed by Tim Jeness



=for bad


Bad values are excluded from the search. If all pixels
are bad then the output is set bad.



=cut






*max2d_ind = \&PDL::max2d_ind;




=head2 centroid2d

=for sig

  Signature: (im(m,n); x(); y(); box(); [o]xcen(); [o]ycen())

=for ref

Refine a list of object positions in 2D image by centroiding in a box

C<$box> is the full-width of the box, i.e. the window
is C<+/- $box/2>.



=for bad

Bad pixels are excluded from the centroid calculation. If all elements are
bad (or the pixel sum is 0 - but why would you be centroiding
something with negatives in...) then the output values are set bad.



=cut






*centroid2d = \&PDL::centroid2d;




=head2 cc8compt

=for sig

  Signature: (a(m,n); [o]b(m,n))


=for ref

Connected 8-component labeling of a binary image.

Connected 8-component labeling of 0,1 image - i.e. find seperate
segmented objects and fill object pixels with object number

=for example

 $segmented = cc8compt( $image > $threshold );



=for bad

cc8compt ignores the bad-value flag of the input piddles.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






*cc8compt = \&PDL::cc8compt;




=head2 polyfill

=for sig

  Signature: (int [o,nc] im(m,n); float ps(two=2,np); int col())

=for ref

fill the area inside the given polygon with a given colour

This function works inplace, i.e. modifies C<im>.



=for bad

polyfill ignores the bad-value flag of the input piddles.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






*polyfill = \&PDL::polyfill;



=head2 polyfillv

=for ref

return the (dataflown) area of an image within a polygon

=for example

  # increment intensity in area bounded by $poly
  $im->polyfillv($pol)++; # legal in perl >= 5.6
  # compute average intensity within area bounded by $poly
  $av = $im->polyfillv($poly)->avg;

=cut

sub PDL::polyfillv {
  my ($im, $ps) = @_;
  my $msk = zeroes(long,$im->dims);
  polyfill($msk, $ps, 1);
  return $im->where($msk == 1);
}
*polyfillv = \&PDL::polyfillv;





=head2 rot2d

=for sig

  Signature: (im(m,n); float angle(); bg(); int aa(); [o] om(p,q))

=for ref

rotate an image by given C<angle>

=for example

  # rotate by 10.5 degrees with antialiasing, set missing values to 7
  $rot = $im->rot2d(10.5,7,1);

This function rotates an image through an C<angle> between -90 and + 90
degrees. Uses/doesn't use antialiasing depending on the C<aa> flag.
Pixels outside the rotated image are set to C<bg>.

Code modified from pnmrotate (Copyright Jef Poskanzer) with an algorithm based
on "A Fast Algorithm for General  Raster  Rotation"  by  Alan Paeth,
Graphics Interface '86, pp. 77-81.

Use the C<rotnewsz> function to find out about the dimension of the
newly created image

  ($newcols,$newrows) = rotnewsz $oldn, $oldm, $angle;

L<PDL::Transform|PDL::Transform> offers a more general interface to 
distortions, including rotation, with various types of sampling; but 
rot2d is faster.



=for bad

rot2d ignores the bad-value flag of the input piddles.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






*rot2d = \&PDL::rot2d;




=head2 bilin2d

=for sig

  Signature: (I(n,m); O(q,p))

=for ref

Bilinearly maps the first piddle in the second. The
interpolated values are actually added to the second
piddle which is supposed to be larger than the first one.



=for bad

bilin2d ignores the bad-value flag of the input piddles.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






*bilin2d = \&PDL::bilin2d;




=head2 rescale2d

=for sig

  Signature: (I(m,n); O(p,q))

=for ref

The first piddle is rescaled to the dimensions of the second
(expanding or meaning values as needed) and then added to it in place.
Nothing useful is returned.

If you want photometric accuracy or automatic FITS header metadata
tracking, consider using L<PDL::Transform::map|PDL::Transform/map>
instead: it does these things, at some speed penalty compared to 
rescale2d.



=for bad

rescale2d ignores the bad-value flag of the input piddles.
It will set the bad-value flag of all output piddles if the flag is set for any of the input piddles.


=cut






*rescale2d = \&PDL::rescale2d;




=head2 fitwarp2d

=for ref

Find the best-fit 2D polynomial to describe
a coordinate transformation.

=for usage

  ( $px, $py ) = fitwarp2d( $x, $y, $u, $v, $nf. { options } )

Given a set of points in the output plane (C<$u,$v>), find
the best-fit (using singular-value decomposition) 2D polynomial 
to describe the mapping back to the image plane (C<$x,$y>).
The order of the fit is controlled by the C<$nf> parameter
(the maximum power of the polynomial is C<$nf - 1>), and you
can restrict the terms to fit using the C<FIT> option.

C<$px> and C<$py> are C<np> by C<np> element piddles which describe
a polynomial mapping (of order C<np-1>) 
from the I<output> C<(u,v)> image to the I<input> C<(x,y)> image:

  x = sum(j=0,np-1) sum(i=0,np-1) px(i,j) * u^i * v^j
  y = sum(j=0,np-1) sum(i=0,np-1) py(i,j) * u^i * v^j

The transformation is returned for the reverse direction (ie
output to input image) since that is what is required by the
L<warp2d()|/warp2d> routine.  The L<applywarp2d()|/applywarp2d>
routine can be used to convert a set of C<$u,$v> points given
C<$px> and C<$py>.

Options:

=for options

  FIT     - which terms to fit? default ones(byte,$nf,$nf)
  THRESH  - in svd, remove terms smaller than THRESH * max value
            default is 1.0e-5

=over 4

=item FIT

C<FIT> allows you to restrict which terms of the polynomial to fit:
only those terms for which the FIT piddle evaluates to true will be
evaluated.  If a 2D piddle is sent in, then it is
used for the x and y polynomials; otherwise 
C<$fit-E<gt>slice(":,:,(0)")> will be used for C<$px> and
C<$fit-E<gt>slice(":,:,(1)")> will be used for C<$py>.

=item THRESH

Remove all singular values whose valus is less than C<THRESH>
times the largest singular value.

=back

The number of points must be at least equal to the number of
terms to fit (C<$nf*$nf> points for the default value of C<FIT>).

=for example

  # points in original image
  $x = pdl( 0,   0, 100, 100 );
  $y = pdl( 0, 100, 100,   0 );
  # get warped to these positions
  $u = pdl( 10, 10, 90, 90 );
  $v = pdl( 10, 90, 90, 10 );
  # 
  # shift of origin + scale x/y axis only
  $fit = byte( [ [1,1], [0,0] ], [ [1,0], [1,0] ] );
  ( $px, $py ) = fitwarp2d( $x, $y, $u, $v, 2, { FIT => $fit } );
  print "px = ${px}py = $py";
  px = 
  [
   [-12.5  1.25]
   [    0     0]
  ]
  py = 
  [
   [-12.5     0]
   [ 1.25     0]
  ]
  #
  # Compared to allowing all 4 terms
  ( $px, $py ) = fitwarp2d( $x, $y, $u, $v, 2 );
  print "px = ${px}py = $py";
  px = 
  [
   [         -12.5           1.25]
   [  1.110223e-16 -1.1275703e-17]
  ]
  py = 
  [
   [         -12.5  1.6653345e-16]
   [          1.25 -5.8546917e-18]
  ]

=head2 applywarp2d

=for ref

Transform a set of points using a 2-D polynomial mapping

=for usage

  ( $x, $y ) = applywarp2d( $px, $py, $u, $v )

Convert a set of points (stored in 1D piddles C<$u,$v>)
to C<$x,$y> using the 2-D polynomial with coefficients stored in C<$px>
and C<$py>.  See L<fitwarp2d()|/fitwarp2d>
for more information on the format of C<$px> and C<$py>.

=cut

# use SVD to fit data. Assuming no errors.
sub _svd ($$$) {
    my $basis  = shift;
    my $y      = shift;
    my $thresh = shift;

    # if we had errors for these points, would normalise the
    # basis functions, and the output array, by these errors here

    # perform the SVD
    my ( $svd_u, $svd_w, $svd_v ) = svd( $basis );

    # remove any singular values
    $svd_w *= ( $svd_w >= ($svd_w->max * $thresh ) );

    # perform the back substitution
    #
    my $tmp = $y x $svd_u;
    if ( $PDL::Bad::Status ) {
	$tmp /= $svd_w->setvaltobad(0.0);
	$tmp->inplace->setbadtoval(0.0);
    } else {
	# not checked
	my $mask = ($svd_w == 0.0);
	$tmp /= ( $svd_w + $mask );
	$tmp *= ( 1 - $mask );
    }

    my $ans = sumover( $svd_v * $tmp );

    return $ans;

} # sub: _svd()

sub _mkbasis ($$$$) {
    my $fit    = shift;
    my $npts   = shift;
    my $u      = shift;
    my $v      = shift;

    my $n      = $fit->getdim(0) - 1;
    my $ncoeff = sum( $fit );

    my $basis = zeroes( $u->type, $ncoeff, $npts );
    my $k = 0;
    foreach my $j ( 0 .. $n ) {
	my $tmp_v = $v**$j;
	foreach my $i ( 0 .. $n ) {
	    if ( $fit->at($i,$j) ) {
		my $tmp = $basis->slice("($k),:");
		$tmp .= $tmp_v * $u**$i;
		$k++;
	    }
	}
    }
    return $basis;

} # sub: _mkbasis()

sub PDL::fitwarp2d {
    croak "Usage: (\$px,\$py) = fitwarp2d(x(m);y(m);u(m);v(m);\$nf; { options })"
	if $#_ < 4 or ( $#_ >= 5 and ref($_[5]) ne "HASH" );

    my $x  = shift;
    my $y  = shift;
    my $u  = shift;
    my $v  = shift;
    my $nf = shift;

    my $opts = PDL::Options->new( { FIT => ones(byte,$nf,$nf), THRESH => 1.0e-5 } );
    $opts->options( $_[0] ) if $#_ > -1;
    my $oref = $opts->current();

    # safety checks
    my $npts = $x->nelem;
    croak "fitwarp2d: x, y, u, and v must be the same size (and 1D)"
	unless $npts == $y->nelem and $npts == $u->nelem and $npts == $v->nelem
	    and $x->getndims == 1 and $y->getndims == 1 and $u->getndims == 1 and $v->getndims == 1;

    my $svd_thresh = $$oref{THRESH};
    croak "fitwarp2d: THRESH option must be >= 0."
	if $svd_thresh < 0;

    my $fit = $$oref{FIT};
    my $fit_ndim = $fit->getndims();
    croak "fitwarp2d: FIT option must be sent a (\$nf,\$nf[,2]) element piddle"
	unless UNIVERSAL::isa($fit,"PDL") and 
	    ($fit_ndim == 2 or ($fit_ndim == 3 and $fit->getdim(2) == 2)) and
	    $fit->getdim(0) == $nf and $fit->getdim(1) == $nf;

    # how many coeffs to fit (first we ensure $fit is either 0 or 1)
    $fit = convert( $fit != 0, byte );

    my ( $fitx, $fity, $ncoeffx, $ncoeffy, $ncoeff );
    if ( $fit_ndim == 2 ) {
	$fitx = $fit;
	$fity = $fit;
	$ncoeff = $ncoeffx = $ncoeffy = sum( $fit );
    } else {
	$fitx = $fit->slice(",,(0)");
	$fity = $fit->slice(",,(1)");
	$ncoeffx = sum($fitx);
	$ncoeffy = sum($fity);
	$ncoeff = $ncoeffx > $ncoeffy ? $ncoeffx : $ncoeffy;
    }

    croak "fitwarp2d: number of points must be >= \$ncoeff"
	unless $npts >= $ncoeff;

    # create the basis functions for the SVD fitting
    my ( $basisx, $basisy );
    $basisx = _mkbasis( $fitx, $npts, $u, $v );
    if ( $fit_ndim == 2 ) {
	$basisy = $basisx;
    } else {
	$basisy = _mkbasis( $fity, $npts, $u, $v );
    }

    my $px = _svd( $basisx, $x, $svd_thresh );
    my $py = _svd( $basisy, $y, $svd_thresh );

    # convert into $nf x $nf element piddles, if necessary
    my $nf2 = $nf * $nf;

    return ( $px->reshape($nf,$nf), $py->reshape($nf,$nf) )
	if $ncoeff == $nf2 and $ncoeffx == $ncoeffy;

    # re-create the matrix
    my $xtmp = zeroes( $nf, $nf );
    my $ytmp = zeroes( $nf, $nf );
    
    my $kx = 0;
    my $ky = 0;
    foreach my $i ( 0 .. ($nf - 1) ) {
	foreach my $j ( 0 .. ($nf - 1) ) {
	    if ( $fitx->at($i,$j) ) { 
		$xtmp->set($i,$j, $px->at($kx) );
		$kx++;
	    }
	    if ( $fity->at($i,$j) ) { 
		$ytmp->set($i,$j, $py->at($ky) );
		$ky++;
	    }
	}
    }

    return ( $xtmp, $ytmp )

} # sub: fitwarp2d

*fitwarp2d = \&PDL::fitwarp2d;

sub PDL::applywarp2d {
    # checks
    croak "Usage: (\$x,\$y) = applywarp2d(px(nf,nf);py(nf,nf);u(m);v(m);)"
	if $#_ != 3;

    my $px = shift;
    my $py = shift;
    my $u  = shift;
    my $v  = shift;
    my $npts = $u->nelem;

    # safety check
    croak "applywarp2d: u and v must be the same size (and 1D)"
	unless $npts == $u->nelem and $npts == $v->nelem 
	    and $u->getndims == 1 and $v->getndims == 1;

    my $nf  = $px->getdim(0);
    my $nf2 = $nf * $nf;

    # could remove terms with 0 coeff here
    # (would also have to remove them from px/py for
    #  the matrix multiplication below)
    #
    my $mat = _mkbasis( ones(byte,$nf,$nf), $npts, $u, $v );
    
    my $x = reshape( $mat x $px->clump(-1)->transpose(), $npts );
    my $y = reshape( $mat x $py->clump(-1)->transpose(), $npts );
    return ( $x, $y );

} # sub: applywarp2d

*applywarp2d = \&PDL::applywarp2d;




=head2 warp2d

=for sig

  Signature: (img(m,n); double px(np,np); double py(np,np); [o] warp(m,n); { options })

=for ref

Warp a 2D image given a polynomial describing the I<reverse> mapping.

=for usage

  $out = warp2d( $img, $px, $py, { options } );

Apply the polynomial transformation encoded in the C<$px> and
C<$py> piddles to warp the input image C<$img> into the output
image C<$out>.

The format for the polynomial transformation is described in
the documentation for the L<fitwarp2d()|/fitwarp2d> routine.

At each point C<x,y>, the closest 16 pixel values are combined
with an interpolation kernel to calculate the value at C<u,v>.
The interpolation is therefore done in the image, rather than
Fourier, domain.
By default, a C<tanh> kernel is used, but this can be changed
using the C<KERNEL> option discussed below
(the choice of kernel depends on the frequency content of the input image).

The routine is based on the C<warping> command from
the Eclipse data-reduction package - see http://www.eso.org/eclipse/ - and
for further details on image resampling see
Wolberg, G., "Digital Image Warping", 1990, IEEE Computer
Society Press ISBN 0-8186-8944-7).

Currently the output image is the same size as the input one,
which means data will be lost if the transformation reduces
the pixel scale.  This will (hopefully) be changed soon.

=for example

  $img = rvals(byte,501,501);
  imag $img, { JUSTIFY => 1 };
  # 
  # use a not-particularly-obvious transformation:
  #   x = -10 + 0.5 * $u - 0.1 * $v 
  #   y = -20 + $v - 0.002 * $u * $v
  #
  $px  = pdl( [ -10, 0.5 ], [ -0.1, 0 ] );
  $py  = pdl( [ -20, 0 ], [ 1, 0.002 ] );
  $wrp = warp2d( $img, $px, $py );
  #
  # see the warped image
  imag $warp, { JUSTIFY => 1 };

The options are:

=for options

  KERNEL - default value is tanh
  NOVAL  - default value is 0

C<KERNEL> is used to specify which interpolation kernel to use
(to see what these kernels look like, use the
L<warp2d_kernel()|/warp2d_kernel> routine).
The options are:

=over 4

=item tanh

Hyperbolic tangent: the approximation of an ideal box filter by the
product of symmetric tanh functions.

=item sinc

For a correctly sampled signal, the ideal filter in the fourier domain is a rectangle,
which produces a C<sinc> interpolation kernel in the spatial domain:

  sinc(x) = sin(pi * x) / (pi * x)

However, it is not ideal for the C<4x4> pixel region used here.

=item sinc2

This is the square of the sinc function.

=item lanczos

Although defined differently to the C<tanh> kernel, the result is very
similar in the spatial domain.  The Lanczos function is defined as

  L(x) = sinc(x) * sinc(x/2)  if abs(x) < 2
       = 0                       otherwise

=item hann

This kernel is derived from the following function:

  H(x) = a + (1-a) * cos(2*pi*x/(N-1))  if abs(x) < 0.5*(N-1)
       = 0                                 otherwise

with C<a = 0.5> and N currently equal to 2001.

=item hamming

This kernel uses the same C<H(x)> as the Hann filter, but with
C<a = 0.54>.

=back

C<NOVAL> gives the value used to indicate that a pixel in the
output image does not map onto one in the input image.

=cut

# support routine
{ 
    my %warp2d = map { ($_,1) } qw( tanh sinc sinc2 lanczos hamming hann );
 
    # note: convert to lower case
    sub _check_kernel ($$) {
	my $kernel = lc shift;
	my $code   = shift;
	barf "Unknown kernel $kernel sent to $code\n" . 
	    "\tmust be one of [" . join(',',keys %warp2d) . "]\n"
		unless exists $warp2d{$kernel};
	return $kernel;
    }
}




        
sub PDL::warp2d {
    my $opts = PDL::Options->new( { KERNEL => "tanh", NOVAL => 0 } );
    $opts->options( pop(@_) ) if ref($_[$#_]) eq "HASH";

    die "Usage: warp2d( in(m,n), px(np,np); py(np,np); [o] out(m,n), {Options} )"
	if $#_<2 || $#_>3;
    my $img = shift;
    my $px  = shift;
    my $py  = shift;
    my $out = $#_ == -1 ? PDL->null() : shift;

    # safety checks
    my $copt   = $opts->current();
    my $kernel = _check_kernel( $$copt{KERNEL}, "warp2d" );

    &PDL::_warp2d_int( $img, $px, $py, $out, $kernel, $$copt{NOVAL} );
    return $out;
}



*warp2d = \&PDL::warp2d;




=head2 warp2d_kernel

=for ref

Return the specified kernel, as used by L<warp2d|/warp2d>

=for usage

  ( $x, $k ) = warp2d_kernel( $name )

The valid values for C<$name> are the same as the C<KERNEL> option
of L<warp2d()|/warp2d>.

=for example

  line warp2d_kernel( "hamming" );

=cut





sub PDL::warp2d_kernel ($) {
    my $kernel = _check_kernel( shift, "warp2d_kernel" );

    my $nelem = _get_kernel_size();
    my $x     = zeroes( $nelem );
    my $k     = zeroes( $nelem );

    &PDL::_warp2d_kernel_int( $x, $k, $kernel );
    return ( $x, $k );

#    return _get_kernel( $kernel );
}
*warp2d_kernel = \&PDL::warp2d_kernel;



*warp2d_kernel = \&PDL::warp2d_kernel;


;


=head1 AUTHORS

Copyright (C) Karl Glazebrook 1997 with additions by Robin Williams
(rjrw@ast.leeds.ac.uk), Tim Jeness (timj@jach.hawaii.edu),
and Doug Burke (burke@ifa.hawaii.edu).

All rights reserved. There is no warranty. You are allowed
to redistribute this software / documentation under certain
conditions. For details, see the file COPYING in the PDL
distribution. If this file is separated from the PDL distribution,
the copyright notice should be included in the file.

=cut





# Exit with OK status

1;