-
Notifications
You must be signed in to change notification settings - Fork 1
/
tif2excel.py
53 lines (38 loc) · 1.42 KB
/
tif2excel.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
import numpy as np
import pandas as pd
from osgeo import gdal
def tif_to_xyz(tif_path: str, output: str, step=3) -> None:
"""
Convert a GeoTIFF file to an Excel file in XYZ format.
Args:
tif_path (str): The path of the input GeoTIFF file.
step (int): The sampling interval of the output data. Default is 3.
Returns:
None.
"""
ds = gdal.Open(tif_path)
band = ds.GetRasterBand(1)
width = ds.RasterXSize
height = ds.RasterYSize
gt = ds.GetGeoTransform()
minX = gt[0]
minY = gt[3] + width*gt[4] + height*gt[5]
maxX = gt[0] + width*gt[1] + height*gt[2]
maxY = gt[3]
print(f"the domain : ({minX}, {maxX}) ({minY}, {maxY})")
elevation = band.ReadAsArray()
gridx = np.linspace(minX, maxX, width)
gridy = np.linspace(maxY, minY, height) # flip the y-axis to match the XYZ format
X, Y = np.meshgrid(gridx[::step], gridy[::step])
Z = elevation[::step, ::step].flatten()
# Remove the boundary value (-32767)
boundary_index = np.where(Z == -32767)[0]
X, Y, Z = np.delete(X.flatten(), boundary_index), np.delete(Y.flatten(), boundary_index), np.delete(Z, boundary_index)
S = np.ones_like(X)
file = pd.DataFrame({'x': X, 'y': Y, 'z': Z, 'slice': S})
file.to_excel(output, index=False)
print("Finished!")
if __name__ == "__main__":
tif_file = 'YOUR_TIFF_FILE.tiff'
output = 'test.xlsx'
tif_to_xyz(tif_file, output)