forked from johnchapman2/pyortho
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathortho_util.py
2767 lines (2279 loc) · 101 KB
/
ortho_util.py
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
from __future__ import division, print_function
import sys, os, datetime, time, json, warnings, signal
from os import SEEK_CUR,SEEK_SET
from os.path import join as pathjoin, exists as pathexists, split as pathsplit
from os.path import splitext, abspath, getsize, realpath, relpath, isabs, expandvars
# (importing individual functions used to be faster than 'from numpy import *')
from numpy import r_, c_, array, asarray, asmatrix, arange, dot, sqrt, ravel
from numpy import float32, float64, count_nonzero
from numpy import bool8, uint8, uint16, uint32, uint64, int8, int16, int32, int64
from numpy import bitwise_and, meshgrid, mgrid, apply_along_axis, dstack
from numpy import fromfile, where, sign, floor, ceil, ones, zeros, round
from numpy import argsort, sort, searchsorted, unique, cumsum, polyfit, polyval
from numpy import pi, tan, sin, cos, arccos, arcsin, arctan, arctan2, hypot
from numpy import roll as np_roll, sum as np_sum, max as np_max, min as np_min
from numpy import nonzero, gradient, memmap, zeros_like, lexsort, linspace
from numpy import inf, nan, isnan, nanpercentile
from numpy import ones_like, zeros_like, newaxis, power
from numpy import mean, median, diff, setdiff1d, mgrid, percentile, clip
from numpy.linalg import inv
from numpy import set_printoptions
from skimage.segmentation import find_boundaries
from skimage.measure import label as bwlabel
from scipy.ndimage.interpolation import map_coordinates
from spectral.io.envi import read_envi_header, write_envi_header, \
open as envi_open, create_image as envi_create_image
try:
from numba import jit as nbjit
except Exception as e:
pass
# print debug output?
DEBUG = 0
# exit codes
SUCCESS = 0
FAILURE = 1
dtime_now = datetime.datetime.now
time_elapsed = lambda start_time: str(dtime_now()-start_time)[2:-4]
time_sleep = time.sleep
def formatwarning(*args):
message, category, filepath, lineno = args[:4]
filedir,filename = pathsplit(filepath)
return "%s (%s:%s): %s\n" % (category.__name__, filename, lineno, message)
warnings.formatwarning = formatwarning
warn = warnings.warn
set_printoptions(suppress=True,precision=6)
# set up functions necessary to load local modules first
def wait_exit(retval,msg=''):
if msg != '':
print(msg)
raw_input()
sys.exit(retval)
def get_env(var_name, default=None):
# fall back to default when available without waiting
env_value = os.getenv(var_name) or default
if env_value is None:
# error and wait if value not found and no default provided
wait_exit(FAILURE,'Error (get_env): %s environment variable not defined'%var_name)
return env_value
def runcmd(cmd,verbose=0):
from shlex import split as shsplit
from subprocess import Popen, PIPE
cmdstr = ' '.join(cmd) if isinstance(cmd,list) else cmd
cmdspl = shsplit(cmdstr)
if len(cmdspl)==0:
cmdspl.append("")
if verbose:
print('runcmd: executing command "%s"'%cmdspl[0],
'with args',cmdspl[1:])
cmdout = PIPE
for rstr in ['>>','>&','>']:
if rstr in cmdstr:
cmdstr,cmdout = map(lambda s:s.strip(),cmdstr.split(rstr))
mode = 'w' if rstr!='>>' else 'a'
cmdout = open(cmdout,mode)
stime = dtime_now()
p = Popen(cmdstr.split(), stdout=cmdout, stderr=cmdout)
out, err = p.communicate()
retcode = p.returncode
if cmdout != PIPE:
cmdout.close()
if verbose:
cmdtime = dtime_now()-stime
print("runcmd: finished executing command\n"
"cputime=%s seconds, return code=%s."%(str(cmdtime),str(retcode)))
return out,err,retcode
# global path variables (inferred with respect to this file)
PYORT_ROOT = pathsplit(realpath(__file__))[0] # (i.e., directory of this file)
PYEXT_ROOT = pathjoin(PYORT_ROOT,'external')
ORTHO_ROOT = realpath(pathjoin(PYORT_ROOT,'..'))
PLATFORM_ROOT = realpath(pathjoin(PYORT_ROOT,'platform'))
CONFIG_FILE = realpath(pathjoin(PYORT_ROOT,'config/pyorthorc.offline'))
# update python paths
FPT_ROOT = pathjoin(PYORT_ROOT,'find_pixel_trace_cython')
FPT_LIB = pathjoin(FPT_ROOT,'find_pixel_trace_cython.so')
SUNPOS_ROOT = pathjoin(PYEXT_ROOT,'sunpos-1.1')
SUNPOS_LIB = pathjoin(SUNPOS_ROOT,'_sunpos.so')
sys.path.extend([PYORT_ROOT,PYEXT_ROOT,FPT_ROOT,SUNPOS_ROOT])
PYEXT_PKG = ['LatLongUTMconversion','sun_dist','sunpos-1.1']
for pkg_path in PYEXT_PKG:
sys.path.append(pathjoin(PYEXT_ROOT,pkg_path))
# local, external, and compiled imports
from LatLongUTMconversion import LLtoUTM, UTMtoLL
from sun_dist import sun_dist_au
# run build_link_cython.sh if FPT_LIB or SUNPOS_LIB not found
if not (pathexists(FPT_LIB) and pathexists(SUNPOS_LIB)):
print('Building find_pixel_trace and sunpos libraries')
curdir = os.getcwd()
os.chdir(PYORT_ROOT)
out,err,retcode = runcmd(pathjoin(PYORT_ROOT,'build_link_cython.sh')+' '+PYORT_ROOT)
if retcode!=0:
print('Error building the find_pixel_trace and sunpos libraries')
print('stdout:\n',out,'\n')
print('stderr:\n',err,'\n')
sys.exit(retcode)
os.chdir(curdir)
print('Build successful')
try:
import find_pixel_trace_cython.find_pixel_trace_cython as _fptlib
def find_pixel_trace(xs,ys,xe,ye):
"""
find_pixel_trace(xs,ys,xe,ye)
Summary: computes 2d shortest path + l2 cost from (xs,ys) to (xe,ye)
Arguments:
- xs: xstart
- ys: ystart
- xe: xend
- ye: yend
Keyword Arguments:
None
Output:
- output
Examples:
>>> find_pixel_trace(1,1,3,3)
array([[1. , 1. , 0. ],
[1. , 2. , 1. ],
[2. , 2. , 1.414214],
[2. , 3. , 2.236068],
[3. , 3. , 2.828427]])
"""
return _fptlib.find_pixel_trace_cython(xs,ys,xe,ye)
except Exception as e:
msg = 'Error importing find_pixel_trace_cython (did you run build_link_cython.sh?)'
warn(msg)
sys.exit(FAILURE)
try:
from sunpos import sunpos, cLocation, cTime, cSunCoordinates
except Exception as e:
msg = 'Error importing sunpos library (did you run build_link_cython.sh?)'
warn(msg)
sys.exit(FAILURE)
double = float64
# sentinel empty return value
EMPTY = zeros(0)
# flag to indicate search failure (e.g., no science frames found in chunk)
NOTFOUND = -1
# georeferencing/gps/pps/frame constants
DATUM_WGS84 = 23
GPS_EPOCHJD = 2444245
MAXINT14 = 2**14-1
g_14bit_mask = uint32(MAXINT14)
OBC_DARK1 = 2
OBC_SCIENCE = 3
OBC_DARK2 = 4
OBC_BRIGHTMED = 5
OBC_BRIGHTHI = 6
OBC_LASER = 7
OBC_STATUS_MSG = {OBC_DARK1: "OBC_DARK1",
OBC_SCIENCE: "OBC_SCIENCE",
OBC_DARK2: "OBC_DARK2",
OBC_BRIGHTMED: "OBC_BRIGHTMED",
OBC_BRIGHTHI: "OBC_BRIGHTHI",
OBC_LASER: "OBC_LASER"}
# gps status messages in frame header
HxBABE = uint32(47806) # gps aligned to pps
HxDEAD = uint32(57005) # gps not aligned with pps (interpolate)
HxBAD = uint32(2989) # gps with no pps
GPS_STATUS_MSG = {HxBABE:'HxBABE',HxDEAD:'HxDEAD',HxBAD:'HxBAD'}
# pixel-level ortho error codes
# IMPORTANT: all subsequent error codes must be less than PIX_ERROR_UNDEF
PIX_ERROR_UNDEF = -9900
PIX_ERROR_OUTSIDE_PB = -9901
PIX_ERROR_NO_LOC = -9902
PIX_ERROR_DEM_EXTENT = -9903
PIX_ERROR_DEM_NOZINT = -9904
PIX_DATA_IGNORE_VALUE = -9999
PIX_ERROR_MSG = {PIX_ERROR_UNDEF: 'uninitialized',
PIX_ERROR_OUTSIDE_PB: 'outside pushbroom bounds',
PIX_ERROR_NO_LOC: 'cannot determine ground location from PPS/GPS data',
PIX_ERROR_DEM_EXTENT: 'outside DEM extent',
PIX_ERROR_DEM_NOZINT: 'did not intersect DEM',
PIX_DATA_IGNORE_VALUE: 'nodata value'}
# downtrack averaging error codes
DT_ERROR_UNDEF = PIX_ERROR_UNDEF
# lat/lon bounds for geoid interpolation
LATMIN,LATMAX = -90.0, 90.0
LONMIN,LONMAX = 0.0, 360.0
DEG2RAD = double(pi/180.0)
RAD2DEG = 1.0/DEG2RAD
def basename(path):
'''
/path/to/file.ext -> file
'''
return splitext(pathsplit(path)[1])[0]
def filename2flightid(filename,check_prefix=True):
'''
get flight id from filename
ang20160922t184215_cmf_v1g_img -> ang20160922t184215
'''
imgid = basename(filename)
prefix = ('ang','prm','AVng','PRISM')
if check_prefix and any([imgid.startswith(p) for p in prefix]):
imgid = imgid.split('_')[0]
return imgid
def datestr(fmt='%m%d%y',date=datetime.datetime.now()):
return date.strftime(fmt)
def input_timeout(prompt, defstr='y', timeout=5):
def interrupt_input(signum, frame):
raise KeyboardInterrupt
astring = defstr # return defstr if no input entered by timeout
signal.signal(signal.SIGALRM, interrupt_input)
signal.alarm(timeout)
try:
astring = raw_input(prompt)
except KeyboardInterrupt:
pass
signal.alarm(0) # disable the signal after we've gotten valid input
return astring.strip()
def timeit(func):
"""
timeit(func)
Decorator to time the invocation of a function
Arguments:
- func: function to time
Keyword Arguments:
None
Returns:
- return value(s) of function func
"""
from time import time
outstr = '%s.%s elapsed time: %0.3f seconds'
def wrapper(*args,**kwargs):
starttime = time()
res = func(*args,**kwargs)
print(outstr%(func.__module__,func.func_name, time()-starttime))
return res
return wrapper
def envi_mapinfo(img,astype=dict):
maplist = img.metadata.get('map info',None)
if maplist is None:
return None
elif astype==list:
return maplist
if astype==str:
mapstr = '{ %s }'%(', '.join(maplist))
return mapstr
elif astype==dict:
from collections import OrderedDict
if maplist is None:
return {}
mapinfo = OrderedDict()
mapinfo['proj'] = maplist[0]
mapinfo['xtie'] = float(maplist[1])
mapinfo['ytie'] = float(maplist[2])
mapinfo['ulx'] = float(maplist[3])
mapinfo['uly'] = float(maplist[4])
mapinfo['xps'] = float(maplist[5])
mapinfo['yps'] = float(maplist[6])
if mapinfo['proj'] == 'UTM':
mapinfo['zone'] = maplist[7]
mapinfo['hemi'] = maplist[8]
mapinfo['datum'] = maplist[9]
elif mapinfo['proj'] == 'Geographic Lat/Lon':
mapinfo['ref'] = maplist[7]
mapmeta = []
for mapitem in maplist[len(mapinfo):]:
if '=' in mapitem:
key,val = map(lambda s: s.strip(),mapitem.split('='))
mapinfo[key] = val
else:
mapmeta.append(mapitem)
mapinfo['rotation'] = float(mapinfo.get('rotation','0'))
if len(mapmeta)!=0:
mapinfo['metadata'] = mapmeta
return mapinfo
def float2byte(I,nodata,cliprange=0.99):
Idata = I!=nodata
Imin,Imax = percentile(I[Idata],[1.0-cliprange,cliprange])
Inorm = clip(I,Imin,Imax)
Inorm = uint8(255*(Inorm-Imin)/(Imax-Imin))
Inorm[~Idata] = 0
return Inorm
def envi2jpeg(img_hdrf,img_jpgf,bands=[0]):
from skimage.io import imsave
img = envi_open(img_hdrf,image=img_hdrf.replace('.hdr',''))
meta = img.metadata
interleave = meta['interleave']
nodata = float32(meta.get('data ignore value',-9999))
imgmm = img.open_memmap(interleave='source',writable=False)
imgbands = []
for band in bands:
if interleave == 'bip':
imgband = imgmm[:,:,band]
elif interleave == 'bil':
imgband = imgmm[:,band,:]
scband = float2byte(array(imgband,dtype=float32),nodata)
imgbands = scband[:,:,newaxis] if len(imgbands)==0 else dstack((imgbands,scband))
imsave(img_jpgf,imgbands.squeeze())
def mask_undef(A):
return A==PIX_ERROR_UNDEF
def mask_errors(A):
# return boolean mask where all errors AND undefined pixels flagged
return A<=PIX_ERROR_UNDEF
def any_errors(A,axis=None):
return mask_errors(A).any(axis=axis)
def all_errors(A,axis=None):
return mask_errors(A).all(axis=axis)
def get_projection(imgf):
img = envi_open(imgf+'.hdr',image=imgf)
map_info = img.metadata['map info']
return map_info[0]
def get_igm_zone(igm):
description = igm.metadata.get('description','')
zstr_idx = description.find('zone')
if zstr_idx == -1:
warn('utm zone undefined in IGM file %s'%igm_hdrf)
return '',''
utm_toks = description[zstr_idx:].split()
utm_zone = int(utm_toks[1])
utm_hemi = 'North' if 'North' in utm_toks[2] else 'South'
return utm_zone, utm_hemi
def rebin(a,f):
"""
rebin(a,f)
Python version of IDL rebin: http://www.exelisvis.com/docs/REBIN.html
Limitations: Handles 1-d case only, does NOT upsample.
Arguments:
- a: 1d input array length n
- f: bin factor (>1; note: this differs from IDL argument "m" = a.size/f)
Keyword Arguments:
None
Returns:
- rebinned array of length m = len(a)/f
Examples:
>>> list(rebin(array([0, 10, 20, 30]),2))
[5.0, 25.0]
>>> list(rebin(array([1690014621, 1690015217, 1690015813, 1690016409, 1690017005, 1690017601, 1690018196, 1690018792, 1690019388, 1690019984, 1690020580, 1690021176, 1690021772, 1690022368, 1690022964, 1690023560, 1690024156, 1690024751],dtype=int),9))
[1690017004.6666667, 1690022367.8888888]
"""
if f>1:
n = len(a)
if n % f != 0:
warn('f must be an integer multiple of n')
return a
ff = double(f)
m = int(n*(1.0/ff))
b = zeros(m)
b[:] = [(a[f*i:f*(i+1)].sum())/ff for i in range(m)]
#b = b-(b.min()-a.min())
return b
elif f<1:
warn('rebin cannot upsample, returning original, unsampled array')
# no resampling, return a
return a
def extrema(a,**kwargs):
'''
extrema(a,**kwargs) -> float,float
Computes the extrema of a list/array
Arguments:
- a: array like
Keyword Arguments:
- p: return (1-p),p percentiles instead of min/max (default=1.0)
- keywards arguments passed to np.min/np.max
Examples:
>>> extrema([-0.538577, 2.501624, -1.227843, 1.469152])
(-1.227843, 2.501624)
'''
p = kwargs.pop('p',1.0)
if p==1.0:
return np_min(a,**kwargs),np_max(a,**kwargs)
assert(p>0.0 and p<1.0)
axis = kwargs.pop('axis',None)
apercent = lambda q: nanpercentile(a,axis=axis,q=q,interpolation='nearest')
return apercent((1-p)*100),apercent(p*100)
def julday(month,day,year):
'''
given mm/dd/yy, return julian day
'''
a = (14 - month)//12
y = year + 4800 - a
m = month + 12*a - 3
return day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045
def gps2hour(gpstime):
#sec_per_hour=3600 # 60**2
#sec_per_day=86400 # 24*sec_per_hour
# Examples:
# >>> gpstime = 323562.00916666654
# >>> gps2hour(gpstime)
# 17.878335879629596
return (gpstime % 86400)/3600.0
def gps2time(gpstime):
return gps2hour(gpstime)
def file2date(rawf):
import re
m = re.match(r'^.*([0-9]{8}t[0-9]{6}).*', rawf)
if m is None:
warn('Malformed filename %s, cannot extract date'%rawf)
return EMPTY
sdate = m.group(1)
year,month,day = map(int,[sdate[:4],sdate[4:6],sdate[6:8]])
file_jd=julday(month,day,year)
gps_week=int((file_jd-GPS_EPOCHJD)/7)
hour,minute,sec = map(double,[sdate[9:11],sdate[11:13],sdate[13:]])
return year,month,day,gps_week,hour,minute,sec
def lsq1d(x,y):
"""
lsq1d(x,y)
Summary: given a pair of 1D vectors x,y, return f_{lsq}(x)->y
Arguments:
- x: 1xn independent variable vector
- y: 1xn dependend variable
Keyword Arguments:
None
Output:
- linear lsq fit f_{lsq}(x)->y
"""
from scipy.linalg import lstsq
m, b = lstsq(np.vstack([x,np.ones_like(x)]).T,y)[0]
flsq = lambda xi: m*xi + b
return flsq
def compute_geoidtrace(geoid,lon,lat,dps,interp=True):
'''
'''
geoidlat,geoidlon = (lat-LATMAX)/(-dps),(lon-LONMIN)/dps
if interp:
# note: return scalar rather than 1x1 array
return bilerp(geoid,geoidlat,geoidlon)[0]
return geoid[int(geoidlat),int(geoidlon)]
def bilerp(gridxy, gridxf, gridyf):
"""
bilinear interpolation on a regular grid
Examples:
>>> bilerp(array([[0,2],[4,8]]),0.5,0)
array([1.])
>>> bilerp(array([[0,2],[4,8]]),0.0,0.5)
array([2.])
>>> bilerp(array([[0,2],[4,8]]),[0.5,0.5],[0,0.5])
array([1. , 3.5])
>>> bilerp(array([[0,2],[4,8]]),1,1)
array([8.])
"""
return map_coordinates(gridxy,[[gridyf],[gridxf]],order=1,prefilter=False,
output=double).ravel()
def rotxy(x,y,adeg,xc,yc):
"""
rotxy(x,y,adeg,xc,yc)
Summary: rotate point x,y about xc,yc by adeg degrees
Arguments:
- x: x coord to rotate
- y: y coord to rotate
- adeg: angle of rotation in degrees
- xc: center x coord
- yc: center y coord
Output:
rotated x,y point
"""
arad = DEG2RAD*adeg
sinr,cosr = sin(arad),cos(arad)
rotm = [[cosr,-sinr],[sinr,cosr]]
xp,yp = dot(rotm,[x-xc,y-yc])+[xc,yc]
return xp,yp
def lonlat2utm(lon,lat,zone=None):
'''
Examples:
>>> lon,lat,zone = -90.0, 17.7, 16
>>> x,y,zone,zonealpha=lonlat2utm(lon,lat,zone=zone)
>>> '%.3f, %.3f, %d, %s'%(x,y,zone,zonealpha)
'181760.100, 1959529.923, 16, Q'
>>> lon,lat = utm2lonlat(y,x,zone,zonealpha)
>>> '%.1f, %.1f'%(lon,lat)
'-90.0, 17.7'
>>> lon,lat,zone = 147.8413733, -16.9661409, 55
>>> x,y,zone,zonealpha=lonlat2utm(lon,lat,zone=zone)
>>> '%.3f, %.3f, %d, %s'%(x,y,zone,zonealpha)
'589577.252, 8123998.687, 55, K'
>>> lon,lat = utm2lonlat(y,x,zone,zonealpha)
>>> '%.1f, %.1f'%(lon,lat)
'147.8, -17.0'
'''
UTMZone, UTMEasting, UTMNorthing = LLtoUTM(DATUM_WGS84,lat,lon,ZoneNumber=zone)
return UTMEasting, UTMNorthing, int(UTMZone[:-1]), UTMZone[-1]
def utm2lonlat(y,x,utm_zone,utm_alpha):
'''
Examples:
>>> x, y, zone, zonealpha = 181760.100,1959529.923,16,'Q'
>>> lon,lat = utm2lonlat(y,x,zone,zonealpha)
>>> '%.1f, %.1f'%(lon,lat)
'-90.0, 17.7'
>>> x,y,zone,zonealpha = lonlat2utm(lon,lat,zone=zone)
>>> '%.3f, %.3f, %d, %s'%(x,y,zone,zonealpha)
'181760.100, 1959529.923, 16, Q'
'''
lat,lon = UTMtoLL(DATUM_WGS84,double(y),double(x),str(utm_zone)+utm_alpha)
return lon,lat
def map2sl(x, y, ulx, uly, ps):
"""
map2sl(x,y,ulx,uly,ps)
Given a defined grid find the s,l values for a given x,y
Arguments:
- x,y: map coordinates
- ulx,uly: upper left map coordinate
- ps: map pixel size
Keyword Arguments:
None
Returns:
- s,l: sample line coordinates of x,y
Examples:
>>> ulx,uly = 0,1000.0
>>> lrx,lry = 1000.0,0.0
>>> map2sl(lrx,lry,ulx,uly,1)
(1000.0, 1000.0)
>>> map2sl(ulx,lry,ulx,uly,1)
(0.0, 1000.0)
>>> map2sl(lrx,uly,ulx,uly,1)
(1000.0, 0.0)
>>> s,l = map2sl(ulx,uly,ulx,uly,1)
>>> sl2map(s,l,ulx,uly,1)
(0.0, 1000.0)
"""
return (x-ulx)/ps, (uly-y)/ps
def sl2map(s,l,ulx,uly,ps):
"""
sl2map(s,l,ulx,uly,ps)
Given pixel coordinates (s,l) convert to UTM map coordinates mapX,mapY
Arguments:
- s,l: sample, line indices
- ulx,uly: upper left map coordinate
- ps: map pixel size
Keyword Arguments:
None
Returns:
- mapX,mapY: s,l in map coordinates
Examples:
>>> ulx,uly = 0,1000.0
>>> s,l = map2sl(ulx,uly,ulx,uly,1)
>>> s,l
(0.0, 0.0)
>>> sl2map(s,l,ulx,uly,1)
(0.0, 1000.0)
"""
return ulx+ps*s, uly-ps*l
def subset_igm(igmf,lon,lat,nbb):
"""
subset_igm(igm,lon,lat,bbrad)
Summary: get the bounding box in pixel coordinates to extract a
[mh x mw] region surrounding coordinate (lon,lat) from an igm file
Arguments:
- igm: igm file
- lon: longitude of bbox center
- lat: latitude of bbox center
- nbb: dim of bbox in pixels
Keyword Arguments:
None
Output:
- [nbb*nbb x 4] matrix of [row,col,utmx,utmy] values
'''
Examples:
>>> lon,lat = -117.336488,33.965377
>>> igmf = '/Users/bbue/Research/range/watch_out/pyortho-latest/ang20140612t204858_rdn_igm'
>>> igmout = subset_igm(igmf,lon,lat,2)
"""
igm_img = envi_open(igmf+'.hdr',image=igmf)
utm_zone,utm_hemi = get_igm_zone(igm_img)
bin_factor = int(igm_img.metadata['line averaging'])
print(bin_factor)
igm_mm = igm_img.open_memmap(interleave='source')
utmx,utmy,utm_zone,utm_alpha = lonlat2utm(lon,lat)
nbr,nbc = nbb,nbb
nrows,ncols = igm_mm.shape[:2]
dist = sqrt((igm_mm[:,:,0]-utmx)**2+(igm_mm[:,:,1]-utmy)**2)
cy,cx = map(lambda idx: idx[0],where(dist==dist.min()))
rowmin,rowmax = max(0,cy-nbr),min(nrows-1,cy+nbr+1)
colmin,colmax = max(0,cx-nbc),min(ncols-1,cx+nbc+1)
h,w = rowmax-rowmin,colmax-colmin
rows = arange(rowmin,rowmax)
cols = arange(colmin,colmax)
rr,cc = meshgrid(rows,cols)
print(igm_mm.shape)
utmxv = igm_mm[rr,cc,0].ravel()
utmyv = igm_mm[rr,cc,1].ravel()
print(len(rr),utmxv.shape)
print(lon,lat,utmx,utmy,cx,cy,utm_zone,len(utmxv),h,w)
return rr,cc,utmxv,utmyv
def array2rgba(a,cmap=None,**kwargs):
import pylab as pl
from numpy import clip,uint8
vmin = float(kwargs.pop('vmin',a.min()))
vmax = float(kwargs.pop('vmax',a.max()))
an = clip(((a-vmin)/(vmax-vmin)),0.,1.)
if cmap is None:
cmap = pl.get_cmap(pl.rcParams['image.cmap'])
elif isinstance(cmap,str):
cmap = pl.get_cmap(cmap)
return cmap(an)
def rotate_camera(camera_model,rot=0,reversed=False):
det_ids = arange(camera_model.shape[1])
new_model = (camera_model[:,det_ids[::-1]] \
if reversed else camera_model).copy()
if rot==0:
return new_model
ar = DEG2RAD*rot
sinr = sin(ar)
cosr = cos(ar)
rotm = float64([[cosr,-sinr, 0.],
[sinr, cosr, 0.],
[0., 0., 1.]])
new_model = dot(rotm.T,new_model)
#print('camera_model.shape',camera_model.shape)
#print('new_model.shape',new_model.shape)
return new_model
def plot_trajectory(frame_pos,frame_clock,fig=None,ax=None,cmap=None):
import pylab as pl
from mpl_toolkits.mplot3d import Axes3D
fig = fig or pl.figure()
ax3 = ax or fig.add_subplot(111, projection='3d')
lat,lon,alt = frame_pos[:,:3].T
print(lat,lon,alt,len(lon),len(alt))
x,y = zeros(len(lat)),zeros(len(lon))
x[0], y[0], ul_zone, ul_alpha = lonlat2utm(lon[0], lat[0])
for i,(loni,lati) in enumerate(zip(lon,lat)):
if i==0:
continue
x[i], y[i], ul_zone, ul_alpha = lonlat2utm(lon[i], lat[i], zone=ul_zone)
pitch,roll,head = frame_pos[3:6]
scale = 1.0 #111120.0
plot3 = ax3.scatter(x,y,alt,c=array2rgba(linspace(0,1,len(lon)),cmap=cmap))
def plot_camera(camera_model,reversed=False,fig=None,ax=None,c=None):
import pylab as pl
from mpl_toolkits.mplot3d import Axes3D
pb_len = int(camera_model.shape[1])
det_ids = arange(camera_model.shape[1])
if reversed:
det_ids = det_ids[::-1]
s = 30
pb_s = pb_len//s
x = arange(1,pb_len+1,s)
y,z = zeros(len(x)),zeros(len(x))
u,v,w = camera_model[:,::s]
_wmin,_wmax = extrema(w)
_wdif = (_wmax-_wmin)
_wsep = _wdif*0.05
if c is None:
c = det_ids/camera_model.shape[1]
c = r_[c,c_[c,c].ravel()]
cmap = pl.get_cmap(pl.rcParams['image.cmap'])
c = array2rgba(c,cmap=cmap)
print(c[::12][:,0])
# repeat to color arrow heads as well
print('plotting camera model with %d samples/frame'%pb_len)
fig = fig or pl.figure()
ax3 = ax or fig.add_subplot(111, projection='3d')
qout3 = ax3.quiver(x,y,z,-u,-v,-w,pivot='tail',length=_wdif/32,
arrow_length_ratio=0.1,
linewidths=1,colors=c)
ax3.set_xlabel('pushbroom')
ax3.set_ylabel('v')
ax3.set_zlabel('w')
ax3.set_xlim(-2,pb_len+3)
_vmin,_vmax = extrema(v)
_vsep = (_vmax-_vmin)*0.005
ax3.set_ylim(-_vsep,_vsep) #_vmin-_vsep,_vmax+_vsep)
#ax3.set_yticks([-0.1,-0.05,0,0.05,0.1])
xt = ['1']+(['']*2)+['%4.1f'%(pb_len/2)]+(['']*2)+['%d'%pb_len]
ax3.set_xticklabels(xt)
ax3.set_yticklabels(['','','','',''])
ax3.set_zlim(-_wsep,_wsep)
ax3.set_zticklabels(['','','','',''])
def plane2world_camera_model(pitch,roll,heading,camera,flip=False):
"""
plane2world_camera_model(pitch,roll,heading,camera)
Given the current (pitch,roll,heading), map camera model into
east north up (enu) frame
Arguments:
- pitch roll heading: in radians
- camera: [3 x pushbroom_length] frame offsets
Keyword Arguments:
None
Returns:
[3 x pushbroom length] camera model
"""
# C matrix converts from aero to enu frame
C = [[0., 1., 0.],
[1., 0., 0.],
[0., 0., -1.]]
cos_roll,sin_roll = cos(roll),sin(roll)
R_r = [[cos_roll, 0., -sin_roll],
[0., 1., 0.],
[sin_roll, 0., cos_roll]]
cos_pitch,sin_pitch = cos(pitch),sin(pitch)
R_p = [[1., 0., 0.],
[0., cos_pitch, sin_pitch],
[0., -sin_pitch, cos_pitch]]
cos_heading,sin_heading = cos(heading),sin(heading)
R_h = [[cos_heading, -sin_heading, 0.],
[sin_heading, cos_heading, 0.],
[0., 0., 1.]]
if flip:
orient = DEG2RAD*180.0
cos_orient,sin_orient = cos(orient),sin(orient)
R_o = [[cos_orient, -sin_orient, 0.],
[sin_orient, cos_orient, 0.],
[0., 0., 1.]]
return dot(dot(dot(dot(dot(R_r,R_p),R_h),R_o).T,C),camera)
# M= R_r*R_p*R_h = mout of navout_mout
#return asarray((((asmatrix(R_r)*R_p)*R_h).T*C)*camera)
return dot(dot(dot(dot(R_r,R_p),R_h).T,C),camera)
def gc_rad(dlat):
a,b = 6378.1370,6356.7523
a2,b2 = a*a,b*b
dlatr = DEG2RAD*dlat
cosr,sinr = cos(dlatr),sin(dlatr)
return sqrt( ( (power(a2*cosr,2.) + power(b2*sinr,2.)) /
(power(a*cosr,2.)) + power(b*sinr,2.)) )
def gc_distance(dlon1, dlat1, dlon2, dlat2):
"""
gc_distance(dlon1, dlat1, dlon2, dlat2)
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
Input:
- dlon1,dlat1: first lat/lon coordinate
- dlon2,dlat2: second lat/lon coordinate
Returns:
- distance between (dlon1,dlat1) and (dlon2,dlat2)
"""
# convert decimal degrees to radians haversine formula
lon1,lat1,lon2,lat2 = DEG2RAD*array([dlon1,dlat1,dlon2,dlat2])
a = power(sin((lat2-lat1)/2.),2.) + cos(lat1) * cos(lat2) * \
power(sin((lon2-lon1)/2.),2.)
return arcsin(sqrt(a))*12742000.0 # earthrad=6371km*1000m*2
def format_clock_words(msw,lsw):
return (int64(msw)<<16)+lsw
def extract_fc(word):
# applies 14 bit mask to extract frame count from 16-bit pps/gps word
return bitwise_and(g_14bit_mask, int32(word))
def read_frames_meta_bands(img_path, platform, start_line=0, num_lines=99999,
alloc_lines=1000, bands=[]):
if not pathexists(img_path):
warn('image file %s not found!'%img_path)
return EMPTY,EMPTY,0
if len(bands) == 0:
bands = arange(NC)
NC = platform.NC
NS = platform.NS
NRAW = platform.NRAW
NFRAME = platform.NFRAME
img_size = getsize(img_path)
num_read = 0
num_bands = len(bands)
alloc_meta = zeros([alloc_lines,2],dtype=int64)
meta = alloc_meta.copy()
read_bands = False if num_bands==0 else True
if read_bands:
img_bands = zeros([alloc_lines,NS,num_bands])
alloc_bands = img_bands.copy()
band_buf = zeros([NS,num_bands])
obc_start = NOTFOUND # odbc start frame
obcv_prev = NOTFOUND
done = False
def collect_bands(f_ptr,b_buf,band_idx,band_type='<u2'):
# parse band_idx bands starting after frame pointer f_ptr metadata
assert(list(band_idx)==sorted(band_idx))
f_start = f_ptr.tell()
b_prev = 0
for jb,b in enumerate(band_idx):
f_ptr.seek((b-b_prev)*NS*2,SEEK_CUR)
bj = fromfile(f_ptr, count=NS, dtype=band_type)
if len(bj) < NS:
break
b_buf[jb,:] = bj
b_prev = b
f_ptr.seek(f_start) # rewind to frame index to advance
return jb
with open(img_path, 'r') as f:
if start_line > 0:
f.seek(start_line*NRAW*2,SEEK_CUR)
if f.tell() >= img_size:
done=True
while not done and num_read < num_lines:
# get frame header
buf = fromfile(f, count=NS, dtype='<u2')
if len(buf) > 0:
clock = format_clock_words(buf[0],buf[1])
count = extract_fc(buf[160])
#int64(bitwise_and(uint32(g_14bit_mask), uint32(buf[160])))
obcv = buf[321] >> 8
if obcv == OBC_SCIENCE and obc_start == NOTFOUND:
obc_start = num_read
b_read = collect_bands(f,b_buf,bands)
if b_read == num_bands:
if num_read+1 == meta.shape[0]:
meta = r_[meta, alloc_meta.copy()]
img_bands = r_[img_bands, alloc_bands.copy()]
meta[num_read,:] = [clock, count]
img_bands[num_read,:,:] = b_buf
obcv_prev = obcv
num_read += 1
else:
done = True
f.seek(NC*NS*2,SEEK_CUR)
else:
done = True
img_bands = img_bands[:num_read,:]
meta = meta[:num_read,:]
#print("read_frames_meta_bands: start_line=%d, num_read=%d"%(start_line,num_read))
return img_bands, meta, num_read, obc_start
def read_frames_meta(img_path, platform, start_line=0, num_lines=inf,
alloc_lines=1000, obc_start=NOTFOUND,
return_obcv=False, transition_warnings=True,
verbose=False):
NC = platform.NC
NS = platform.NS