-
Notifications
You must be signed in to change notification settings - Fork 10
/
georeference_airport_diagrams_via_db.pl
executable file
·2540 lines (2036 loc) · 88.4 KB
/
georeference_airport_diagrams_via_db.pl
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
#!/usr/bin/perl
# A utility to automatically georeference FAA airport diagrams
# Copyright (C) 2013 Jesse McGraw (jlmcgraw@gmail.com)
#
#-------------------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
#-------------------------------------------------------------------------------
#Unavoidable problems:
#-----------------------------------
# Relies on actual text being in PDF. It seems that most, if not all, military
# plates have no text in them
# We may be able to get around this with tesseract OCR but that will take some work
#
# Known issues:
#---------------------
use 5.010;
use strict;
use warnings;
# Standard libraries
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
use File::Basename;
use Getopt::Std;
use Carp;
use Math::Trig;
use Math::Trig qw(great_circle_distance deg2rad great_circle_direction rad2deg);
use File::Slurp;
use POSIX;
# Allow use of locally installed libraries in conjunction with Carton
use FindBin '$Bin';
use lib "$FindBin::Bin/local/lib/perl5";
use lib $FindBin::Bin;
# Non-standard libraries
use PDF::API2;
use DBI;
use Image::Magick;
use Math::Round;
# use Math::Round;
use Time::HiRes q/gettimeofday/;
# PDF constants
use constant mm => 25.4 / 72;
use constant in => 1 / 72;
use constant pt => 1;
# Some subroutines
use GeoReferencePlatesSubroutines;
# Some other constants
#-------------------------------------------------------------------------------
# Max allowed radius in PDF points from an icon (obstacle, fix, gps) to its
# associated textbox's center
our $maxDistanceFromObstacleIconToTextBox = 20;
# DPI of the output PNG
our $pngDpi = 300;
# A hash to collect statistics
our %statistics = ();
use vars qw/ %opt /;
# Define the valid command line options
my $opt_string = 'nspva:c:i:';
my $arg_num = scalar @ARGV;
# We need at least one argument (the name of the PDF to process)
if ( $arg_num < 1 ) {
usage();
exit(1);
}
# This will fail if we receive an invalid option
unless ( getopts( "$opt_string", \%opt ) ) {
usage();
exit(1);
}
# Get the target PDF file from command line options
our ($dtppDirectory) = $ARGV[0];
if ( !-e ($dtppDirectory) ) {
say "Target dTpp directory $dtppDirectory doesn't exist";
exit(1);
}
# Default to all airports for the SQL query
our $airportId = "%";
if ( $opt{a} ) {
#If something provided on the command line use it instead
$airportId = $opt{a};
say "Supplied airport ID: $airportId";
}
# Default to all states for the SQL query
our $stateId = "%";
if ( $opt{i} ) {
# If something provided on the command line use it instead
$stateId = $opt{i};
say "Supplied state ID: $stateId";
}
# Which cycle to process
my $cycle;
if ( $opt{c} ) {
# If something provided on the command line use it instead
$cycle = $opt{c};
say "Supplied cycle: $cycle";
}
our $shouldNotOverwriteVrt = $opt{n};
our $shouldOutputStatistics = $opt{s};
our $shouldSaveMarkedPdf = $opt{p};
our $debug = $opt{v};
# database of metadata for dtpp
# Created by load_dtpp_metadata.pl
my $dtppDbh = DBI->connect( "dbi:SQLite:dbname=./dtpp-$cycle.sqlite",
"", "", { RaiseError => 1 } )
or croak $DBI::errstr;
#-----------------------------------------------
# Open the nasr database
# created by parse_nasr project
our $dbh;
my $sth;
$dbh =
DBI->connect( "dbi:SQLite:dbname=nasr.sqlite", "", "", { RaiseError => 1 } )
or croak $DBI::errstr;
our (
$TPP_VOLUME, $FAA_CODE, $CHART_SEQ, $CHART_CODE,
$CHART_NAME, $USER_ACTION, $PDF_NAME, $FAANFD18_CODE,
$MILITARY_USE, $COPTER_USE, $STATE_ID
);
$dtppDbh->do("PRAGMA page_size=4096");
$dtppDbh->do("PRAGMA synchronous=OFF");
# Query the dtpp database for charts
my $dtppSth = $dtppDbh->prepare(
"SELECT TPP_VOLUME, FAA_CODE, CHART_SEQ, CHART_CODE, CHART_NAME, USER_ACTION, PDF_NAME, FAANFD18_CODE, MILITARY_USE, COPTER_USE, STATE_ID
FROM dtpp
WHERE
CHART_CODE = 'APD'
AND
FAA_CODE LIKE '$airportId'
AND
STATE_ID LIKE '$stateId'
"
);
$dtppSth->execute();
my $_allSqlQueryResults = $dtppSth->fetchall_arrayref();
my $_rows = $dtppSth->rows;
say "Processing $_rows charts";
my $completedCount = 0;
our $successCount = 0;
our $failCount = 0;
our $noTextCount = 0;
our $noPointsCount = 0;
foreach my $_row (@$_allSqlQueryResults) {
(
$TPP_VOLUME, $FAA_CODE, $CHART_SEQ, $CHART_CODE,
$CHART_NAME, $USER_ACTION, $PDF_NAME, $FAANFD18_CODE,
$MILITARY_USE, $COPTER_USE, $STATE_ID
) = @$_row;
# say '$TPP_VOLUME, $FAA_CODE, $CHART_SEQ, $CHART_CODE, $CHART_NAME, $USER_ACTION, $PDF_NAME, $FAANFD18_CODE, $MILITARY_USE, $COPTER_USE, $STATE_ID';
say
"$TPP_VOLUME, $FAA_CODE, $CHART_SEQ, $CHART_CODE, $CHART_NAME, $USER_ACTION, $PDF_NAME, $FAANFD18_CODE, $MILITARY_USE, $COPTER_USE, $STATE_ID";
# say "$FAA_CODE";
process_one_plate();
++$completedCount;
say
"Success: $successCount, Fail: $failCount, No Text: $noTextCount, No Points: $noPointsCount, Chart: $completedCount"
. "/"
. "$_rows";
}
# Close the charts database
$dtppSth->finish();
$dtppDbh->disconnect();
# Close the locations database
# $sth->finish();
$dbh->disconnect();
exit;
#-------------------------------------------------------------------------------
sub process_one_plate {
# Zero out the stats hash
%statistics = (
'$airportLatitude' => "0",
'$horizontalAndVerticalLinesCount' => "0",
'$gcpCount' => "0",
'$yMedian' => "0",
'$gpsCount' => "0",
'$targetPdf' => "0",
'$yScaleAvgSize' => "0",
'$airportLongitude' => "0",
'$notToScaleIndicatorCount' => "0",
'$unique_obstacles_from_dbCount' => "0",
'$xScaleAvgSize' => "0",
'$navaidCount' => "0",
'$xMedian' => "0",
'$insetCircleCount' => "0",
'$obstacleCount' => "0",
'$insetBoxCount' => "0",
'$fixCount' => "0",
'$yAvg' => "0",
'$xAvg' => "0",
'$pdftotext' => "0",
'$lonLatRatio' => "0",
'$upperLeftLon' => "0",
'$upperLeftLat' => "0",
'$lowerRightLon' => "0",
'$lowerRightLat' => "0",
'$targetLonLatRatio' => "0",
'$runwayIconsCount' => "0",
'isPortraitOrientation' => "0",
'$xPixelSkew' => "0",
'$yPixelSkew' => "0",
'$status' => "0"
);
#
our $targetPdf = $dtppDirectory . $PDF_NAME;
my $retval;
# Say what our input PDF is
say $targetPdf;
# Pull out the various filename components of the input file from the command line
our ( $filename, $dir, $ext ) = fileparse( $targetPdf, qr/\.[^.]*/x );
$airportId = $FAA_CODE;
# Set some output file names based on the input filename
our $outputPdf = $dir . "marked-" . $filename . ".pdf";
our $outputPdfOutlines = $dir . "outlines-" . $filename . ".pdf";
our $outputPdfRaw = $dir . "raw-" . $filename . ".txt";
our $targetpng = $dir . $filename . ".png";
our $gcpPng = $dir . "gcp-" . $filename . ".png";
our $targettif = $dir . $filename . ".tif";
# our $targetvrt = $dir . $filename . ".vrt";
our $targetVrtFile =
$STATE_ID . "-" . $FAA_CODE . "-" . $PDF_NAME . "-" . $CHART_NAME;
# convert spaces, ., and slashes to dash
$targetVrtFile =~ s/[ \s | \/ | \\ | \. ]/-/xg;
our $targetVrtFile2 = "warped" . $targetVrtFile;
our $targetVrtBadRatio = $dir . "badRatio-" . $targetVrtFile . ".vrt";
our $noPointsFile = $dir . "noPoints-" . $targetVrtFile . ".vrt";
our $failFile = $dir . "fail-" . $targetVrtFile . ".vrt";
our $noTextFile =
$dir . $MILITARY_USE . "noText-" . $targetVrtFile . ".vrt";
our $targetvrt = $dir . $targetVrtFile . ".vrt";
our $targetvrt2 = $dir . $targetVrtFile2 . ".vrt";
our $targetStatistics = "./statistics.csv";
if ($debug) {
say "Directory: " . $dir;
say "File: " . $filename;
say "Suffix: " . $ext;
say "";
say "TargetPdf: $targetPdf";
say "OutputPdf: $outputPdf";
say "TargetPng: $targetpng";
say "TargetTif: $targettif";
say "TargetVrt: $targetvrt";
say "targetStatistics: $targetStatistics";
say "";
}
$statistics{'$targetPdf'} = $targetPdf;
# This is a quick hack to abort if we've already created a .vrt for this plate
if ( $shouldNotOverwriteVrt && -e $targetvrt ) {
say "$targetvrt exists, exiting";
return (1);
}
# Default is portait orientation
our $isPortraitOrientation = 1;
# Pull all text out of the PDF
my @pdftotext;
@pdftotext = qx(pdftotext $targetPdf -enc ASCII7 -);
$retval = $? >> 8;
if ( @pdftotext eq "" || $retval != 0 ) {
say
"No output from pdftotext. Is it installed? Return code was $retval";
return (1);
}
$statistics{'$pdftotext'} = scalar(@pdftotext);
if ( scalar(@pdftotext) < 5 ) {
++$main::noTextCount;
say "Not enough pdftotext output for $targetPdf";
$statistics{'$status'} = "AUTOBAD";
writeStatistics() if $shouldOutputStatistics;
touchFile($main::noTextFile);
# say "Touching $main::noTextFile";
# open( my $fh, ">", "$main::noTextFile" )
# or die "cannot open > $main::noTextFile $!";
# close($fh);
# return;
return (1);
}
# Pull airport location from chart text or, if a name was supplied on command line, from database
our ( $airportLatitudeDec, $airportLongitudeDec ) =
findAirportLatitudeAndLongitude();
our $airportLatitudeDegrees = floor($airportLatitudeDec);
our $airportLongitudeDegrees = floor($airportLongitudeDec);
our $airportLatitudeDeclination = $airportLatitudeDec < 0 ? "S" : "N";
our $airportLongitudeDeclination = $airportLongitudeDec < 0 ? "W" : "E";
$airportLatitudeDegrees = abs($airportLatitudeDegrees);
$airportLongitudeDegrees = abs($airportLongitudeDegrees);
if ($debug) {
say
"$airportLatitudeDegrees $airportLatitudeDeclination, $airportLongitudeDegrees $airportLongitudeDeclination";
}
# Get the mediabox size and other variables from the PDF
our ( $pdfXSize, $pdfYSize, $pdfCenterX, $pdfCenterY, $pdfXYRatio ) =
getMediaboxSize();
# Convert the PDF to a PNG if one doesn't already exist
convertPdfToPng();
# Get PNG dimensions and the PDF->PNG scale factors
our ( $pngXSize, $pngYSize, $scaleFactorX, $scaleFactorY, $pngXYRatio ) =
getPngSize();
#---------------------------------------------------------------------------
# Some regex building blocks to be used elsewhere
# numbers that start with 1-9 followed by 2 or more digits
our $obstacleHeightRegex = qr/[1-9]\d{1,}/x;
# A number with possible decimal point and minus sign
our $numberRegex = qr/[-\.\d]+/x;
our $latitudeRegex = qr/$numberRegex’[N|S]/x;
our $longitudeRegex = qr/$numberRegex’[E|W]/x;
# A transform, capturing the X and Y
our ($transformCaptureXYRegex) =
qr/q\s1\s0\s0\s1\s+($numberRegex)\s+($numberRegex)\s+cm/x;
# A transform, not capturing the X and Y
our ($transformNoCaptureXYRegex) =
qr/q\s1\s0\s0\s1\s+$numberRegex\s+$numberRegex\s+cm/x;
# A bezier curve
our ($bezierCurveRegex) = qr/(?:$numberRegex\s+){6}c/x;
# A line or path
our ($lineRegex) = qr/ $numberRegex \s+ $numberRegex \s+ l/x;
our ($lineRegexCaptureXY) = qr/ ($numberRegex) \s+ ($numberRegex) \s+ l/x;
# my $bezierCurveRegex = qr/(?:$numberRegex\s){6}c/;
# my $lineRegex = qr/$numberRegex\s$numberRegex\sl/;
# Move to the origin
our ($originRegex) = qr/0 \s+ 0 \s+ m/x;
#F* Fill path
#S Stroke path
#cm Scale and translate coordinate space
#c Bezier curve
#q Save graphics state
#Q Restore graphics state
our %latitudeAndLongitudeLines = ();
# Get number of objects/streams in the targetpdf
our $objectstreams = getNumberOfStreams();
our @pdfToTextBbox = ();
our %latitudeTextBoxes = ();
our %longitudeTextBoxes = ();
# Loop through each of the streams in the PDF and find all of the icons we're interested in
findAllIcons();
# Loop through each of the streams in the PDF and find all of the textboxes we're interested in
findAllTextboxes();
#---------------------------------------------------------------------------
# Modify the PDF
# Don't do anything PDF related unless we've asked to create one on the command line
our ( $pdf, $page );
if ($shouldSaveMarkedPdf) {
$pdf = PDF::API2->open($targetPdf);
#Set up the various types of boxes to draw on the output PDF
$page = $pdf->openpage(1);
}
#---------------------------------------------------
# Convert the outlines PDF to a PNG
our ( $image, $perlMagickStatus );
# Draw boxes around the icons and textboxes we've found so far
outlineEverythingWeFound() if $shouldSaveMarkedPdf;
our %gcps = ();
my $latitudeLineOrientation = "horizontal";
my $longitudeLineOrientation = "vertical";
# The orientation is being determined within the textbox finding routines for now
if ( !$isPortraitOrientation ) {
say "Setting orientation to landscape";
$latitudeLineOrientation = "vertical";
$longitudeLineOrientation = "horizontal";
}
#---------------------------------------------------------------------------
# Everything to do with latitude
# Match a line to a textbox
findClosestLineToTextBox( \%latitudeTextBoxes, \%latitudeAndLongitudeLines,
$latitudeLineOrientation );
if ($debug) {
say "latitudeTextBoxes";
# print Dumper ( \%latitudeAndLongitudeLines );
print Dumper ( \%latitudeTextBoxes );
}
# Draw a line between the two
if ($shouldSaveMarkedPdf) {
drawLineFromEachIconToMatchedTextBox( \%latitudeTextBoxes,
\%latitudeAndLongitudeLines );
}
#---------------------------------------------------------------------------
# Everything to do with longitude
# Match a line to a textbox
findClosestLineToTextBox( \%longitudeTextBoxes,
\%latitudeAndLongitudeLines, $longitudeLineOrientation );
if ($debug) {
say "longitudeTextBoxes";
# print Dumper ( \%latitudeAndLongitudeLines );
print Dumper ( \%longitudeTextBoxes );
}
# Draw a line between the two
if ($shouldSaveMarkedPdf) {
drawLineFromEachIconToMatchedTextBox( \%longitudeTextBoxes,
\%latitudeAndLongitudeLines );
}
# Find the points where all of our lines intersect, use those as GCPs
findIntersectionOfLatLonLines( \%latitudeTextBoxes, \%longitudeTextBoxes,
\%latitudeAndLongitudeLines );
# Build the GCP portion of the command line parameters
our $gcpstring = createGcpString();
# Outline the GCP points we ended up using
drawCircleAroundGCPs() if $shouldSaveMarkedPdf;
# Make sure we have enough GCPs
my $gcpCount = scalar( keys(%gcps) );
say "Found $gcpCount potential Ground Control Points" if $debug;
# Save statistics
$statistics{'$gcpCount'} = $gcpCount;
if ($shouldSaveMarkedPdf) {
$pdf->saveas($outputPdf);
}
# Can't do anything if we didn't find any valid ground control points
if ( $gcpCount < 2 ) {
say
"Only found $gcpCount ground control points in $targetPdf, can't georeference";
touchFile($noPointsFile);
++$main::noPointsCount;
$statistics{'$status'} = "AUTOBAD";
writeStatistics() if $shouldOutputStatistics;
return (1);
}
# Actually produce the georeferencing data via GDAL
georeferenceTheRaster();
# Write out the statistics of this file if requested
writeStatistics() if $shouldOutputStatistics;
# Since we've calculated our extents, try drawing some features on the outputPdf to see if they align
# With our work
# drawFeaturesOnPdf() if $shouldSaveMarkedPdf;
return;
}
# SUBROUTINES
#-------------------------------------------------------------------------------
sub findAirportLatitudeAndLongitude {
#Get the lat/lon of the airport for the plate we're working on
my $_airportLatitudeDec = "";
my $_airportLongitudeDec = "";
if ( $_airportLongitudeDec eq "" or $_airportLatitudeDec eq "" ) {
#We didn't get any airport info from the PDF, let's check the database
#Get airport from database
if ( !$airportId ) {
say
"You must specify an airport ID (eg. -a SMF) since there was no info found in $main::targetPdf";
return (1);
}
# Query the database for airport
my $sth = $dbh->prepare(
"SELECT location_identifier, apt_latitude, apt_longitude, official_facility_name FROM APT_APT WHERE location_identifier = '$airportId'"
);
$sth->execute();
my $_allSqlQueryResults = $sth->fetchall_arrayref();
foreach my $_row (@$_allSqlQueryResults) {
my ( $airportFaaId, $airportname );
(
$airportFaaId, $_airportLatitudeDec, $_airportLongitudeDec,
$airportname
) = @$_row;
if ($debug) {
say "Airport ID: $airportFaaId";
say "Airport Latitude: $_airportLatitudeDec";
say "Airport Longitude: $_airportLongitudeDec";
say "Airport Name: $airportname";
}
}
if ( $_airportLongitudeDec eq "" or $_airportLatitudeDec eq "" ) {
say
"No airport coordinate information found for $airportId in $main::targetPdf or database";
return (1);
}
}
# Save statistics
$statistics{'$airportLatitude'} = $_airportLatitudeDec;
$statistics{'$airportLongitude'} = $_airportLongitudeDec;
return ( $_airportLatitudeDec, $_airportLongitudeDec );
}
sub getMediaboxSize {
#Get the mediabox size from the PDF
my $mutoolinfo = qx(mutool info $main::targetPdf);
my $retval = $? >> 8;
die "No output from mutool info. Is it installed? Return code was $retval"
if ( $mutoolinfo eq "" || $retval != 0 );
foreach my $line ( split /[\r\n]+/, $mutoolinfo ) {
## Regular expression magic to grab what you want
if ( $line =~ /([-\.0-9]+) ([-\.0-9]+) ([-\.0-9]+) ([-\.0-9]+)/ ) {
my $_pdfXSize = $3 - $1;
my $_pdfYSize = $4 - $2;
my $_pdfCenterX = $_pdfXSize / 2;
my $_pdfCenterY = $_pdfYSize / 2;
my $_pdfXYRatio = $_pdfXSize / $_pdfYSize;
if ($debug) {
say "PDF Mediabox size: " . $_pdfXSize . "x" . $_pdfYSize;
say "PDF Mediabox center: " . $_pdfCenterX . "x" . $_pdfCenterY;
say "PDF X/Y Ratio: " . $_pdfXYRatio;
}
return (
$_pdfXSize, $_pdfYSize, $_pdfCenterX,
$_pdfCenterY, $_pdfXYRatio
);
}
}
return;
}
sub getPngSize {
#Calculate the raster size ourselves
my $_pngXSize = ceil( ( $main::pdfXSize / 72 ) * $pngDpi );
my $_pngYSize = ceil( ( $main::pdfYSize / 72 ) * $pngDpi );
#This calls the file utility to determine raster size
# #Find the dimensions of the PNG
# my $fileoutput = qx(file $targetpng );
# my $_retval = $? >> 8;
# die "No output from file. Is it installed? Return code was $_retval"
# if ( $fileoutput eq "" || $_retval != 0 );
# foreach my $line ( split /[\r\n]+/, $fileoutput ) {
# ## Regular expression magic to grab what you want
# if ( $line =~ /([-\.0-9]+)\s+x\s+([-\.0-9]+)/ ) {
# $_pngXSize = $1;
# $_pngYSize = $2;
# }
# }
#Calculate the ratios of the PNG/PDF coordinates
my $_scaleFactorX = $_pngXSize / $main::pdfXSize;
my $_scaleFactorY = $_pngYSize / $main::pdfYSize;
my $_pngXYRatio = $_pngXSize / $_pngYSize;
if ($debug) {
say "PNG size: " . $_pngXSize . "x" . $_pngYSize;
say "Scalefactor PDF->PNG X: " . $_scaleFactorX;
say "Scalefactor PDF->PNG Y: " . $_scaleFactorY;
say "PNG X/Y Ratio: " . $_pngXYRatio;
}
return ( $_pngXSize, $_pngYSize, $_scaleFactorX, $_scaleFactorY,
$_pngXYRatio );
}
sub getNumberOfStreams {
#Get number of objects/streams in the targetpdf
my $_mutoolShowOutput = qx(mutool show $main::targetPdf x);
my $retval = $? >> 8;
die "No output from mutool show. Is it installed? Return code was $retval"
if ( $_mutoolShowOutput eq "" || $retval != 0 );
my $_objectstreams;
foreach my $line ( split /[\r\n]+/, $_mutoolShowOutput ) {
## Regular expression magic to grab what you want
if ( $line =~ /^(\d+)\s+(\d+)$/ ) {
$_objectstreams = $2;
}
}
if ($debug) {
say "Object streams: " . $_objectstreams;
}
return $_objectstreams;
}
sub outlineEverythingWeFound {
say ":outlineEverythingWeFound" if $debug;
#Draw the various types of boxes on the output PDF
my %font = (
Helvetica => {
Bold => $main::pdf->corefont(
'Helvetica-Bold', -encoding => 'latin1'
),
# Roman => $pdf->corefont('Helvetica', -encoding => 'latin1'),
# Italic => $pdf->corefont('Helvetica-Oblique', -encoding => 'latin1'),
},
Times => {
# Bold => $pdf->corefont('Times-Bold', -encoding => 'latin1'),
Roman => $main::pdf->corefont( 'Times', -encoding => 'latin1' ),
# Italic => $pdf->corefont('Times-Italic', -encoding => 'latin1'),
},
);
foreach my $key ( sort keys %main::latitudeTextBoxes ) {
my ($latitudeTextBox) = $main::page->gfx;
$latitudeTextBox->strokecolor('red');
$latitudeTextBox->linewidth(1);
$latitudeTextBox->rect(
$main::latitudeTextBoxes{$key}{"CenterX"} -
( $main::latitudeTextBoxes{$key}{"Width"} / 2 ),
$main::latitudeTextBoxes{$key}{"CenterY"} -
( $main::latitudeTextBoxes{$key}{"Height"} / 2 ),
$main::latitudeTextBoxes{$key}{"Width"},
$main::latitudeTextBoxes{$key}{"Height"}
);
$latitudeTextBox->stroke;
}
foreach my $key ( sort keys %main::longitudeTextBoxes ) {
my ($longitudeTextBox) = $main::page->gfx;
$longitudeTextBox->strokecolor('yellow');
$longitudeTextBox->linewidth(1);
$longitudeTextBox->rect(
$main::longitudeTextBoxes{$key}{"CenterX"} -
( $main::longitudeTextBoxes{$key}{"Width"} / 2 ),
$main::longitudeTextBoxes{$key}{"CenterY"} -
( $main::longitudeTextBoxes{$key}{"Height"} / 2 ),
$main::longitudeTextBoxes{$key}{"Width"},
$main::longitudeTextBoxes{$key}{"Height"}
);
$longitudeTextBox->stroke;
}
foreach my $key ( sort keys %main::latitudeAndLongitudeLines ) {
my ($lines) = $main::page->gfx;
$lines->strokecolor('orange');
$lines->linewidth(2);
$lines->move(
$main::latitudeAndLongitudeLines{$key}{"X"},
$main::latitudeAndLongitudeLines{$key}{"Y"}
);
$lines->line(
$main::latitudeAndLongitudeLines{$key}{"X2"},
$main::latitudeAndLongitudeLines{$key}{"Y2"}
);
$lines->stroke;
}
}
sub findAllIcons {
my ($_output);
say ":findAllIcons" if $debug;
#Loop through each "stream" in the pdf looking for our various icon regexes
for ( my $i = 1 ; $i <= ( $main::objectstreams - 1 ) ; $i++ ) {
$_output = qx(mutool show $main::targetPdf $i x);
my $retval = $? >> 8;
if ( $_output eq "" || $retval != 0 ) {
say
"No output from mutool show. Is it installed? Return code was $retval";
return;
}
print "Stream $i: " if $debug;
findLatitudeAndLongitudeLines($_output);
findLatitudeAndLongitudeTextBoxes($_output);
say "" if $debug;
}
return;
}
sub findClosestLineToTextBox {
#Find the closest line of preferredOrientation to this textbox
my ( $hashRefTextBox, $hashRefLine, $preferredOrientation ) = @_;
say ":findClosestLineToTextBox" if $debug;
#Maximum distance in points between textbox center and line endpoint
my $maxDistance = 70;
# say "findClosest $hashRefLine to each $hashRefTextBox" if $debug;
foreach my $key ( sort keys %$hashRefTextBox ) {
#Start with a very high number so initially everything is closer than it
my $distanceToClosest = 999999999999;
foreach my $key2 ( sort keys %$hashRefLine ) {
#The X distance from the textbox center to each endpoint X coordinate
my $distanceToLineX =
$hashRefLine->{$key2}{"X"} - $hashRefTextBox->{$key}{"CenterX"};
my $distanceToLineX2 =
$hashRefLine->{$key2}{"X2"} - $hashRefTextBox->{$key}{"CenterX"};
#The Y distance from the textbox center to each endpoint Y coordinate
my $distanceToLineY =
$hashRefLine->{$key2}{"Y"} - $hashRefTextBox->{$key}{"CenterY"};
my $distanceToLineY2 =
$hashRefLine->{$key2}{"Y2"} - $hashRefTextBox->{$key}{"CenterY"};
#Calculate the distance to each endpoint of the line
my $hypotenuse = sqrt( $distanceToLineX**2 + $distanceToLineY**2 );
my $hypotenuse2 =
sqrt( $distanceToLineX2**2 + $distanceToLineY2**2 );
# say "$hypotenuse, $hypotenuse2";
#Prefer whichever endpoint is closest
if ( $hypotenuse2 < $hypotenuse ) {
$hypotenuse = $hypotenuse2;
}
my $lineSlope = $hashRefLine->{$key2}{"Slope"};
$lineSlope = $lineSlope % 180;
#We can adjust our tolerance to rotation here
#I think most civilian diagrams are either True North up or rotated 90 degrees
#I know at least one military plate, KSUU, is rotated arbitrarily
if ( $preferredOrientation =~ m/vertical/ ) {
#Skip this line if it's horizontal
# if ( ( $lineSlope < 45 ) || ( $lineSlope > 135 ) ) {
if ( ( $lineSlope < 88 ) || ( $lineSlope > 92 ) ) {
say
"Wanted vertical but this line is horizontal, lineSlope: $lineSlope, preferredOrientation: $preferredOrientation"
if $debug;
next;
}
}
elsif ( $preferredOrientation =~ m/horizontal/ ) {
#Skip this line if it's vertical
# if ( ( $lineSlope > 45 ) && ( $lineSlope < 135 ) ) {
if ( ( $lineSlope > 2 ) && ( $lineSlope < 178 ) ) {
say
"Wanted horizontal but this line is vertical,lineSlope: $lineSlope, preferredOrientation: $preferredOrientation"
if $debug;
next;
}
}
else {
say "Unrecognized orientation";
next;
}
#Ignore this textbox if it's further away than our max distance variables
next
if (
(
$hypotenuse > $maxDistance
|| $hypotenuse > $distanceToClosest
)
);
#Update the distance to the closest line endpoint
$distanceToClosest = $hypotenuse;
$hashRefTextBox->{$key}{"MatchedTo"} = $key2;
# $hashRefLine->{$key2}{"MatchedTo"} = $key;
}
}
if ($debug) {
# print Dumper ($hashRefTextBox);
# say "";
# say "$hashRefLine";
# print Dumper ($hashRefLine);
}
return;
}
sub findLatitudeAndLongitudeLines {
#Finds lines
my ($_output) = @_;
say ":findLatitudeAndLongitudeLines" if $debug;
#REGEX building blocks
#A line
my $lineRegex = qr/^$main::transformCaptureXYRegex$
^$main::originRegex$
^($main::numberRegex)\s+($main::numberRegex)\s+l$
^S$
^Q$/m;
my @tempLine = $_output =~ /$lineRegex/ig;
my $tempLineLength = 0 + @tempLine;
my $tempLineCount = $tempLineLength / 4;
if ( $tempLineLength >= 4 ) {
my $random = rand();
for ( my $i = 0 ; $i < $tempLineLength ; $i = $i + 4 ) {
#Let's only save long lines
my $distanceHorizontal = $tempLine[ $i + 2 ];
my $distanceVertical = $tempLine[ $i + 3 ];
my $hypotenuse =
sqrt( $distanceHorizontal**2 + $distanceVertical**2 );
#Is line too short to consider?
next if ( abs( $hypotenuse < 3 ) );
#Get endpoints from array
my $_X = $tempLine[$i];
my $_Y = $tempLine[ $i + 1 ];
my $_X2 = $_X + $tempLine[ $i + 2 ];
my $_Y2 = $_Y + $tempLine[ $i + 3 ];
#put them into a hash
$main::latitudeAndLongitudeLines{ $i . $random }{"X"} = $_X;
$main::latitudeAndLongitudeLines{ $i . $random }{"Y"} = $_Y;
$main::latitudeAndLongitudeLines{ $i . $random }{"X2"} = $_X2;
$main::latitudeAndLongitudeLines{ $i . $random }{"Y2"} = $_Y2;
$main::latitudeAndLongitudeLines{ $i . $random }{"CenterX"} =
( $_X + $_X2 ) / 2;
$main::latitudeAndLongitudeLines{ $i . $random }{"CenterY"} =
( $_Y + $_Y2 ) / 2;
$main::latitudeAndLongitudeLines{ $i . $random }{"Slope"} =
round( slopeAngle( $_X, $_Y, $_X2, $_Y2 ) );
}
}
my $lineRegex2 = qr/^$main::transformCaptureXYRegex$
^$main::originRegex$
^($main::numberRegex)\s+($main::numberRegex)\s+l$
^($main::numberRegex)\s+($main::numberRegex)\s+l$
^S$
^Q$/m;
@tempLine = $_output =~ /$lineRegex2/ig;
$tempLineLength = 0 + @tempLine;
$tempLineCount = $tempLineLength / 6;
if ( $tempLineLength >= 6 ) {
my $random = rand();
for ( my $i = 0 ; $i < $tempLineLength ; $i = $i + 6 ) {
#Let's only save long lines
my $distanceHorizontal = $tempLine[ $i + 4 ];
my $distanceVertical = $tempLine[ $i + 5 ];
my $hypotenuse =
sqrt( $distanceHorizontal**2 + $distanceVertical**2 );
#Is line too short to consider?
next if ( abs( $hypotenuse < 35 ) );
#Get endpoints from array
my $_X = $tempLine[$i];
my $_Y = $tempLine[ $i + 1 ];
my $_X2 = $_X + $distanceHorizontal;
my $_Y2 = $_Y + $distanceVertical;
#put them into a hash
$main::latitudeAndLongitudeLines{ $i . $random }{"X"} = $_X;
$main::latitudeAndLongitudeLines{ $i . $random }{"Y"} = $_Y;
$main::latitudeAndLongitudeLines{ $i . $random }{"X2"} = $_X2;
$main::latitudeAndLongitudeLines{ $i . $random }{"Y2"} = $_Y2;
$main::latitudeAndLongitudeLines{ $i . $random }{"CenterX"} =
( $_X + $_X2 ) / 2;
$main::latitudeAndLongitudeLines{ $i . $random }{"CenterY"} =
( $_Y + $_Y2 ) / 2;
$main::latitudeAndLongitudeLines{ $i . $random }{"Slope"} =
round( slopeAngle( $_X, $_Y, $_X2, $_Y2 ) );
}
}
my $lineRegex3 = qr/^$main::transformCaptureXYRegex$
^$main::originRegex$
^($main::numberRegex)\s+($main::numberRegex)\s+l$
^($main::numberRegex)\s+($main::numberRegex)\s+l$