-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdemo_preprocess_height_v2.py
More file actions
1986 lines (1773 loc) · 74.9 KB
/
demo_preprocess_height_v2.py
File metadata and controls
1986 lines (1773 loc) · 74.9 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
'''
function: convert all building height in vector to raster format at 2.5 m
update: should be consistent with CNBH 10m dataset, 2023.10.6
'''
import cv2
import numpy as np
import os
import shutil
from osgeo import gdal, ogr, osr, gdalconst
import datetime
from xpinyin import Pinyin
from time import time
from pathlib import Path
import math
from glob import glob
import sys
import numpy
import rasterio
from mask_revised import mask
import geopandas as gpd
from tqdm import tqdm
import pandas as pd
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
import matplotlib
def shp_to_tiff(shp_file, output_tiff, attribute='class', nresolution=2.5):
"""
:param shp_file:
:param output_tiff:
:param attribute: 定义栅格值的矢量属性
:return:
"""
start_time = datetime.datetime.now()
print("start :" + str(start_time))
# 读取shp文件
driver = ogr.GetDriverByName("ESRI Shapefile")
data_source = driver.Open(shp_file, 1)
# 获取图层文件对象
shp_layer = data_source.GetLayer()
lon_min, lon_max, lat_min, lat_max = shp_layer.GetExtent()
s_projection = str(shp_layer.GetSpatialRef())
# (0,0,:,0,:,0)表示旋转系数
# 自定义仿射矩阵系数 , 1表示分辨率大小,决定了栅格像元的大小
dst_transform = (lon_min, nresolution, 0, lat_max, 0, -nresolution)
d_lon = int(abs((lon_max - lon_min) / dst_transform[1])) # 除以横向分辨率
d_lat = int(abs((lat_max - lat_min) / dst_transform[5]))
# 根据模板tif属性信息创建对应标准的目标栅格
target_ds = gdal.GetDriverByName('GTiff').Create(output_tiff, d_lon, d_lat, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform(dst_transform)
target_ds.SetProjection(s_projection)
band = target_ds.GetRasterBand(1)
# 设置背景数值
NoData_value = 0
band.SetNoDataValue(NoData_value)
band.FlushCache()
# 调用栅格化函数。gdal.RasterizeLayer函数有四个参数,分别有栅格对象,波段,矢量对象,value的属性值将为栅格值
option = ['ATTRIBUTE=%s' % (attribute)]
gdal.RasterizeLayer(target_ds, [1], shp_layer, options=option)
# 直接写入
y_buffer = band.ReadAsArray()
target_ds.WriteRaster(0, 0, d_lon, d_lat, y_buffer.tobytes())
start_time = datetime.datetime.now()
print("end :" + str(start_time))
target_ds = None # todo 释放内存,只有强制为None才可以释放干净
del target_ds, shp_layer
def get_tif_meta(tif_path):
dataset = gdal.Open(tif_path)
# 栅格矩阵的列数
width = dataset.RasterXSize
# 栅格矩阵的行数
height = dataset.RasterYSize
# 获取仿射矩阵信息
geotrans = dataset.GetGeoTransform()
# 获取投影信息
proj = dataset.GetProjection()
# close dataset
dataset = None
return width, height, geotrans, proj
def shp2tif(shp_path, refer_tif_path, target_tif_path, attribute_field="class", nodata_value=0):
width, height, geotrans, proj = get_tif_meta(refer_tif_path)
# 读取shp文件
shp_file = ogr.Open(shp_path)
# 获取图层文件对象
shp_layer = shp_file.GetLayer()
# 创建栅格
target_ds = gdal.GetDriverByName('GTiff').Create(
utf8_path=target_tif_path, # 栅格地址
xsize=width, # 栅格宽
ysize=height, # 栅格高
bands=1, # 栅格波段数
eType=gdal.GDT_Byte # 栅格数据类型
)
# 将参考栅格的仿射变换信息设置为结果栅格仿射变换信息
target_ds.SetGeoTransform(geotrans)
# 设置投影坐标信息
target_ds.SetProjection(proj)
band = target_ds.GetRasterBand(1)
# 设置背景nodata数值
band.SetNoDataValue(nodata_value)
band.FlushCache()
# 栅格化函数
gdal.RasterizeLayer(
dataset=target_ds, # 输出的栅格数据集
bands=[1], # 输出波段
layer=shp_layer, # 输入待转换的矢量图层
options=[f"ATTRIBUTE={attribute_field}"] # 指定字段值为栅格值
)
target_ds = None # todo 释放内存,只有强制为None才可以释放干净
del target_ds
def addField_byExpression(shp_file, newFieldName='FloorNum', oldFieldName='elevation'):
# from osgeo import ogr
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open(shp_file, 1) # 1 is read/write
layer = dataSource.GetLayer()
defn = layer.GetLayerDefn()
fieldIndex = defn.GetFieldIndex(newFieldName)
if fieldIndex < 0:
# define floating point field named DistFld and 16-character string field named Name:
fldDef = ogr.FieldDefn(newFieldName, ogr.OFTInteger)
# fldDef2 = ogr.FieldDefn('Name', ogr.OFTString)
# fldDef2.SetWidth(16) # 16 char string width
layer.CreateField(fldDef)
fieldIndex2 = defn.GetFieldIndex(newFieldName)
if fieldIndex2>0:
print('create success!')
# field expression
feature = layer.GetNextFeature()
indexA = defn.GetFieldIndex(oldFieldName)
indexB = defn.GetFieldIndex(newFieldName)
oField = defn.GetFieldDefn(indexB)
fieldName = oField.GetNameRef()
while feature is not None:
valueA = feature.GetFieldAsInteger(indexA) #
if valueA is None:
feature.SetFieldNull(indexB)
continue
feature.SetField2(fieldName, valueA/3) # floor number
layer.SetFeature(feature)
feature = layer.GetNextFeature()
# feature.Destroy()
del layer, dataSource
# fishgrid
def Fishgrid(outfile, xmin, xmax, ymin, ymax, gridwidth, gridheight,
geoproj):
#参数转换到浮点型
xmin = float(xmin)
xmax = float(xmax)
ymin = float(ymin)
ymax = float(ymax)
gridwidth = float(gridwidth)
gridheight = float(gridheight)
#计算行数和列数
rows = math.ceil((ymax-ymin)/gridheight)
cols = math.ceil((xmax-xmin)/gridwidth)
#初始化起始格网四角范围
ringXleftOrigin = xmin
ringXrightOrigin = xmin+gridwidth
ringYtopOrigin = ymax
ringYbottomOrigin = ymax-gridheight
#创建输出文件
outdriver = ogr.GetDriverByName('ESRI Shapefile')
if os.path.exists(outfile):
outdriver.DeleteDataSource(outfile)
outds = outdriver.CreateDataSource(outfile)
# create the spatial reference system, WGS84
srs = osr.SpatialReference(wkt=geoproj)
# srs.ImportFromEPSG(4326)
outlayer = outds.CreateLayer(outfile, srs, geom_type = ogr.wkbPolygon)
#不添加属性信息,获取图层属性
outfielddefn = outlayer.GetLayerDefn()
#遍历列,每一列写入格网
col = 0
while col<cols:
#初始化,每一列写入完成都把上下范围初始化
ringYtop = ringYtopOrigin
ringYbottom = ringYbottomOrigin
#遍历行,对这一列每一行格子创建和写入
row = 0
while row<rows:
#创建左上角第一个格子
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(ringXleftOrigin,ringYtop)
ring.AddPoint(ringXrightOrigin,ringYtop)
ring.AddPoint(ringXrightOrigin,ringYbottom)
ring.AddPoint(ringXleftOrigin,ringYbottom)
ring.CloseRings()
#写入几何多边形
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
#创建要素,写入多边形
outfeat = ogr.Feature(outfielddefn)
outfeat.SetGeometry(poly)
#写入图层
outlayer.CreateFeature(outfeat)
outfeat = None
#下一多边形,更新上下范围, 向下移动
row+=1
ringYtop = ringYtop - gridheight
ringYbottom = max(ymin, ringYbottom-gridheight) # boundary
#一列写入完成后,下一列,更新左右范围, 向右移动
col+=1
ringXleftOrigin = ringXleftOrigin+gridwidth
ringXrightOrigin = min(xmax, ringXrightOrigin+gridwidth) # boundary
#写入后清除缓存
outds = None
outlayer = None
def Fishgridnew(tif_path, window_size=256):
idir = os.path.dirname(tif_path)
iname = os.path.basename(tif_path)[:-4]
outfile = os.path.join(idir, iname + '_grid.shp')
width, height, geotrans, geoproj = get_tif_meta(tif_path)
xres = geotrans[1]
yres = geotrans[5]
xmin = geotrans[0] # top left x
ymax = geotrans[3] # top left y
xmax = xmin + xres * width
ymin = ymax + yres * height
grid_size = int(window_size * xres)
#参数转换到浮点型
xmin = float(xmin)
xmax = float(xmax)
ymin = float(ymin)
ymax = float(ymax)
gridwidth = float(grid_size)
gridheight = float(grid_size)
#计算行数和列数
rows = math.ceil((ymax-ymin)/gridheight)
cols = math.ceil((xmax-xmin)/gridwidth)
#初始化起始格网四角范围
ringXleftOrigin = xmin
ringXrightOrigin = xmin+gridwidth
ringYtopOrigin = ymax
ringYbottomOrigin = ymax-gridheight
#创建输出文件
outdriver = ogr.GetDriverByName('ESRI Shapefile')
if os.path.exists(outfile):
outdriver.DeleteDataSource(outfile)
outds = outdriver.CreateDataSource(outfile)
# create the spatial reference system, WGS84
srs = osr.SpatialReference(wkt=geoproj)
# srs.ImportFromEPSG(4326)
outlayer = outds.CreateLayer(outfile, srs, geom_type = ogr.wkbPolygon)
#不添加属性信息,获取图层属性
outfielddefn = outlayer.GetLayerDefn()
#遍历列,每一列写入格网
col = 0
while col<cols:
#初始化,每一列写入完成都把上下范围初始化
ringYtop = ringYtopOrigin
ringYbottom = ringYbottomOrigin
#遍历行,对这一列每一行格子创建和写入
row = 0
while row<rows:
#创建左上角第一个格子
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(ringXleftOrigin,ringYtop)
ring.AddPoint(ringXrightOrigin,ringYtop)
ring.AddPoint(ringXrightOrigin,ringYbottom)
ring.AddPoint(ringXleftOrigin,ringYbottom)
ring.CloseRings()
#写入几何多边形
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
#创建要素,写入多边形
outfeat = ogr.Feature(outfielddefn)
outfeat.SetGeometry(poly)
#写入图层
outlayer.CreateFeature(outfeat)
outfeat = None
#下一多边形,更新上下范围, 向下移动
row+=1
ringYtop = ringYtop - gridheight
ringYbottom = max(ymin, ringYbottom-gridheight) # boundary
#一列写入完成后,下一列,更新左右范围, 向右移动
col+=1
ringXleftOrigin = ringXleftOrigin+gridwidth
ringXrightOrigin = min(xmax, ringXrightOrigin+gridwidth) # boundary
#写入后清除缓存
outds = None
outlayer = None
def Raster_extent(filelist, outfile,
locName='location', locType=ogr.OFTString,
yearName='2020'):
# Create the output shapefile
shpDriver = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(outfile):
shpDriver.DeleteDataSource(outfile)
outDataSource = shpDriver.CreateDataSource(outfile)
# Set the spatial reference
_, _, _, proj = get_tif_meta(filelist[0])
srs = osr.SpatialReference(wkt=proj)
basename = os.path.basename(outfile)[:-4]
outlayer = outDataSource.CreateLayer(basename, srs, geom_type=ogr.wkbPolygon)
# Create fields
outlayer.CreateField(ogr.FieldDefn(locName, locType))
outlayer.CreateField(ogr.FieldDefn(yearName, ogr.OFTInteger64))
# Loop over all rasters
for file in filelist:
width, height, geotrans, proj = get_tif_meta(file)
filename = os.path.basename(file)
filename = filename.split('_')
year = filename[1]
loc = filename[2]+'_'+filename[3]
xres = geotrans[1]
yres = geotrans[5]
xmin = geotrans[0] # top left x
ymax = geotrans[3] # top left y
xmax = xmin + xres*width
ymin = ymax + yres*height
# 创建左上角第一个格子
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(xmin, ymax) # top left
ring.AddPoint(xmax, ymax) # top right
ring.AddPoint(xmax, ymin) # down right
ring.AddPoint(xmin, ymin) # down left
ring.CloseRings()
# 写入几何多边形
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
# 创建要素,写入多边形
outfeat = ogr.Feature(outlayer.GetLayerDefn())
outfeat.SetGeometry(poly)
outfeat.SetField(locName, loc)
outfeat.SetField(yearName, year)
# Create the feature in the layer (shapefile)
outlayer.CreateFeature(outfeat)
# Dereference the featur
outfeat = None
# Save and close the data source
outDataSource = None
# 2023.9.28: need reproject all images to the same projection
def Raster_extent_prj(filelist, outfile,
locName='location', locType=ogr.OFTString,
yearName='2020',
target_crs=4326):
# Create the output shapefile
shpDriver = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(outfile):
shpDriver.DeleteDataSource(outfile)
outDataSource = shpDriver.CreateDataSource(outfile)
# Set the spatial reference
# if target_crs==None:
_, _, _, proj = get_tif_meta(filelist[0])
targetSR = osr.SpatialReference(wkt=proj)
# else:
# create the spatial reference, WGS84
# targetSR = osr.SpatialReference()
# targetSR.ImportFromEPSG(target_crs)
basename = os.path.basename(outfile)[:-4]
outlayer = outDataSource.CreateLayer(basename, targetSR, geom_type=ogr.wkbPolygon)
# Create fields
outlayer.CreateField(ogr.FieldDefn(locName, locType))
outlayer.CreateField(ogr.FieldDefn(yearName, ogr.OFTInteger64))
# Loop over all rasters
for file in filelist:
print(file)
width, height, geotrans, proj = get_tif_meta(file)
filename = os.path.basename(file)[:-4]
filename = filename.split('_')
year = '2020' # filename[1]
loc = filename[1] # filename[2]+'_'+filename[3]
# Reproject vector geometry to same projection as raster
sourceSR = osr.SpatialReference(wkt=proj)
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
xres = geotrans[1]
yres = geotrans[5]
xmin = geotrans[0] # top left x
ymax = geotrans[3] # top left y
xmax = xmin + xres*width
ymin = ymax + yres*height
# 创建左上角第一个格子
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(xmin, ymax) # top left
ring.AddPoint(xmax, ymax) # top right
ring.AddPoint(xmax, ymin) # down right
ring.AddPoint(xmin, ymin) # down left
ring.CloseRings()
# 写入几何多边形
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
poly.Transform(coordTrans)
# 创建要素,写入多边形
outfeat = ogr.Feature(outlayer.GetLayerDefn())
outfeat.SetGeometry(poly)
outfeat.SetField(locName, loc)
outfeat.SetField(yearName, year)
# Create the feature in the layer (shapefile)
outlayer.CreateFeature(outfeat)
# Dereference the feature
outfeat = None
# Save and close the data source
outDataSource = None
# def Zone_stats(raster_file, shp_file, fieldName='area', fieldType=ogr.OFTReal):
# width, height, geotrans, proj = get_tif_meta(raster_file)
# # Create the output shapefile
# shpDriver = ogr.GetDriverByName("ESRI Shapefile")
# dataSource = shpDriver.Open(shp_file, 1) # 1 is read/write
# shplayer = dataSource.GetLayer()
# # Create the field
# defn = shplayer.GetLayerDefn()
# if defn.GetFieldIndex(fieldName) == -1:
# shplayer.CreateField(ogr.FieldDefn(fieldName, fieldType))
# # Statistics for each raster
# for feature in shplayer:
# value =
# feature.SetField(fieldName, value)
# shplayer.SetFeature(feature)
#
# # Close
# dataSource = None
def zonal_stats(input_zone_polygon, input_value_raster, fieldName=('sum','count'),
fieldType=ogr.OFTInteger64):
# Open data
raster = gdal.Open(input_value_raster)
shp = ogr.Open(input_zone_polygon, 1) # 1 read & write
lyr = shp.GetLayer()
# Create field
defn = lyr.GetLayerDefn()
for ifield in fieldName:
if defn.GetFieldIndex(ifield) == -1:
lyr.CreateField(ogr.FieldDefn(ifield, fieldType))
# Get raster georeference info
transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]
# Reproject vector geometry to same projection as raster
sourceSR = lyr.GetSpatialRef()
targetSR = osr.SpatialReference()
targetSR.ImportFromWkt(raster.GetProjectionRef())
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
sumstats=[]
countstats=[]
# feat = lyr.GetNextFeature() # the first feature
for feat in lyr:
geom = feat.GetGeometryRef()
geom.Transform(coordTrans)
# Get extent of feat
geom = feat.GetGeometryRef()
if (geom.GetGeometryName() == 'MULTIPOLYGON'):
count = 0
pointsX = []; pointsY = []
for polygon in geom:
geomInner = geom.GetGeometryRef(count)
ring = geomInner.GetGeometryRef(0)
numpoints = ring.GetPointCount()
for p in range(numpoints):
lon, lat, z = ring.GetPoint(p)
pointsX.append(lon)
pointsY.append(lat)
count += 1
elif (geom.GetGeometryName() == 'POLYGON'):
ring = geom.GetGeometryRef(0)
numpoints = ring.GetPointCount()
pointsX = []; pointsY = []
for p in range(numpoints):
lon, lat, z = ring.GetPoint(p)
pointsX.append(lon)
pointsY.append(lat)
else:
sys.exit("ERROR: Geometry needs to be either Polygon or Multipolygon")
xmin = min(pointsX)
xmax = max(pointsX)
ymin = min(pointsY)
ymax = max(pointsY)
# Specify offset and rows and columns to read
xoff = int((xmin - xOrigin)/pixelWidth)
yoff = int((yOrigin - ymax)/pixelWidth)
xcount = int((xmax - xmin)/pixelWidth) # +1
ycount = int((ymax - ymin)/pixelWidth) # +1
# Create memory target raster
target_ds = gdal.GetDriverByName('MEM').Create('', xcount, ycount, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((
xmin, pixelWidth, 0,
ymax, 0, pixelHeight,
))
target_ds.SetProjection(raster.GetProjectionRef())
# Create memory target vector layer
shp_name = 'temp'
mem_driver = ogr.GetDriverByName("Memory")
if os.path.exists(shp_name):
mem_driver.DeleteDataSource(shp_name)
shp_ds = mem_driver.CreateDataSource(shp_name)
target_lyr = shp_ds.CreateLayer('polygons', targetSR, ogr.wkbPolygon)
target_lyr.CreateFeature(feat.Clone())
# Create for target raster the same projection as for the value raster
# raster_srs = osr.SpatialReference()
# raster_srs.ImportFromWkt(raster.GetProjectionRef())
# target_ds.SetProjection(raster_srs.ExportToWkt())
# Rasterize zone polygon to raster
gdal.RasterizeLayer(target_ds, [1], target_lyr, burn_values=[1])
# Read raster as arrays, grid from the original raster
banddataraster = raster.GetRasterBand(1)
dataraster = banddataraster.ReadAsArray(xoff, yoff, xcount, ycount).astype(numpy.float64)
bandmask = target_ds.GetRasterBand(1)
datamask = bandmask.ReadAsArray(0, 0, xcount, ycount).astype(numpy.float64)
# Mask zone of raster
zoneraster = numpy.ma.masked_array(dataraster, numpy.logical_not(datamask))
zoneraster_foot = (zoneraster>0).astype(numpy.uint8)
# Set field
feat.SetField2(fieldName[0], zoneraster_foot.sum())
feat.SetField2(fieldName[1], zoneraster.count())
lyr.SetFeature(feat)
# sumstats.append(zoneraster.sum())
# countstats.append(zoneraster.count())
# Close
target_ds = None
target_lyr = None
shp_ds = None
shp = None
lyr = None
raster = None
return True
# def loop_zonal_stats(input_zone_polygon, input_value_raster):
#
# shp = ogr.Open(input_zone_polygon)
# lyr = shp.GetLayer()
# featList = range(lyr.GetFeatureCount())
# statDict = {}
#
# for FID in featList:
# feat = lyr.GetFeature(FID)
# meanValue = zonal_stats(feat, input_zone_polygon, input_value_raster)
# statDict[FID] = meanValue
# return statDict
def merge_alltif(imglist, outfile, srcNodata=0, VRTNodata=0):
tifs = imglist # [:10]
t0 = time()
iroot = os.path.dirname(outfile)
iname = os.path.basename(outfile)
if '.' in iname:
iname = iname[:-4]+'.vrt'
else:
iname = iname+'.vrt'
vrt_file = os.path.join(iroot, iname)
# tif_file = os.path.join(iroot, iname+'.tif')
gdal.BuildVRT(vrt_file, tifs,
options=gdal.BuildVRTOptions(srcNodata=srcNodata,
VRTNodata=VRTNodata)) #options=gdal.BuildVRTOptions()srcNodata=0, VRTNodata=0))
# ds = gdal.Open(vrt_file)
# translateoptions = gdal.TranslateOptions(
# gdal.ParseCommandLine("-of GTiff -ot Byte -co COMPRESS=LZW -a_nodata 255"))
# gdal.Translate(tif_file, ds, options=translateoptions)
print('time elaps: %.2f' % (time() - t0))
ds = None
def clip_vrt(vrt_file, shp_file, out_file, proj,
fieldname=('vrt_sum', 'vrt_count'), nresolution=2.5):
# raster = gdal.Open(vrt_file, gdal.GA_ReadOnly) # read raster
VectorDriver = ogr.GetDriverByName('ESRI Shapefile') # intialize vector
VectorDataset = VectorDriver.Open(shp_file, 1)
lyr = VectorDataset.GetLayer()
sourceSR = lyr.GetSpatialRef()
targetSR = osr.SpatialReference(wkt=proj)
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
# Create field
defn = lyr.GetLayerDefn()
for ifield in fieldname:
if defn.GetFieldIndex(ifield) == -1:
lyr.CreateField(ogr.FieldDefn(ifield, ogr.OFTInteger64))
# feature = lyr.GetNetFeature() # select the first polygon (the circle shown in image)
# Loop over all
num_feature = lyr.GetFeatureCount()
for i in range(num_feature):
feature = lyr.GetNextFeature()
geom = feature.GetGeometryRef()
geom.Transform(coordTrans)
# Get extent of feat
minX, maxX, minY, maxY = geom.GetEnvelope()
# Clip & warp the original images
out_file = out_file[:-4]+'.vrt'
OutTile = gdal.Warp(out_file, vrt_file, format='VRT',
outputBounds=[minX, minY, maxX, maxY],
xRes=nresolution, yRes=nresolution,
dstSRS=proj)
OutTile = None
out_source = gdal.Open(out_file, 0)
out_data = out_source.GetRasterBand(1)
out_data = out_data.ReadAsArray()
out_data = (out_data==255).astype(numpy.uint8)
feature.SetField2(fieldname[0], out_data.sum())
feature.SetField2(fieldname[1], out_data.size)
lyr.SetFeature(feature)
out_source = None
VectorDataset = None
lyr = None
# compare two tiff images using the same shp_file
def compare_twotiff(tif_file1, tif_file2, shp_file, target_proj,
fieldname=('sum', 'count', 'vrt_sum', 'vrt_count', 'absdiff'),
nresolution=2.5,
condition=(0, 0)):
# Vector
VectorDriver = ogr.GetDriverByName('ESRI Shapefile') # intialize vector
VectorDataset = VectorDriver.Open(shp_file, 1) # read & write
lyr = VectorDataset.GetLayer()
# Coordinate transformation to the same projection
sourceSR = lyr.GetSpatialRef()
targetSR = osr.SpatialReference(wkt=target_proj)
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
# Create field
defn = lyr.GetLayerDefn()
for ifield in fieldname:
if defn.GetFieldIndex(ifield) == -1:
lyr.CreateField(ogr.FieldDefn(ifield, ogr.OFTInteger64))
# feature = lyr.GetNetFeature() # select the first polygon (the circle shown in image)
# Loop over all
for feature in lyr:
# feature = lyr.GetNextFeature()
# Tif 1
geom = feature.GetGeometryRef()
geom.Transform(coordTrans)
minX, maxX, minY, maxY = geom.GetEnvelope() # get the extent
# Clip & warp the original images
OutTile2 = gdal.Warp("tmp1.vrt", tif_file1, format='VRT',
outputBounds=[minX, minY, maxX, maxY],
xRes=nresolution, yRes=nresolution,
dstSRS=target_proj)
out_data1 = OutTile2.GetRasterBand(1)
out_data1 = out_data1.ReadAsArray()
out_data1 = (out_data1>condition[0]).astype(numpy.uint8)
OutTile2 = None
# Tif 2
# geom = feature.GetGeometryRef()
# geom.Transform(coordTrans)
# minX, maxX, minY, maxY = geom.GetEnvelope() # get the extent
# Clip & warp the original images
OutTile = gdal.Warp("tmp2.vrt", tif_file2, format='VRT',
outputBounds=[minX, minY, maxX, maxY],
xRes=nresolution, yRes=nresolution,
dstSRS=target_proj)
out_data2 = OutTile.GetRasterBand(1)
out_data2 = out_data2.ReadAsArray()
out_data2 = (out_data2>condition[1]).astype(numpy.uint8)
OutTile = None
# Absolute difference: check dimension
if out_data1.shape == out_data2.shape:
diff = ((out_data1 -out_data2)!=0).astype('uint8')
diff = diff.sum()
else:
diff = 65536 # means delete
# Create fields: sum & count
feature.SetField2(fieldname[0], out_data1.sum())
feature.SetField2(fieldname[1], out_data1.size)
feature.SetField2(fieldname[2], out_data2.sum())
feature.SetField2(fieldname[3], out_data2.size)
feature.SetField2(fieldname[4], diff)
lyr.SetFeature(feature)
# out_source = None
feature = None
# Close dataset
VectorDataset = None
lyr = None
def calculate_iou(gt_mask, pred_mask):
overlap = pred_mask * gt_mask # Logical AND
union = (pred_mask + gt_mask)>0 # Logical OR
iou = overlap.sum() / float(union.sum())
return iou
# compare two tiff images using the same shp_file
def compare_twotiff_valid(tif_ref, vrt_file, shp_file,
fieldname=('vrt_sum', 'vrt_count', 'absdiff'),
validname=('isv', 'isv2', 'isv3', 'isv4'),
nresolution=2.5,
condition=(0, 2000, 65536, 0.3)):
# Vector
VectorDriver = ogr.GetDriverByName('ESRI Shapefile') # intialize vector
VectorDataset = VectorDriver.Open(shp_file, 1) # read & write
lyr = VectorDataset.GetLayer()
# Referenced tif
raster = gdal.Open(tif_ref)
target_proj = raster.GetProjectionRef()
rasterband = raster.GetRasterBand(1)
transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = -transform[5]
# Coordinate transformation to the same projection
sourceSR = lyr.GetSpatialRef()
targetSR = osr.SpatialReference(wkt=target_proj)
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
# Create field
defn = lyr.GetLayerDefn()
for ifield in fieldname+validname:
if defn.GetFieldIndex(ifield) == -1:
lyr.CreateField(ogr.FieldDefn(ifield, ogr.OFTInteger64))
index_isv = defn.GetFieldIndex(validname[0])
# feature = lyr.GetNetFeature() # select the first polygon (the circle shown in image)
# Loop over all
for feature in lyr:
# feature = lyr.GetNextFeature()
# Check if the feature is valid (e.g., meet the condition 1)
value_isv = feature.GetFieldAsInteger(index_isv)
if value_isv == 0:
continue
geom = feature.GetGeometryRef()
geom.Transform(coordTrans)
minX, maxX, minY, maxY = geom.GetEnvelope() # get the extent
# Tif 1: the reference file
# Specify offset and rows and columns to read
xoff = int((minX - xOrigin)/pixelWidth)
yoff = int((yOrigin - maxY)/pixelHeight)
xcount = int((maxX - minX)/pixelWidth) # +1
ycount = int((maxY - minY)/pixelHeight) # +1
out_data1 = rasterband.ReadAsArray(xoff, yoff, xcount, ycount).astype(numpy.uint8)
out_data1 = (out_data1>condition[0]).astype(numpy.uint8)
#Tif 2: Clip & warp the reference images
OutTile2 = gdal.Warp("tmp.vrt", vrt_file, format='VRT',
outputBounds=[minX, minY, maxX, maxY],
xRes=nresolution, yRes=nresolution,
dstSRS=target_proj)
out_data2 = OutTile2.GetRasterBand(1)
out_data2 = out_data2.ReadAsArray()
out_data2 = (out_data2>condition[0]).astype(numpy.uint8)
OutTile2 = None
isum = out_data2.sum()
icount = out_data2.size
ivalid2 = 1 if (isum >= condition[1]) and (icount >= condition[2]) else 0
# Absolute difference: check dimension
if out_data1.shape == out_data2.shape:
diff = (out_data1!=out_data2).astype('uint8')
diff = diff.sum()
else:
diff = 65536 # means delete
# Condition 2: difference should be lower than T2 (0.3)
ivalid3 = ((diff/icount) <= condition[3]).astype(numpy.uint8)
ivalid4 = 1 if (ivalid2==1) and (ivalid3==1) else 0
# Create fields: sum & count
feature.SetField2(fieldname[0], isum)
feature.SetField2(fieldname[1], icount)
feature.SetField2(fieldname[2], diff)
feature.SetField2(validname[1], ivalid2)
feature.SetField2(validname[2], ivalid3)
feature.SetField2(validname[3], ivalid4)
lyr.SetFeature(feature)
feature = None
# Close dataset
raster = None
VectorDataset = None
lyr = None
def compare_twotiff_valid_iou(tif_ref, vrt_file, shp_file,
fieldname=('vrt_sum', 'vrt_count', 'absdiff'),
validname=('isv', 'isv2', 'isv3', 'isv4'),
nresolution=2.5,
condition=(0, 2000, 65536, 0.3)):
# Vector
VectorDriver = ogr.GetDriverByName('ESRI Shapefile') # intialize vector
VectorDataset = VectorDriver.Open(shp_file, 1) # read & write
lyr = VectorDataset.GetLayer()
# Referenced tif
raster = gdal.Open(tif_ref)
target_proj = raster.GetProjectionRef()
rasterband = raster.GetRasterBand(1)
transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = -transform[5]
# Coordinate transformation to the same projection
sourceSR = lyr.GetSpatialRef()
targetSR = osr.SpatialReference(wkt=target_proj)
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
# Create field
defn = lyr.GetLayerDefn()
for ifield in fieldname+validname:
if defn.GetFieldIndex(ifield) == -1:
lyr.CreateField(ogr.FieldDefn(ifield, ogr.OFTInteger64))
index_isv = defn.GetFieldIndex(validname[0])
# create iou
if defn.GetFieldIndex('diou') == -1:
lyr.CreateField(ogr.FieldDefn('diou', ogr.OFTReal))
# feature = lyr.GetNetFeature() # select the first polygon (the circle shown in image)
# Loop over all
for feature in lyr:
# feature = lyr.GetNextFeature()
# Check if the feature is valid (e.g., meet the condition 1)
value_isv = feature.GetFieldAsInteger(index_isv)
if value_isv == 0:
continue
geom = feature.GetGeometryRef()
geom.Transform(coordTrans)
minX, maxX, minY, maxY = geom.GetEnvelope() # get the extent
# Tif 1: the reference file
# Specify offset and rows and columns to read
xoff = int((minX - xOrigin)/pixelWidth)
yoff = int((yOrigin - maxY)/pixelHeight)
xcount = int((maxX - minX)/pixelWidth) # +1
ycount = int((maxY - minY)/pixelHeight) # +1
out_data1 = rasterband.ReadAsArray(xoff, yoff, xcount, ycount).astype(numpy.uint8)
out_data1 = (out_data1>condition[0]).astype(numpy.uint8)
#Tif 2: Clip & warp the reference images
OutTile2 = gdal.Warp("tmp.vrt", vrt_file, format='VRT',
outputBounds=[minX, minY, maxX, maxY],
xRes=nresolution, yRes=nresolution,
dstSRS=target_proj)
out_data2 = OutTile2.GetRasterBand(1)
out_data2 = out_data2.ReadAsArray()
out_data2 = (out_data2>condition[0]).astype(numpy.uint8)
OutTile2 = None
isum = out_data2.sum()
icount = out_data2.size
ivalid2 = 1 if (isum >= condition[1]) and (icount >= condition[2]) else 0
# Absolute difference: check dimension
if out_data1.shape == out_data2.shape:
diou = 1-calculate_iou(out_data1, out_data2)
diff = (out_data1!=out_data2).astype(numpy.uint8)
diff = diff.sum()
else:
diff = 65536 # means delete
diou = 1
# Condition 2: difference should be lower than T2 (0.3)
# ivalid3 = (diff/icount <= condition[3]).astype(numpy.uint8)
ivalid3 = (diou <= condition[3]) # and ((diff/icount <= 0.3))
ivalid3 = ivalid3.astype(numpy.uint8)
ivalid4 = 1 if (ivalid2==1) and (ivalid3==1) else 0
# Create fields: sum & count
feature.SetField2(fieldname[0], isum)
feature.SetField2(fieldname[1], icount)
feature.SetField2(fieldname[2], diff)
feature.SetField2(validname[1], ivalid2)
feature.SetField2(validname[2], ivalid3)
feature.SetField2(validname[3], ivalid4)
feature.SetField2('diou', diou)
lyr.SetFeature(feature)
feature = None
# Close dataset
raster = None
VectorDataset = None
lyr = None
def compare_twotiff_valid_rmse(tif_ref, vrt_file, shp_file,
fieldname=('vrt_sum', 'vrt_count', 'absdiff'),
validname=('isv', 'isv2', 'isv3', 'isv4'),
nresolution=2.5,
condition=(0, 2000, 65536, 0.3)):
# Vector
VectorDriver = ogr.GetDriverByName('ESRI Shapefile') # intialize vector
VectorDataset = VectorDriver.Open(shp_file, 1) # read & write
lyr = VectorDataset.GetLayer()
# Referenced tif
raster = gdal.Open(tif_ref)
target_proj = raster.GetProjectionRef()
rasterband = raster.GetRasterBand(1)
transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = -transform[5]
# Coordinate transformation to the same projection
sourceSR = lyr.GetSpatialRef()
targetSR = osr.SpatialReference(wkt=target_proj)
coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
# Create field
defn = lyr.GetLayerDefn()
for ifield in fieldname+validname:
if defn.GetFieldIndex(ifield) == -1:
lyr.CreateField(ogr.FieldDefn(ifield, ogr.OFTInteger64))
index_isv = defn.GetFieldIndex(validname[0])
# create iou
if defn.GetFieldIndex('diou') == -1:
lyr.CreateField(ogr.FieldDefn('diou', ogr.OFTReal))
# feature = lyr.GetNetFeature() # select the first polygon (the circle shown in image)
# Loop over all
for feature in lyr:
# feature = lyr.GetNextFeature()
# Check if the feature is valid (e.g., meet the condition 1)
value_isv = feature.GetFieldAsInteger(index_isv)
if value_isv == 0:
continue
geom = feature.GetGeometryRef()
geom.Transform(coordTrans)
minX, maxX, minY, maxY = geom.GetEnvelope() # get the extent
# Tif 1: the reference file
# Specify offset and rows and columns to read
xoff = int((minX - xOrigin)/pixelWidth)
yoff = int((yOrigin - maxY)/pixelHeight)
xcount = int((maxX - minX)/pixelWidth) # +1
ycount = int((maxY - minY)/pixelHeight) # +1
out_data1 = rasterband.ReadAsArray(xoff, yoff, xcount, ycount).astype(numpy.uint8)
out_data1 = (out_data1>condition[0]).astype(numpy.uint8)
#Tif 2: Clip & warp the reference images
OutTile2 = gdal.Warp("tmp.vrt", vrt_file, format='VRT',
outputBounds=[minX, minY, maxX, maxY],
xRes=nresolution, yRes=nresolution,
dstSRS=target_proj)
out_data2 = OutTile2.GetRasterBand(1)
out_data2 = out_data2.ReadAsArray()
out_data2 = (out_data2>condition[0]).astype(numpy.uint8)
OutTile2 = None