-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.py
More file actions
1963 lines (1538 loc) · 63.1 KB
/
Functions.py
File metadata and controls
1963 lines (1538 loc) · 63.1 KB
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
""" Script to store all functions"""
import numpy as np
from osgeo.gdalconst import *
from osgeo import ogr, gdal
import subprocess
import simplekml
import sys
import scipy
import multiprocessing as mp
from scipy import ndimage
import os
import cv2
import time
import multiprocessing as mp
from pathos.multiprocessing import ProcessingPool as PathosPool
import functools
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
from shapely.geometry import Polygon as shPol
from shapely.geometry.polygon import LinearRing as shLinRing
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from matplotlib.path import Path
from shapely.geometry import Polygon as shPol
from shapely.geometry import MultiPolygon as shMPol
from shapely.geometry import Point as shPoint
from osgeo import ogr
import json
from shapely.geometry import shape
import meshio
import numpy as np
import pygmsh
import re
import utm
import shutil
from osgeo import osr
def distanceMapCenter(buffer_size):
""" function to create a raster with distances to the central cell,
rounded, only input is the size of the buffer around the middle cell """
rows = buffer_size*2+1
dist = np.zeros([rows, rows])
mid = buffer_size # buffer size is alway the index of the middle cell
for i in range(0,rows):
for j in range(0,rows):
dist[i,j] = np.sqrt((i-mid)**2+(j-mid)**2)
dist = np.round(dist)
return(dist)
def rasterize(InputVector,RefImage,OutputImage):
""" function to rasterize vectorial data, works with polygons, points and lines
all corresponding cells get value 1 """
#InputVector = 'Roads.shp'
#OutputImage = 'Result.tif'
#RefImage = 'DEM.tif'
gdalformat = 'GTiff'
datatype = gdal.GDT_Byte
burnVal = 1 #value for the output image pixels
##########################################################
# Get projection info from reference image
Image = gdal.Open(RefImage, gdal.GA_ReadOnly)
# Open Shapefile
Shapefile = ogr.Open(InputVector)
Shapefile_layer = Shapefile.GetLayer()
# Rasterise
print("Rasterising shapefile...")
Output = gdal.GetDriverByName(gdalformat).Create(OutputImage, Image.RasterXSize, Image.RasterYSize, 1, datatype, options=['COMPRESS=DEFLATE'])
Output.SetProjection(Image.GetProjectionRef())
Output.SetGeoTransform(Image.GetGeoTransform())
# Write data to band 1
Band = Output.GetRasterBand(1)
Band.SetNoDataValue(0)
gdal.RasterizeLayer(Output, [1], Shapefile_layer, burn_values=[burnVal])
# Close datasets
Band = None
Output = None
Image = None
Shapefile = None
# Build image overviews
subprocess.call("gdaladdo --config COMPRESS_OVERVIEW DEFLATE "+OutputImage+" 2 4 8 16 32 64", shell=True)
print("Done.")
return(OutputImage)
def localEdgeRasterize(XY, generalize_factor=5, get_indices = False):
""" Function to locally rasterize a set of coordinates
@params:
XY - Required: List of coordinate pairs
generalize_factor - Optional: Factor to determine the degree of generalization"""
XY = addVerticesToPolygon(XY, generalize_factor, shapely= False)
XY_upd = []
for x, y in XY:
x = int(x / generalize_factor)
y = int(y / generalize_factor)
XY_upd.append([x, y])
XY_np = np.asarray(XY_upd)
x_min = np.min(XY_np[:, 0])
x_max = np.max(XY_np[:, 0])
y_min = np.min(XY_np[:, 1])
y_max = np.max(XY_np[:, 1])
cols = int(x_max - x_min + 2)
rows = int(y_max - y_min + 2)
ras = np.zeros([rows, cols])
XY_in = []
for c, r in XY_upd:
c = int(c - x_min + 1)
r = int(y_max - r + 1)
XY_in.append([r, c])
ras[r, c] = 1
if get_indices:
return ras, XY_in
else:
return ras
def localRasterize(XY_exter_L, XY_inner_L = [], generalize_factor = 1, get_indices = False, xmin = [], xmax = [], ymin = [], ymax = [], printing = False ):
""" Function to locally rasterize a set of coordinates
@params:
XY_exter_L - Required: List of coordinate pairs of outer bounds
XYs_inner - Optional: List of coordinate pairs lists of inner bounds
"""
t_start = time.time()
if XY_exter_L == []:
if type(xmin) != list and type(xmax) != list and type(ymin) != list and type(ymax) != list:
print('Woeps Empty Polygon, zero array is returned.')
return np.zeros([ymax-ymin, xmax-xmin])
else:
print('Woeps Empty Polygon, 0 is returned.')
return(0)
else:
# make sure it can accept both a single coordiante pair list or a list of lists
if len(XY_exter_L[0]) == 2:
XY_exter_L = [XY_exter_L]
if len(XY_inner_L) > 0:
if len(XY_inner_L[0]) == 2:
XY_inner_L = [XY_inner_L]
XY_exter_L_upd = []
XY_inner_L_upd = []
x_mins = []
y_mins = []
x_maxs = []
y_maxs = []
for XY_exter in XY_exter_L:
XY_exter_upd = []
for x, y in XY_exter:
x = int(x / generalize_factor)
y = int(y / generalize_factor)
XY_exter_upd.append([x, y])
XY_exter_L_upd.append(XY_exter_upd)
XY_exter_upd_np = np.asarray(XY_exter_upd)
x_mins.append(np.min(XY_exter_upd_np[:, 0]))
x_maxs.append(np.max(XY_exter_upd_np[:, 0]))
y_mins.append(np.min(XY_exter_upd_np[:, 1]))
y_maxs.append(np.max(XY_exter_upd_np[:, 1]))
if len(XY_inner_L) > 0:
for XY_inner in XY_inner_L:
XYs_inner_upd = []
for i in XY_inner:
XYs_inner_upd.append([])
for xy in i:
x = xy[0]
y = xy[1]
x = int(x / generalize_factor)
y = int(y / generalize_factor)
XYs_inner_upd[-1].append([x, y])
XY_inner_L_upd.append(XYs_inner_upd)
if type(xmax) == list: x_max = np.max(x_maxs)
else: x_max = xmax
if type(ymax) == list: y_max = np.max(y_maxs)
else: y_max = ymax
if type(xmin) == list: x_min = np.min(x_mins)
else: x_min = xmin
if type(ymin) == list: y_min = np.min(y_mins)
else: y_min = ymin
cols = int(x_max - x_min)
rows = int(y_max - y_min)
#print('xmax: ', x_max, 'and xmin: ', x_min)
#print('ymax: ', y_max, 'and ymin: ', y_min)
# Create vertex coordinates for each grid cell...
# (<0,0> is at the top left of the grid in this system)
print('preparing the mesh grid...')
x_ind, y_ind = np.meshgrid(np.arange(x_min, x_max), np.arange(y_min, y_max))
x, y = np.meshgrid(np.arange(cols), np.arange(rows))
x = x.flatten()+x_min
y = y.flatten()+y_min
points = np.vstack((x, y))
points = points.T
# outer bounds
t = 0
print('rasterizing...')
for XY in XY_exter_L_upd:
t += 1
printProgressBar(t, len(XY_inner_L_upd)+1)
path = Path(XY)
grid = path.contains_points(points)
grid = grid.reshape((rows, cols))
if t == 1:
grid_outer = grid
grid_outer = grid|grid_outer
# inner:
t = 0
if len(XY_inner_L) > 0:
for XY in XY_inner_L_upd:
for I in XY:
if len(I) > 0:
t += 1
path = Path(I)
grid = path.contains_points(points)
grid = grid.reshape((rows, cols))
grid = np.invert(grid)
grid_outer *= grid
grid_outer = np.flip(np.flip(grid_outer), axis = 1)
if get_indices:
return grid_outer.astype(int), x_ind[0,:], y_ind[:,0]
else:
return grid_outer.astype(int)
tit = time.time() - t_start
min = int(tit // 60)
sec = int(tit % 60)
print('It took %d minutes and %d seconds to rasterize this tile!' % (min, sec))
def localRasterizeInParallel(XY_exter_L, XY_inner_L = [], generalize_factor=1, get_indices = False):
""" Function to locally rasterize a set of coordinates
@params:
XY_exter_L - Required: List of coordinate pairs of outer bounds
XYs_inner - Optional: List of coordinate pairs lists of inner bounds
generalize_factor - Optional: Factor to determine the degree of generalization"""
# track time
t_start = time.time()
# make sure it can accept both a single coordiante pair list or a list of lists
if len(XY_exter_L[0]) == 2:
XY_exter_L = [XY_exter_L]
if len(XY_inner_L) > 0:
if len(XY_inner_L[0][0]) == 2:
XY_inner_L = [XY_inner_L]
inner_flag = True
else:
for i in range(len(XY_exter_L)):
XY_inner_L.append([])
inner_flag = False
# generalize
XY_exter_L_upd = []
for pol in XY_exter_L:
XY_exter_L_upd.append([])
for x,y in pol:
x = x/generalize_factor
y= y/generalize_factor
XY_exter_L_upd[-1].append((x,y))
XY_exter_L = XY_exter_L_upd
XY_inner_L_upd = []
if len(XY_inner_L) > 0:
for XY_inner in XY_inner_L:
XYs_inner_upd = []
for i in XY_inner:
XYs_inner_upd.append([])
for x, y in i:
x = x / generalize_factor
y = y / generalize_factor
XYs_inner_upd[-1].append((x, y))
XY_inner_L_upd.append(XYs_inner_upd)
XY_inner_L = XY_inner_L_upd
# calculate the real mins and maxs
x_mins, y_mins, x_maxs, y_maxs = [],[],[],[]
for XY_exter in XY_exter_L:
XY_exter_np = np.asarray(XY_exter)
x_mins.append(np.min(XY_exter_np[:, 0]))
x_maxs.append(np.max(XY_exter_np[:, 0]))
y_mins.append(np.min(XY_exter_np[:, 1]))
y_maxs.append(np.max(XY_exter_np[:, 1]))
x_max, y_max, x_min, y_min = np.max(x_maxs), \
np.max(y_maxs), \
np.min(x_mins), \
np.min(y_mins)
# calculate dimensions
cols, rows = int(x_max - x_min), \
int(y_max - y_min)
print('xmax: ', x_max, 'and xmin: ', x_min) ; print('ymax: ', y_max, 'and ymin: ', y_min)
# original indices
xmax_orig = x_max*generalize_factor
ymax_orig = y_max*generalize_factor
xmin_orig = x_min*generalize_factor
ymin_orig = y_min*generalize_factor
x_coordinates = np.hstack((np.arange(xmin_orig, xmax_orig, (xmax_orig-xmin_orig)/cols),xmax_orig))
y_coordinates = np.hstack((np.arange(ymin_orig, ymax_orig, (ymax_orig-ymin_orig)/rows),ymax_orig))
# create list of shapely polygons
Pols = [] ; t = 0
for p in XY_exter_L:
if len(XY_inner_L) > 0:
inter = XY_inner_L[t]
inter = [i for i in inter if len(i) >= 3]
if len(inter) > 0: pol = shPol(p, inter)
else: pol = shPol(p)
Pols.append(pol)
t += 1
MultiPol = shMPol(Pols)
# calculate tile dimensions
width = cols // 4
height = rows // 2
print('width: ', cols , ' & height: ', rows )
lefts, rights = [x_min + i * width for i in range(4)], [1 + x_min + i * width for i in range(1, 4)] + [1 + x_min + 4 * width + cols % 4]
tops, bots = [y_min + i * height for i in range(2)], [y_min + i * height for i in range(1, 2)] + [y_min + 2 * height + rows % 2]
# Cut the polygon into 8 subtiles
ROIs = [] ; Tiles = []
for i in range(4):
for j in range(2):
BL = (lefts[i], bots[j])
TL = (lefts[i], tops[j])
TR = (rights[i], tops[j])
BR = (rights[i], bots[j])
roi = shPol([BL, TL, TR, BR])
tile = MultiPol.intersection(roi)
ROIs.append(roi)
Tiles.append(tile)
print('Lefts: ', lefts) ; print('Rights: ', rights) ; print('Tops: ', tops) ; print('Bots: ', bots)
# clean up tiles:
Tiles_exter = [] ; Tiles_inter = []
for Ti in Tiles:
if type(Ti) == shPoint:
Tiles_exter.append([]) ; Tiles_inter.append([])
elif type(Ti) == shPol:
exter = np.asarray(Ti.exterior.xy).T
Tiles_exter.append([exter])
if len(Ti.interiors) > 0:
inters = Ti.interiors
inter = []
for i in inters:
i = np.asarray(i.xy).T
inter.append(i)
Tiles_inter.append([inter])
else: Tiles_inter.append([])
elif type(Ti) == shMPol:
MPol_list = list(Ti)
Tiles_exter.append([])
Tiles_inter.append([])
for pol in MPol_list:
exter = np.asarray(pol.exterior.xy).T
Tiles_exter[-1].append(exter)
if len(pol.interiors) > 0:
inters = pol.interiors
inter = []
for i in inters:
i = np.asarray(i.xy).T
inter.append(i)
Tiles_inter[-1].append(inter)
else:
Tiles_inter[-1].append([])
else: Tiles_inter[-1].append([]); Tiles_exter.append(exter)
# multiprocess to rasterize all tiles
print('Rasterizing all tiles...')
pool = mp.Pool(int(mp.cpu_count()-2))
print('Inner_flag: ' + str(inner_flag))
print(len(Tiles_exter))
if inner_flag:
Tiles_rasterized = pool.starmap(localRasterize, [(Tiles_exter[i], Tiles_inter[i], 1, False, x_min, x_max, y_min, y_max, True) for i in range(8)])
else: Tiles_rasterized = pool.starmap(localRasterize, [(Tiles_exter[i], [], 1, False, x_min, x_max, y_min, y_max, True) for i in range(8)])
print('Ready! Merging tiles...')
pool.close()
# merge tiles again
Raster = np.sum(np.asarray(Tiles_rasterized), axis = 0)
Raster[Raster > 0] = 1
# print time it took
tit = time.time() - t_start
min = int(tit//60)
sec = int(tit%60)
print('It took %d minutes and %d seconds to rasterize the entire polygon!' % (min, sec))
if get_indices: return(Raster, x_coordinates[:-1], y_coordinates[:-1])
else: return(Raster)
def bwdist(image):
""" function to calculate a distance map of a boolean input map (distance to closest cell with value 1)"""
a = scipy.ndimage.morphology.distance_transform_edt(image==0)
return(a)
def neigh(image):
""" neighboorhood function to calculate number of neighboring cells containing value 1
input has to be boolean"""
# Neighboorhood alternative
dim = image.shape
rows= dim[0]
cols= dim[1]
tif_neigh = np.zeros(dim)
neigh = np.zeros([rows-2,cols-2])
for i in range(0,3):
for j in range(0,3):
neigh = neigh+image[i:i+rows-2,j:j+cols-2]
tif_neigh[1:rows-1,1:cols-1]=neigh
tif_neigh = tif_neigh-image
return(tif_neigh)
def rescale(data,rescale_to):
""" function to rescale linearally"""
rescaled = rescale_to*(data-np.min(data))/(np.max(data)-np.min(data))
return(rescaled)
def exportRaster(LU,Example,Path_Name):
'''
input is a raster file (.rst, .tif), output a 2D array
'''
Example = gdal.Open(Example, gdal.GA_ReadOnly)
gdal.AllRegister()
# get info of example data
rows=Example.RasterYSize
cols=Example.RasterXSize
# create output image
driver=Example.GetDriver()
outDs=driver.Create(Path_Name,cols,rows,1,GDT_Int32)
outBand = outDs.GetRasterBand(1)
outData = np.zeros((rows,cols), np.int16)
# write the data
outBand.WriteArray(LU, 0, 0)
# flush data to disk, set the NoData value and calculate stats
outBand.FlushCache()
outBand.SetNoDataValue(-1)
# georeference the image and set the projection
outDs.SetGeoTransform(Example.GetGeoTransform())
outDs.SetProjection(Example.GetProjection())
del outData
def importRaster(file):
Raster = gdal.Open(file)
Band=Raster.GetRasterBand(1)
Array=Band.ReadAsArray()
return(Raster, Band, Array)
def coorList2Tiles(XY, rxc = [2,4], add_corner = False):
""" Method to divide a list of coordinate pairs into a number of tiles to enable parallel processing
@params:
XY - Required: list of coordinate pairs
rxc - Optional: rows and columns for the tile table
add_corner Optional: add the corner of the tiles as coor pair
"""
pol = shPol(XY)
r,c = rxc
r_per_bots = np.arange(0,100,100/r)
r_per_tops = np.arange(100/r,101,100/r)
c_per_lefts = np.arange(0,100,100/c)
c_per_rights = np.arange(100/c,101,100/c)
XY = np.asarray(XY)
X,Y = XY[:,0], XY[:,1]
lefts, rights = np.percentile(X,c_per_lefts), np.percentile(X,c_per_rights)
bots, tops = np.percentile(Y,r_per_bots), np.percentile(Y,r_per_tops)
rights[-1] += abs(rights[-1])*0.00001 ; tops[-1] += abs(tops[-1])*0.00001
Tiles = []
for i in range(c):
for j in range(r):
mask = (X >= lefts[i])*(X<rights[i]) * (Y >= bots[j])*(Y<tops[j])
XY_tile = XY[mask, :]
Corners = [(lefts[i], tops[j]),
(lefts[i], bots[j]),
(rights[i], tops[j]),
(rights[i], bots[j])];
if add_corner:
Corners_incl = []
for c in Corners:
print(c)
if pol.contains(shPoint(c)):
Corners_incl.append(c)
if len(Corners_incl) > 0:
C = np.asarray(Corners_incl)
print(np.shape(C))
print(np.shape(XY_tile))
XY_tile = np.vstack((XY_tile, C))
Tiles.append(XY_tile)
return Tiles
def image2Blocks(image, vert_n, hor_n, topleftcorners = False):
""" Function to divide a 2d numpy array into blocks
Input: image --> a 2D numpy array
vert_n--> number of blocks in de vertical
hor_n --> number of blocks in the horizontal
Output: Blocks --> list of smaller 2d numpy arrays from the original image
image_blocks --> numpy 2d array with number of block"""
rows, cols = np.shape(image)
Blocks = []
max_row = 0
max_col = 0
t = 1
TL = []
image_blocks = np.zeros(np.shape(image))
for i in range(vert_n + 1):
for j in range(hor_n + 1):
height = rows//vert_n
width = cols//hor_n
top = i*height
bottom = (i+1) * height
left = j*width
right = (j+1) * width
block = image[top:bottom,left:right]
image_blocks[top:bottom,left:right] = t
Blocks.append(block)
t += 1
if bottom > max_row:
max_row = bottom
if right > max_col:
max_col = right
TL.append([top, left])
if topleftcorners:
return Blocks, image_blocks, TL
else:
return Blocks, image_blocks
def blocks2image(Blocks, blocks_image):
""" Function to stitch the blocks back to the original image
input: Blocks --> the list of blocks (2d numpies)
blocks_image --> numpy 2d array with numbers corresponding to block number
output: image --> stitched image """
image = np.zeros(np.shape(blocks_image))
for i in range(1,int(np.max(blocks_image))):
ind = np.asarray(np.where(blocks_image==i))
top = np.min(ind[0, :])
bottom = np.max(ind[0, :])
left = np.min(ind[1, :])
right = np.max(ind[1, :])
#print('top: {}, bottom: {}, left: {}, right: {}'.format(top, bottom, left, right))
image[top:bottom+1,left:right+1] = Blocks[i-1]
return image
def nestedIndicesList(rows, cols):
""" Function to get a two column numpy array with all possible indices of a 2D numpy array
Usage: use to run nested loops in parallel
Input: rows and cols of your 2d array
Output: list with 2x1 numpy arrays"""
ind = np.zeros([rows*cols, 2])
ind[:,0] = np.tile(np.arange(rows), cols)
ind[:,1] = np.repeat(np.arange(cols), rows)
return list(ind)
def retrievePixelValue(geo_coord, image, band):
"""Return floating-point value that corresponds to given point."""
lat = geo_coord[0]
lon = geo_coord[1]
image_np = image.GetRasterBand(band)
image_np = image_np.ReadAsArray()
height = np.shape(image_np)[0]
width = np.shape(image_np)[1]
# the x and y resolution of the pixels, and the rotation of the
# raster.
TL_lon, lon_res, x_rot, TL_lat, lat_rot, lat_res = image.GetGeoTransform()
# calculate coordinates for each cell
CoorRasterLon = (TL_lon + 0.5 * lon_res) + np.arange(width) * lon_res
CoorRasterLat = (TL_lat + 0.5 * lat_res) + np.arange(height) * lat_res
# get indices from lat and lon
j = int(round(((lon - (TL_lon - lon_res / 2)) / lon_res)))
i = int(round(((lat - (TL_lat - lat_res / 2)) / lat_res)))
return image_np[i,j], i, j
def extent2KML(Image,filename):
""" Function to plot the extent of a geotiff """
Band = Image.GetRasterBand(1)
Array = Band.ReadAsArray()
rows, cols = np.shape(Array)
TL_lon, x_res, x_rot, TL_lat, y_rot, y_res = Image.GetGeoTransform()
res = x_res
kml = simplekml.Kml()
pol = kml.newpolygon()
TL = (TL_lon, TL_lat)
BL = (TL_lon, TL_lat - rows*res)
BR = (TL_lon + cols*res, TL_lat - rows*res)
TR = (TL_lon + cols*res, TL_lat)
pol.outerboundaryis = [TL,BL,BR,TR,TL]
kml.save(filename)
def contourKML(Image,cn,filename,minlen = 100):
""" Function to generate a kml file with contours from a certain raster
@params:
the gdal image, a plt.contour output, the filename of the eventual kml file,
the minimum length of a contour (unit is number of nodes) and color for the eventual
kml lines (html color codes) """
c_coor = cn.allsegs[0]
latlon = Indices2LatLon(Image)
kml = simplekml.Kml()
Contour_latlon = []
Contour_latlon.append([])
t = 0
for c_list in c_coor:
if t%1000 == 0:
print('Super Process:' +str(round(t/len(c_coor),2)*100)+ ' %')
t += 1
f = True
if len(c_list) > minlen:
for c in c_list:
y = c[1]
x = c[0]
try:
lat = latlon[int(round(y)), int(round(x)), 0]
lon = latlon[int(round(y)), int(round(x)), 1]
if f == True:
Contour_latlon[-1].append((lon, lat))
f = False
else:
lon_old,lat_old = Contour_latlon[-1][-1]
dist = ((lon_old-lon)**2+(lat_old-lat)**2)**0.5
if dist < 0.0005:
Contour_latlon[-1].append((lon, lat))
else:
Contour_latlon.append([])
Contour_latlon[-1].append((lon, lat))
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
for C in Contour_latlon:
l = kml.newlinestring()
l.name = str(t)
l.coords = C
print('Saving file...')
kml.save(filename)
def calcPolyArea(pol):
""" Function to calculate the area (units = cells) of a polygon
input: a numpy array with two cols
output: the area in number of cells """
x = pol[:,0]
y = pol[:,1]
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
def autoCanny(image, sigma=0.33):
""" Function to use canny without tuning (source: pyimagesearch.com) """
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
# return the edged image
return edged
def shapelyPol2PLTPol(shapelypol, facecolor = 'grey', edgecolor = 'red', alpha = 0.5):
""" Function to translate a shapely polygon to a plt polygon
!!! so far only for exterior boundaries
input: a shapely polygon
output: a patch to be plotted with plt.add_patch"""
# get coordinate list
C = np.rot90(shapelypol.exterior.xy)
# create a polygon from coordinate list
pol = Polygon(C, closed=True, facecolor = facecolor, edgecolor = edgecolor, alpha = alpha) # plt polygon
return pol
def printProgressBar(iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
source: https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
# Print New Line on Complete
if iteration == total:
print()
def shapelyInd2shapelyLatLon(pol, latlon, indlist = False):
ind = np.asarray(pol.exterior.xy)
ind_latlon = []
for i in range(np.shape(ind)[1]):
col = int(ind[0, i])
row = int(ind[1, i])
ind_latlon.append(latlon[row,col,:])
if indlist:
return shPol(ind_latlon), ind_latlon
else:
return shPol(ind_latlon)
def shapely2KML(pol_ext, path, pol_int = [], name = '', invert = False):
""" Funtion to translate shapely polygons to kml polygon
@ params:
pol_ext - Required: shapely polygon in lat and lon of the exterior boundaries
path - Required: DIrectory path or file name (stored in working directory) of the kml file
pol_int - Optional: List of shapely polygons which describe the interior boundaries
name - Optional: String of the name of the polygon
invert - Optional: trun on True to change x and y
"""
kml = simplekml.Kml()
xy = np.asarray(pol_ext.exterior.xy)
xy = np.rot90(xy)
if invert == False:
xy = list(np.flip(xy))
xy_int = []
for i in pol_int:
xy_i = list(np.flip(np.rot90(np.asarray(i.exterior.xy))))
xy_int.append(xy_i)
pol = kml.newpolygon(name = name, outerboundaryis = xy, innerboundaryis = xy_int)
pol.style.polystyle.color = simplekml.Color.changealphaint(50, simplekml.Color.azure)
kml.save(path)
print(f'The Google Earth File is saved in {path}')
def extractPolygon2Snap2FromNDVI(NDVI, LatLon, NDVI_tresh = 0, path = 'Polygon2Snap2.kml'):
""" Function to extract Polygon2Snap2 from a NDVI image
@params:
NDVI - Required: 2d numpy array of NDVI
LatLon - Required: 3d (rowsxcolsx2) numpy array with latitudes and longitudes of the NDVI image
NDVI_tresh - Optional: value to distinguish water from non water (default is 0)
path - Optional: path to store the resulting kml file (default is 'Polygon2Snap2.kml')
"""
# Close all open figures
plt.close('all')
# treshold value to distinguish water based on NDVI
t = NDVI_tresh
Tresh = np.zeros(np.shape(NDVI))
# apply filter to cancel noise without affecting edges
blur = cv2.bilateralFilter(NDVI, 3, 5, 5)
# make a binary image
(t, binary) = cv2.threshold(src=blur * -1,
thresh=t,
maxval=255,
type=cv2.THRESH_BINARY)
# convert to proper data type
binary = np.uint8(binary)
# contour
contours = cv2.findContours(image=binary, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0]
contours_len = []
print("Found %d objects." % len(contours))
# list how long each contour is
for (i, c) in enumerate(contours):
contours_len.append(len(c))
# print("\tSize of contour %d: %d" % (i, len(c)))
# create empty lists to store the polygons
patches = []
sh_Pols = []
# minimum length of contour to generate polygon
tresh = 100
# generate polygons
t = 0
print('Generating Polygons...')
for C in contours:
t += 1
printProgressBar(t, len(contours))
if len(C) > tresh:
# adapt the dimensions
C = C[:, 0, :]
# create a polygon
pol = Polygon(C, closed=True, facecolor='red', edgecolor='red', alpha=0.05) # plt polygon
patches.append(pol)
shpol = shPol(C) # shapely polygon
if type(shpol.buffer(0)) is shPol:
if shpol.buffer(0).length > tresh:
sh_Pols.append(shpol.buffer(0))
else:
for s in list(shpol.buffer(0)):
if s.length > tresh:
sh_Pols.append(s)
# get the major polygon
sh_Pols_len = []
for s in sh_Pols:
sh_Pols_len.append(s.length)
C_maj = sh_Pols[np.argmax(sh_Pols_len)]
# get the interiors
interiors = []
t = 0
print('Getting the interior boundaries...')
for c in sh_Pols:
#print("\tSize of contour %d: %d" % (i, c.length))
t += 1
printProgressBar(t,len(sh_Pols))
if c.within(C_maj):
if c.area < C_maj.area:
interiors.append(c)
"""
print('Getting the interior boundaries...')
def checkWithin(c, C_maj):
if c.within(C_maj):
if c.area < C_maj.area:
return c
pool = mp.Pool(mp.cpu_count())
interiors = pool.starmap(checkWithin, [(c, C_maj) for c in sh_Pols])
"""
interiors = [i for i in interiors if i]
print(f'Got them! There are {len(interiors)} interior polygons')
# translate to latlon
interiors_latlon = []
for i in interiors:
pol_latlon = shapelyInd2shapelyLatLon(i, LatLon)
interiors_latlon.append(pol_latlon)
pol_maj_latlon = shapelyInd2shapelyLatLon(C_maj, LatLon)
shapely2KML(pol_maj_latlon, pol_int=interiors_latlon, path=path, name='test')
def indices2LatLon(Image):
""" Function to calculate a 2D numpy array which hold latitude and longitude in each cell
input: gdal loaded geotiff
output: 2D numpy array with lat-lon for each cell"""
Band=Image.GetRasterBand(1)
Array=Band.ReadAsArray()
rows, cols = np.shape(Array)
TL_lon, x_res, x_rot, TL_lat, y_rot, y_res = Image.GetGeoTransform()
res = x_res
latlon = np.zeros([rows,cols,2])
for i in range(rows):
printProgressBar(i,rows)
for j in range(cols):
lat = TL_lat - i*res
lon = TL_lon + j*res
latlon[i,j,0] = lat
latlon[i,j,1] = lon
return latlon
def shapely2KML_MultiplePolygons(Pol_list, path, invert = False):
""" Funtion to translate shapely polygons to kml polygon
@ params:
pol_list_element - Required: list of lists where the first element of each list is the outerboundaries of a polygon
path - Required: DIrectory path or file name (stored in working directory) of the kml file
invert - Optional: trun on True to change x and y
"""
def savePolList(p, pol, xy, kml, xy_init):
inxy = np.asarray(pol_list_element[p].exterior.xy)
inxy = np.rot90(inxy)
inxy = list(np.flip(inxy))
xy_init.append(inxy)
pol = kml.newpolygon(outerboundaryis=xy, innerboundaryis=xy_init)
pol.style.polystyle.color = simplekml.Color.changealphaint(50, simplekml.Color.azure)
kml = simplekml.Kml()
i = 0
for pol_list_element in Pol_list:
xy = np.asarray(pol_list_element[0].exterior.xy)
xy = np.rot90(xy)
if invert == False:
xy = list(np.flip(xy))
if len(pol_list_element) == 1: