disco-tif 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- disco-tif-0.0.1/HISTORY.md +5 -0
- disco-tif-0.0.1/MANIFEST.in +8 -0
- disco-tif-0.0.1/PKG-INFO +17 -0
- disco-tif-0.0.1/README.md +6 -0
- disco-tif-0.0.1/disco_tif/__init__.py +0 -0
- disco-tif-0.0.1/disco_tif/geotiff_plotting.py +76 -0
- disco-tif-0.0.1/disco_tif/hillshades_pca.py +181 -0
- disco-tif-0.0.1/disco_tif/process_sb_tiff.py +405 -0
- disco-tif-0.0.1/disco_tif/write_mapfile.py +257 -0
- disco-tif-0.0.1/disco_tif.egg-info/PKG-INFO +17 -0
- disco-tif-0.0.1/disco_tif.egg-info/SOURCES.txt +14 -0
- disco-tif-0.0.1/disco_tif.egg-info/dependency_links.txt +1 -0
- disco-tif-0.0.1/disco_tif.egg-info/requires.txt +7 -0
- disco-tif-0.0.1/disco_tif.egg-info/top_level.txt +1 -0
- disco-tif-0.0.1/setup.cfg +4 -0
- disco-tif-0.0.1/setup.py +24 -0
disco-tif-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: disco-tif
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Geotiff processing utilities
|
|
5
|
+
Home-page: https://github.com/emerald-geomodelling/disco-tif
|
|
6
|
+
Author: Benjamin Bloss
|
|
7
|
+
Author-email: bb@emrld.no
|
|
8
|
+
Keywords: raster_processing
|
|
9
|
+
Requires-Dist: seaborn
|
|
10
|
+
Requires-Dist: rasterio
|
|
11
|
+
Requires-Dist: numpy
|
|
12
|
+
Requires-Dist: pandas
|
|
13
|
+
Requires-Dist: matplotlib
|
|
14
|
+
Requires-Dist: earthpy
|
|
15
|
+
Requires-Dist: scikit-learn
|
|
16
|
+
|
|
17
|
+
Geotiff processing utilities
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# disco_tif
|
|
2
|
+
some general raster tools for visualization
|
|
3
|
+
|
|
4
|
+
The primary utility of this library is to take a single-channel geotiff and create an rgba (32bit) geotiff.
|
|
5
|
+
The code can take a colormap name from matplotlib (https://matplotlib.org/stable/users/explain/colors/colormaps.html), however If no colormap is supplied the EMerald_standard_colormap will be applied. This is a data driven colormap.
|
|
6
|
+
Basically
|
|
File without changes
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import rasterio
|
|
3
|
+
import earthpy as et
|
|
4
|
+
import earthpy.spatial as es
|
|
5
|
+
import earthpy.plot as ep
|
|
6
|
+
import matplotlib as mpl
|
|
7
|
+
from matplotlib import pyplot as plt
|
|
8
|
+
from matplotlib.colors import LinearSegmentedColormap
|
|
9
|
+
import datetime
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import sklearn.decomposition
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def plot_singleband_raster(raster_data, cmap="terrain", title='Raster Data', ax=None, figsize = [15, 9]):
|
|
16
|
+
# Plot the data
|
|
17
|
+
if ax is None:
|
|
18
|
+
figsize = [15, 9]
|
|
19
|
+
fig,ax = plt.subplots(1,1,figsize=figsize)
|
|
20
|
+
ep.plot_bands(raster_data,
|
|
21
|
+
cmap = cmap,
|
|
22
|
+
title=title,
|
|
23
|
+
ax=ax)
|
|
24
|
+
plt.tight_layout()
|
|
25
|
+
plt.show()
|
|
26
|
+
return fig, ax
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def plot_greyband_only(raster_data_dict,
|
|
30
|
+
nrows,
|
|
31
|
+
ncols,
|
|
32
|
+
plotsize=4):
|
|
33
|
+
|
|
34
|
+
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[ncols*plotsize, nrows*plotsize] )
|
|
35
|
+
try:
|
|
36
|
+
axs=axs.flatten()
|
|
37
|
+
except:
|
|
38
|
+
pass
|
|
39
|
+
ind=-1
|
|
40
|
+
for key, value in raster_data_dict.items():
|
|
41
|
+
ind+=1
|
|
42
|
+
try:
|
|
43
|
+
ax=axs[ind]
|
|
44
|
+
except:
|
|
45
|
+
ax=axs
|
|
46
|
+
ep.plot_bands(value,
|
|
47
|
+
ax=ax,
|
|
48
|
+
cbar=False,
|
|
49
|
+
title=f"{key}")
|
|
50
|
+
plt.tight_layout()
|
|
51
|
+
plt.show()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def plot_color_raster_with_greyscale_overlay(raster_data, raster_data_dict, nrows, ncols, plotsize=4, cmap='terrain'):
|
|
55
|
+
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[ncols*plotsize, nrows*plotsize] )
|
|
56
|
+
try:
|
|
57
|
+
axs=axs.flatten()
|
|
58
|
+
except:
|
|
59
|
+
pass
|
|
60
|
+
ind=-1
|
|
61
|
+
for key, value in raster_data_dict.items():
|
|
62
|
+
ind+=1
|
|
63
|
+
try:
|
|
64
|
+
ax=axs[ind]
|
|
65
|
+
except:
|
|
66
|
+
ax=axs
|
|
67
|
+
ep.plot_bands(raster_data,
|
|
68
|
+
ax=ax,
|
|
69
|
+
cmap = cmap,
|
|
70
|
+
title=f"{key}")
|
|
71
|
+
ax.imshow(value, cmap="Greys", alpha=0.5)
|
|
72
|
+
|
|
73
|
+
plt.tight_layout()
|
|
74
|
+
plt.show()
|
|
75
|
+
|
|
76
|
+
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import rasterio
|
|
3
|
+
import earthpy as et
|
|
4
|
+
import earthpy.spatial as es
|
|
5
|
+
import earthpy.plot as ep
|
|
6
|
+
import matplotlib as mpl
|
|
7
|
+
from matplotlib import pyplot as plt
|
|
8
|
+
from matplotlib.colors import LinearSegmentedColormap
|
|
9
|
+
import datetime
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import sklearn.decomposition
|
|
13
|
+
|
|
14
|
+
#import process_sb_tiff
|
|
15
|
+
import disco_tif.geotiff_plotting
|
|
16
|
+
|
|
17
|
+
#################################################
|
|
18
|
+
|
|
19
|
+
def build_hs_az_al(start_al, al_inc, num_al_angles, start_az, num_az_angles):
|
|
20
|
+
azimuths = np.linspace(start_az, start_az+360, num_az_angles+1) # degrees 0=360, number of divisions + 1 because start=end
|
|
21
|
+
filt = azimuths>=360
|
|
22
|
+
while filt.sum()>0:
|
|
23
|
+
azimuths[filt] = azimuths[filt]-360
|
|
24
|
+
filt = azimuths>=360
|
|
25
|
+
azimuths = azimuths[:-1].astype(int).tolist()
|
|
26
|
+
azimuths = sorted(azimuths)
|
|
27
|
+
print(f"azimuths = {azimuths}")
|
|
28
|
+
|
|
29
|
+
altitudes = np.linspace(start_al, (al_inc*num_al_angles)+start_al, num_al_angles+1)
|
|
30
|
+
altitudes = altitudes[:-1].astype(int).tolist()
|
|
31
|
+
print(f"altitudes = {altitudes}")
|
|
32
|
+
return azimuths, altitudes
|
|
33
|
+
|
|
34
|
+
def write_raster_dict_data_to_geotiff(single_band_tiff_path, origprofile, raster_data_dict, len_hs=None):
|
|
35
|
+
for key, value in raster_data_dict.items():
|
|
36
|
+
if 'component' in key:
|
|
37
|
+
assert len_hs is not None, "'len_hs' cannot be none if passing in a pca_dictionary_object"
|
|
38
|
+
new_tiff_path = f"{single_band_tiff_path.split('.tif')[0]}_hillshade_pca{len_hs}-{key}.tif"
|
|
39
|
+
else:
|
|
40
|
+
new_tiff_path = f"{single_band_tiff_path.split('.tif')[0]}_hillshade_{key}.tif"
|
|
41
|
+
|
|
42
|
+
newprofile = origprofile.copy()
|
|
43
|
+
newprofile.update(dtype=str((value[0,0]).dtype), nodata=np.nan)
|
|
44
|
+
|
|
45
|
+
with rasterio.open(new_tiff_path, 'w', **newprofile) as dst:
|
|
46
|
+
dst.write(arr=value, indexes=1, masked=True)
|
|
47
|
+
|
|
48
|
+
print(f"New single-channel geotiff generated successfully: '{new_tiff_path}'")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def MakeHillShadePCA(hillshades, plot_figures=False, raster_data=None, cmap='terrain', n_components=3):
|
|
52
|
+
if plot_figures:
|
|
53
|
+
assert raster_data is not None, "raster data must be supplied if plot_figures is true"
|
|
54
|
+
|
|
55
|
+
NoNanIndicies = np.argwhere(~np.isnan(hillshades[list(hillshades.keys())[0]].flatten())).flatten()
|
|
56
|
+
|
|
57
|
+
n_samples = len(NoNanIndicies)
|
|
58
|
+
n_features = len(hillshades.keys())
|
|
59
|
+
assert n_features >= 4, "There must be at least 4 hillshades to produce a PCA"
|
|
60
|
+
|
|
61
|
+
flat_hillshades = np.ones([n_samples, n_features]) * np.nan
|
|
62
|
+
|
|
63
|
+
feature_ind=-1
|
|
64
|
+
for key, value in hillshades.items():
|
|
65
|
+
feature_ind+=1
|
|
66
|
+
value = value.flatten()
|
|
67
|
+
value = value[NoNanIndicies]
|
|
68
|
+
flat_hillshades[:,feature_ind]=value
|
|
69
|
+
|
|
70
|
+
assert np.isnan(flat_hillshades).sum()==0, "There can be no NaN's when performing a pca"
|
|
71
|
+
|
|
72
|
+
pca = sklearn.decomposition.PCA(n_components = n_components)
|
|
73
|
+
|
|
74
|
+
pcaout = pca.fit(flat_hillshades).transform(flat_hillshades)
|
|
75
|
+
pcaout
|
|
76
|
+
|
|
77
|
+
pcaout.shape
|
|
78
|
+
|
|
79
|
+
data = hillshades[list(hillshades.keys())[0]]
|
|
80
|
+
|
|
81
|
+
nrow = data.shape[0]
|
|
82
|
+
ncol = data.shape[1]
|
|
83
|
+
nlay = len(pcaout[0])
|
|
84
|
+
|
|
85
|
+
dumarray = np.ones([nrow * ncol])*np.nan
|
|
86
|
+
|
|
87
|
+
pcaComponents={}
|
|
88
|
+
for ilay in range(0,len(pcaout[0])):
|
|
89
|
+
tdat = dumarray.copy()
|
|
90
|
+
nowdat = pcaout[:, ilay]
|
|
91
|
+
tdat[NoNanIndicies] = nowdat
|
|
92
|
+
pcaComponents[f'component_{ilay+1}'] = tdat.reshape([nrow,ncol], order='C')
|
|
93
|
+
|
|
94
|
+
if plot_figures:
|
|
95
|
+
# plot the pca outputs
|
|
96
|
+
disco_tif.geotiff_plotting.plot_greyband_only(raster_data_dict=pcaComponents,
|
|
97
|
+
nrows=1,
|
|
98
|
+
ncols=n_components)
|
|
99
|
+
disco_tif.geotiff_plotting.plot_color_raster_with_greyscale_overlay(raster_data=raster_data,
|
|
100
|
+
cmap=cmap,
|
|
101
|
+
raster_data_dict=pcaComponents,
|
|
102
|
+
nrows=1,
|
|
103
|
+
ncols=n_components)
|
|
104
|
+
|
|
105
|
+
# pcaComponents['component_1_0_1'] = ( pcaComponents['component_1'] - np.nanmin(pcaComponents['component_1'])) / \
|
|
106
|
+
# (np.nanmax(pcaComponents['component_1']) - np.nanmin(pcaComponents['component_1']))
|
|
107
|
+
|
|
108
|
+
# pcaComponents['component_2_0_1'] = ( pcaComponents['component_2'] - np.nanmin(pcaComponents['component_2'])) / \
|
|
109
|
+
# (np.nanmax(pcaComponents['component_2']) - np.nanmin(pcaComponents['component_2']))
|
|
110
|
+
|
|
111
|
+
# pcaComponents['component_3_0_1'] = ( pcaComponents['component_3'] - np.nanmin(pcaComponents['component_3'])) / \
|
|
112
|
+
# (np.nanmax(pcaComponents['component_3']) - np.nanmin(pcaComponents['component_3']))
|
|
113
|
+
|
|
114
|
+
return pcaComponents
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def build_hillshade(single_band_tiff_path, data_min_max, hs_azimuths, hs_altitudes, cmap='terrain', process_pca=False, plot_figures=False):
|
|
118
|
+
# read geotiff and minimally process for the colormap function
|
|
119
|
+
with rasterio.open(single_band_tiff_path, 'r') as src:
|
|
120
|
+
data = src.read(1) # Read the first band
|
|
121
|
+
no_data_value = src.nodata # Get the no-data value from the GeoTIFF
|
|
122
|
+
epsg_code = src.crs.to_epsg() if src.crs else None
|
|
123
|
+
origprofile = src.profile
|
|
124
|
+
width = src.width
|
|
125
|
+
height = src.height
|
|
126
|
+
srcmask = src.read_masks(1)
|
|
127
|
+
|
|
128
|
+
# Clip data values to the specified range
|
|
129
|
+
clipped_data = np.clip(data, data_min_max[0], data_min_max[1])
|
|
130
|
+
|
|
131
|
+
nan_data = data.copy().astype(float)
|
|
132
|
+
nan_clipped_data = clipped_data.copy().astype(float)
|
|
133
|
+
|
|
134
|
+
if no_data_value is not None:
|
|
135
|
+
nan_data[data==no_data_value]=np.nan
|
|
136
|
+
nan_clipped_data[data==no_data_value]=np.nan
|
|
137
|
+
|
|
138
|
+
#
|
|
139
|
+
if plot_figures:
|
|
140
|
+
# Plot the data
|
|
141
|
+
disco_tif.geotiff_plotting.plot_singleband_raster(raster_data=nan_clipped_data,
|
|
142
|
+
cmap=cmap,
|
|
143
|
+
title=f"{single_band_tiff_path} Without Hillshade",
|
|
144
|
+
ax=None)
|
|
145
|
+
|
|
146
|
+
# calculate the hillshade for all combination fo azimuths and altitudes
|
|
147
|
+
num_hillshades = len(hs_azimuths) * len(hs_altitudes)
|
|
148
|
+
# it it expensive to generate all of these hillshades and do the pca on them => we limit the number to something reasonable # 8 azimuths at 3 angles will produce 24 hillshades. ### what is reasonable here?
|
|
149
|
+
max_num_hs = 24
|
|
150
|
+
assert num_hillshades<=max_num_hs, f"Only {max_num_hs} azimuth-altidude combinations can be used to calculate a Hillshade PCA but {num_hillshades} were provided"
|
|
151
|
+
|
|
152
|
+
hillshades = {}
|
|
153
|
+
for az_ind, my_azimuth in enumerate(hs_azimuths):
|
|
154
|
+
for al_ind, my_altitude in enumerate(hs_altitudes):
|
|
155
|
+
# Create and plot the hillshade with earthpy
|
|
156
|
+
txt_my_azimuth = f"00{my_azimuth}"[-3:]
|
|
157
|
+
txt_my_altitude = f"0{my_altitude}"[-2:]
|
|
158
|
+
hskey = f'az{txt_my_azimuth}_al{txt_my_altitude}'
|
|
159
|
+
hillshades[hskey] = es.hillshade(nan_data, azimuth=my_azimuth, altitude=my_altitude)
|
|
160
|
+
|
|
161
|
+
if plot_figures:
|
|
162
|
+
# plot the hillshades
|
|
163
|
+
disco_tif.geotiff_plotting.plot_greyband_only(raster_data_dict=hillshades,
|
|
164
|
+
nrows=max([len(hs_azimuths), len(hs_altitudes)]),
|
|
165
|
+
ncols=min([len(hs_azimuths), len(hs_altitudes)]))
|
|
166
|
+
# plot geotiff overlain with the hillshades
|
|
167
|
+
disco_tif.geotiff_plotting.plot_color_raster_with_greyscale_overlay(raster_data=nan_clipped_data,
|
|
168
|
+
raster_data_dict=hillshades,
|
|
169
|
+
nrows=max([len(hs_azimuths), len(hs_altitudes)]),
|
|
170
|
+
ncols=min([len(hs_azimuths), len(hs_altitudes)]),
|
|
171
|
+
cmap=cmap)
|
|
172
|
+
|
|
173
|
+
write_raster_dict_data_to_geotiff(single_band_tiff_path, origprofile, hillshades)
|
|
174
|
+
|
|
175
|
+
if not process_pca:
|
|
176
|
+
return hillshades
|
|
177
|
+
elif process_pca:
|
|
178
|
+
assert num_hillshades>=4, f'Need at least 4 azimuth-altitude combinations, only {num_hillshades} were provided'
|
|
179
|
+
pcaComponents = MakeHillShadePCA(hillshades, plot_figures, raster_data=nan_clipped_data, cmap=cmap)
|
|
180
|
+
write_raster_dict_data_to_geotiff(single_band_tiff_path, origprofile, pcaComponents, len_hs=len(hillshades.keys()))
|
|
181
|
+
return hillshades, pcaComponents
|
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import rasterio
|
|
3
|
+
import earthpy as et
|
|
4
|
+
import earthpy.spatial as es
|
|
5
|
+
import earthpy.plot as ep
|
|
6
|
+
import matplotlib as mpl
|
|
7
|
+
from matplotlib import pyplot as plt
|
|
8
|
+
from matplotlib.colors import LinearSegmentedColormap
|
|
9
|
+
import datetime
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import sklearn.decomposition
|
|
13
|
+
|
|
14
|
+
######################################
|
|
15
|
+
|
|
16
|
+
def nowTime():
|
|
17
|
+
return datetime.datetime.now().strftime("%H:%M:%S")
|
|
18
|
+
def now():
|
|
19
|
+
return datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
20
|
+
def snow():
|
|
21
|
+
return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
22
|
+
def today():
|
|
23
|
+
return datetime.datetime.now().strftime("%Y-%m-%d")
|
|
24
|
+
def stoday():
|
|
25
|
+
return datetime.datetime.now().strftime("%Y%m%d")
|
|
26
|
+
|
|
27
|
+
######################################
|
|
28
|
+
|
|
29
|
+
def hex_to_rgb(hexcolor):
|
|
30
|
+
if '#' in hexcolor:
|
|
31
|
+
hexcolor = hexcolor.split('#')[1]
|
|
32
|
+
rgb = []
|
|
33
|
+
for i in (0, 2, 4):
|
|
34
|
+
decimal = int(hexcolor[i:i+2], 16)
|
|
35
|
+
rgb.append(decimal)
|
|
36
|
+
return rgb[0], rgb[1], rgb[2]
|
|
37
|
+
def rgb_to_hex(r, g, b):
|
|
38
|
+
return '#{:02x}{:02x}{:02x}'.format(r, g, b)
|
|
39
|
+
|
|
40
|
+
######################################
|
|
41
|
+
|
|
42
|
+
# define custom color steps - Order matters
|
|
43
|
+
EMerald_custom_colors_hexcolorcodes = ['#0000ff', # Blue
|
|
44
|
+
'#01ffff', # Cyan
|
|
45
|
+
'#3fca3f', # Green
|
|
46
|
+
'#f19898', # Salmon
|
|
47
|
+
'#deb201', # Tan
|
|
48
|
+
'#896651', # Brown
|
|
49
|
+
'#f1bfff', # Light_Purple
|
|
50
|
+
'#fffafc', # Near_White
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
colormap_length = 256
|
|
54
|
+
|
|
55
|
+
######################################
|
|
56
|
+
|
|
57
|
+
def build_EMerald_terrain_colormap(breaks_by_percentages):
|
|
58
|
+
EMerald_custom_colors_rgb=[]
|
|
59
|
+
for hexcode in EMerald_custom_colors_hexcolorcodes:
|
|
60
|
+
temp = hex_to_rgb(hexcode)
|
|
61
|
+
EMerald_custom_colors_rgb.append([np.round(temp[0]/(colormap_length-1), 3),
|
|
62
|
+
np.round(temp[1]/(colormap_length-1), 3),
|
|
63
|
+
np.round(temp[2]/(colormap_length-1), 3)])
|
|
64
|
+
colorarray = np.array(EMerald_custom_colors_rgb)
|
|
65
|
+
colorarray
|
|
66
|
+
|
|
67
|
+
if breaks_by_percentages[1]==0: # if second entry is 0 we know that there are no negative numbers and we should ignore blue
|
|
68
|
+
sn=1
|
|
69
|
+
else:
|
|
70
|
+
sn=0
|
|
71
|
+
EMeraldCustomColormap_cdict = {'red': [(breaks_by_percentages[ijk], colorarray[ijk,0], colorarray[ijk,0]) for ijk in range(sn, len(breaks_by_percentages))],
|
|
72
|
+
'green': [(breaks_by_percentages[ijk], colorarray[ijk,1], colorarray[ijk,1]) for ijk in range(sn, len(breaks_by_percentages))],
|
|
73
|
+
'blue': [(breaks_by_percentages[ijk], colorarray[ijk,2], colorarray[ijk,2]) for ijk in range(sn, len(breaks_by_percentages))],
|
|
74
|
+
}
|
|
75
|
+
EMeraldCustomColormap = LinearSegmentedColormap("EMerald_Custom_Colormap", EMeraldCustomColormap_cdict, N=colormap_length)
|
|
76
|
+
EMeraldCustomColormap
|
|
77
|
+
|
|
78
|
+
return EMeraldCustomColormap
|
|
79
|
+
|
|
80
|
+
######################################
|
|
81
|
+
|
|
82
|
+
def make_percentile_array(data_min_max, data, no_data_value, cmap_method='pseudo_hist_norm', plot_histograms=False):
|
|
83
|
+
if data_min_max is not None:
|
|
84
|
+
assert len(data_min_max)==2, 'len of data_min_max must be 2'
|
|
85
|
+
assert data_min_max[0] < data_min_max[1], 'first value must be less than second value'
|
|
86
|
+
assert data_min_max[1] > 0, 'This should really be a bigger number, but at least this will save dividing by a zero...'
|
|
87
|
+
|
|
88
|
+
datatype = str(data[0,0].dtype)
|
|
89
|
+
num_color = len(EMerald_custom_colors_hexcolorcodes)
|
|
90
|
+
bz_num_color = 1 #number of colors for below zero
|
|
91
|
+
az_num_color = num_color-bz_num_color-1 # number of intervals
|
|
92
|
+
|
|
93
|
+
z_data = data.copy()
|
|
94
|
+
z_data = z_data.flatten()
|
|
95
|
+
bz_data = z_data[z_data<0]
|
|
96
|
+
az_data = z_data[z_data>=0]
|
|
97
|
+
norm_az_data = (az_data.copy() - np.min(az_data)) / (np.max(az_data) - np.min(az_data)) # shift to zero, then normalize by the range
|
|
98
|
+
|
|
99
|
+
if cmap_method=='pseudo_linear':
|
|
100
|
+
az_min=np.max([0, data_min_max[0]]) # above_zero_min: if data_min_max[0]<0, then 0; if data_min_max[0]>=0, then data_min_max[0].
|
|
101
|
+
#print(f"az_min = {az_min}")
|
|
102
|
+
az_data_breaks = np.round(np.linspace(az_min, data_min_max[1], az_num_color+1))
|
|
103
|
+
#print(f"az_data_breaks = {az_data_breaks}")
|
|
104
|
+
|
|
105
|
+
elif cmap_method=='pseudo_hist_norm':
|
|
106
|
+
my_percentiles = np.linspace(0, 100, az_num_color+1)
|
|
107
|
+
my_percentiles = my_percentiles[1:-1]
|
|
108
|
+
#print(f"my_percentiles = {my_percentiles}")
|
|
109
|
+
|
|
110
|
+
az_data_breaks = np.percentile(a=az_data, q=my_percentiles)
|
|
111
|
+
if data_min_max[0]<0:
|
|
112
|
+
az_data_breaks = np.insert(az_data_breaks, 0, 0) #prepend with: if data_min_max[0]<0, then 0;
|
|
113
|
+
else:
|
|
114
|
+
az_data_breaks = np.insert(az_data_breaks, 0, data_min_max[0]) #prepend with: if data_min_max[0]>=0, then data_min_max[0]
|
|
115
|
+
az_data_breaks = np.append(az_data_breaks, data_min_max[1])
|
|
116
|
+
#print(f"az_data_breaks = {az_data_breaks}")
|
|
117
|
+
|
|
118
|
+
data_breaks = [data_min_max[0]]
|
|
119
|
+
#print(f"data_breaks = {data_breaks}")
|
|
120
|
+
data_breaks.extend(az_data_breaks)
|
|
121
|
+
data_breaks = np.array(data_breaks)
|
|
122
|
+
data_breaks = data_breaks.astype(datatype).tolist()
|
|
123
|
+
#print(f"data_breaks = {data_breaks}")
|
|
124
|
+
|
|
125
|
+
percentile_breaks = np.round((np.array(data_breaks) - data_min_max[0]) / (data_min_max[1] - data_min_max[0]), 4)
|
|
126
|
+
percentile_breaks = percentile_breaks.tolist()
|
|
127
|
+
#print(f"percentile_breaks = {percentile_breaks}")
|
|
128
|
+
|
|
129
|
+
if plot_histograms:
|
|
130
|
+
no_dum_data = data.copy()
|
|
131
|
+
no_dum_data = no_dum_data.flatten()
|
|
132
|
+
no_dum_data = no_dum_data.astype(float)
|
|
133
|
+
if no_data_value is not None:
|
|
134
|
+
no_dum_data[no_dum_data==no_data_value] = np.nan
|
|
135
|
+
norm_no_dum_data = (no_dum_data.copy() - data_min_max[0]) / (data_min_max[1] - data_min_max[0]) # shift to zero, then normalize by the range
|
|
136
|
+
|
|
137
|
+
fig, axs = plt.subplots(nrows=2, ncols=1, sharey=True)
|
|
138
|
+
|
|
139
|
+
axs[0].hist(no_dum_data, bins=min(data_min_max[1]-data_min_max[0], 100))
|
|
140
|
+
ylimits = axs[0].get_ylim()
|
|
141
|
+
for db in data_breaks:
|
|
142
|
+
axs[0].plot([db, db], [0, ylimits[1]])
|
|
143
|
+
axs[0].set_title('Breaks by data values')
|
|
144
|
+
|
|
145
|
+
axs[1].hist(norm_no_dum_data, bins=min(data_min_max[1]-data_min_max[0], 100))
|
|
146
|
+
for pb in percentile_breaks:
|
|
147
|
+
axs[1].plot([pb, pb], [0, ylimits[1]])
|
|
148
|
+
axs[1].set_title('Breaks by percentage of data')
|
|
149
|
+
|
|
150
|
+
plt.tight_layout(); plt.show()
|
|
151
|
+
|
|
152
|
+
return percentile_breaks, data_breaks
|
|
153
|
+
|
|
154
|
+
######################################
|
|
155
|
+
|
|
156
|
+
def calc_data_min_max(data, no_data_value, clip_perc, min_max_method='percentile'):
|
|
157
|
+
if min_max_method=='data_absolute':
|
|
158
|
+
# using absolute min max from data
|
|
159
|
+
if no_data_value is not None:
|
|
160
|
+
data_min_max = [np.min(data[data!=no_data_value]), np.max(data[data!=no_data_value])]
|
|
161
|
+
else:
|
|
162
|
+
data_min_max = [np.min(data), np.max(data)]
|
|
163
|
+
|
|
164
|
+
elif min_max_method=='percentile':
|
|
165
|
+
# using percentiles of data (defined in the import statement)
|
|
166
|
+
if no_data_value is not None:
|
|
167
|
+
data_min_max = np.percentile(a=data[data!=no_data_value], q=clip_perc)
|
|
168
|
+
else:
|
|
169
|
+
data_min_max = np.percentile(a=data, q=clip_perc)
|
|
170
|
+
data_min_max = np.round(data_min_max)
|
|
171
|
+
data_min_max = data_min_max.astype(int)
|
|
172
|
+
data_min_max = list(data_min_max)
|
|
173
|
+
return data_min_max
|
|
174
|
+
|
|
175
|
+
######################################
|
|
176
|
+
|
|
177
|
+
def build_1_component_color_tables(cmap, data_breaks, data, no_data_value, new_multiband_lut_path):
|
|
178
|
+
EMerald_colors_rgb = pd.DataFrame()
|
|
179
|
+
for ii in range(0, len(cmap)):
|
|
180
|
+
hexcolor = cmap[ii]
|
|
181
|
+
EMerald_colors_rgb.loc[ii, ['r']] = hex_to_rgb(hexcolor)[0]
|
|
182
|
+
EMerald_colors_rgb.loc[ii, ['g']] = hex_to_rgb(hexcolor)[1]
|
|
183
|
+
EMerald_colors_rgb.loc[ii, ['b']] = hex_to_rgb(hexcolor)[2]
|
|
184
|
+
|
|
185
|
+
if len(EMerald_colors_rgb) == len(data_breaks):
|
|
186
|
+
EMerald_colors_rgb['data_val'] = np.array(data_breaks)
|
|
187
|
+
else:
|
|
188
|
+
print("there's an odd mismatch in length of 'EMerald_colors_rgb' and 'data_breaks'")
|
|
189
|
+
|
|
190
|
+
outfilepaths=[]
|
|
191
|
+
for rgb in ['r', 'g', 'b']:
|
|
192
|
+
lut_str = f"{EMerald_colors_rgb.loc[0, 'data_val']}: {EMerald_colors_rgb.loc[0, rgb]}"
|
|
193
|
+
for row in range(1, len(EMerald_colors_rgb)):
|
|
194
|
+
lut_str = f"{lut_str}, {EMerald_colors_rgb.loc[row, 'data_val']}: {int(np.round(EMerald_colors_rgb.loc[row, rgb]))}"
|
|
195
|
+
tname=f"{new_multiband_lut_path}_{rgb}.lut"
|
|
196
|
+
outfilepaths.append(tname)
|
|
197
|
+
with open(tname, 'w') as lut_file_out:
|
|
198
|
+
lut_file_out.write(lut_str)
|
|
199
|
+
|
|
200
|
+
lut_str = f"{np.array(no_data_value, dtype=data[0,0].dtype).tolist()}: 0, {data_breaks[0]}: 255, {data_breaks[-1]}:255"
|
|
201
|
+
tname=f"{new_multiband_lut_path}_a.lut"
|
|
202
|
+
outfilepaths.append(tname)
|
|
203
|
+
with open(tname, 'w') as lut_file_out:
|
|
204
|
+
lut_file_out.write(lut_str)
|
|
205
|
+
|
|
206
|
+
return outfilepaths
|
|
207
|
+
|
|
208
|
+
######################################
|
|
209
|
+
|
|
210
|
+
def build_4_component_color_tables(single_band_tiff_path, cmap, data, no_data_value, percentile_breaks, data_breaks, outfile):
|
|
211
|
+
pathparts = single_band_tiff_path.split(os.path.sep)
|
|
212
|
+
destfolder = ''
|
|
213
|
+
for part in pathparts[:-1]:
|
|
214
|
+
destfolder=f"{destfolder}{part}{os.path.sep}"
|
|
215
|
+
|
|
216
|
+
index_breaks = np.round([id * 255 for id in percentile_breaks]).astype(int).tolist()
|
|
217
|
+
index_breaks
|
|
218
|
+
|
|
219
|
+
ph_colormap_df = pd.DataFrame((cmap._lut * 255).astype('uint8'), columns=['red', 'green', 'blue', 'alpha']).iloc[:256,:]
|
|
220
|
+
ph_colormap_df.loc[index_breaks,'data_breaks'] = data_breaks
|
|
221
|
+
ph_colormap_df['data_breaks'] = ph_colormap_df['data_breaks'].interpolate(method='linear').astype(type(data_breaks[0]))
|
|
222
|
+
|
|
223
|
+
nan_ph_colormap_df = ph_colormap_df.copy()
|
|
224
|
+
nan_ph_colormap_df.loc[-1] = [0, 0, 0, 0, np.array(no_data_value, dtype=data[0,0].dtype).tolist()]
|
|
225
|
+
nan_ph_colormap_df.index = nan_ph_colormap_df.index + 1 # shifting index
|
|
226
|
+
nan_ph_colormap_df = nan_ph_colormap_df.sort_index() # sorting by index
|
|
227
|
+
|
|
228
|
+
#outfile = os.path.join(destfolder, outfile)
|
|
229
|
+
|
|
230
|
+
qgisfile = f"{outfile}_qgis_color_table.txt"
|
|
231
|
+
ph_colormap_df.to_csv(qgisfile, index=False, header=False, columns=['data_breaks', 'red', 'green', 'blue', 'alpha', 'data_breaks'])
|
|
232
|
+
with open(qgisfile, 'r') as inlut:
|
|
233
|
+
origstuff=inlut.read()
|
|
234
|
+
with open(qgisfile, 'w') as outlut:
|
|
235
|
+
outlut.seek(0)
|
|
236
|
+
outlut.write(f"# EMerald Generated Color Map Export File for {single_band_tiff_path}\n")
|
|
237
|
+
outlut.write("INTERPOLATION:INTERPOLATED\n")
|
|
238
|
+
outlut.write(origstuff)
|
|
239
|
+
|
|
240
|
+
rgba_lut_file = f"{outfile}_lut.lut"
|
|
241
|
+
ph_colormap_df.to_csv(rgba_lut_file, index=False, header=False, columns=['data_breaks', 'red', 'green', 'blue', 'alpha'])
|
|
242
|
+
nan_rgba_lut_file = f"{outfile}_NaN_lut.lut"
|
|
243
|
+
nan_ph_colormap_df.to_csv(nan_rgba_lut_file, index=False, header=False, columns=['data_breaks', 'red', 'green', 'blue', 'alpha'])
|
|
244
|
+
|
|
245
|
+
return [qgisfile, rgba_lut_file]
|
|
246
|
+
|
|
247
|
+
######################################
|
|
248
|
+
|
|
249
|
+
def make_rgba_tiff_from_single_Band(single_band_tiff_path,
|
|
250
|
+
data_min_max=None,
|
|
251
|
+
min_max_method='percentile',
|
|
252
|
+
clip_perc=[1, 99],
|
|
253
|
+
color_palette_name=None,
|
|
254
|
+
cmap_method='pseudo_hist_norm',
|
|
255
|
+
output_tif=False,
|
|
256
|
+
plot_rgba_raster=False,
|
|
257
|
+
):
|
|
258
|
+
'''Function to take a single band geotiff file, apply a colormap to the data, and write a rgba geotiff to file
|
|
259
|
+
|
|
260
|
+
Input parameters:
|
|
261
|
+
- single_band_tiff_path:
|
|
262
|
+
complete path to single-band-geotiff
|
|
263
|
+
|
|
264
|
+
- data_min_max:
|
|
265
|
+
default = None
|
|
266
|
+
Can take a list of lenth: 2, ex: [0, 500]
|
|
267
|
+
This function will automatically apply min/max values based on the 1 and 99 percentiles of the data values (excluding no-data values).
|
|
268
|
+
|
|
269
|
+
- min_max_method:
|
|
270
|
+
default = 'percentile'
|
|
271
|
+
Also accepts 'data_absolute'.
|
|
272
|
+
'percentile' uses the percentiles used in clip_perc.
|
|
273
|
+
'data_absolute' uses the minimum and maximum values of the data
|
|
274
|
+
|
|
275
|
+
- clip_perc
|
|
276
|
+
default = [1, 99]
|
|
277
|
+
Percentile values to clip the data values to if no data_min_max is specified.
|
|
278
|
+
|
|
279
|
+
- color_palette_name
|
|
280
|
+
default = None
|
|
281
|
+
Desired color pallet based on matplotlib colormaps.
|
|
282
|
+
https://matplotlib.org/stable/users/explain/colors/colormaps.html
|
|
283
|
+
If None, the funtion will automatically create a new "EMerald_Custom_Colormap"
|
|
284
|
+
|
|
285
|
+
- cmap_method:
|
|
286
|
+
defualt = 'pseudo_hist_norm'
|
|
287
|
+
Method to determine where the color breaks should be. Also accepts 'pseudo_linear'
|
|
288
|
+
'pseudo_hist_norm' will produce a linear colormap for data values below 0 and a histogram normalized colormap for the positive values
|
|
289
|
+
'pseudo_linear' will produce a linear colormap for data values below 0 and a separate linear colormap for the positive values.
|
|
290
|
+
'''
|
|
291
|
+
|
|
292
|
+
if data_min_max is not None:
|
|
293
|
+
assert len(data_min_max)==2, "len of data_min_max must be 2"
|
|
294
|
+
assert data_min_max[0] < data_min_max[1], "first value must be less than second value"
|
|
295
|
+
assert data_min_max[1] > 0, "This should really be a bigger number, but at least this will save dividing by a zero..."
|
|
296
|
+
assert len(clip_perc)==2, "len of data_min_max must be 2"
|
|
297
|
+
assert clip_perc[0] < clip_perc[1], "first value must be less than second value"
|
|
298
|
+
|
|
299
|
+
# 1. Read the Single-Band GeoTIFF:
|
|
300
|
+
# Open the single-band GeoTIFF
|
|
301
|
+
with rasterio.open(single_band_tiff_path, 'r') as src:
|
|
302
|
+
data = src.read(1) # Read the first band
|
|
303
|
+
origprofile = src.profile
|
|
304
|
+
extent = src.bounds
|
|
305
|
+
size = (src.width, src.height)
|
|
306
|
+
epsg_code = src.crs.to_epsg() if src.crs else None
|
|
307
|
+
no_data_value = src.nodata # Get the no-data value from the GeoTIFF
|
|
308
|
+
|
|
309
|
+
no_data_value = np.array(no_data_value, dtype=data[0,0].dtype).tolist()
|
|
310
|
+
if data_min_max is None:
|
|
311
|
+
data_min_max = calc_data_min_max(data, no_data_value, clip_perc, min_max_method=min_max_method)
|
|
312
|
+
|
|
313
|
+
# Clip data values to the specified range
|
|
314
|
+
clipped_data = np.clip(data, data_min_max[0], data_min_max[1])
|
|
315
|
+
|
|
316
|
+
# Normalize the clipped data to the [0, 1] range
|
|
317
|
+
normalized_data = (clipped_data - data_min_max[0]) / (data_min_max[1] - data_min_max[0]) # shift to zero, divide by the range
|
|
318
|
+
|
|
319
|
+
# clip the data to the min-max values specified
|
|
320
|
+
clipped_data_with_dum = clipped_data.copy()
|
|
321
|
+
if no_data_value is not None:
|
|
322
|
+
clipped_data_with_dum[data==no_data_value]=no_data_value # since int is a valid datatype we can reuse the no-data-value (iff it's outside our min-max range)
|
|
323
|
+
|
|
324
|
+
# make percentile ranges
|
|
325
|
+
percentile_breaks, data_breaks = make_percentile_array(data_min_max,
|
|
326
|
+
clipped_data_with_dum,
|
|
327
|
+
no_data_value,
|
|
328
|
+
cmap_method=cmap_method)
|
|
329
|
+
#print(f"percentile_breaks = {percentile_breaks}")
|
|
330
|
+
#print(f"data_breaks = {data_breaks}")
|
|
331
|
+
|
|
332
|
+
# 2. Generate a custom colormap (EMeraldCustomColormap):
|
|
333
|
+
if color_palette_name is None:
|
|
334
|
+
color_palette_name = "EMeraldCustomTerrain"
|
|
335
|
+
EMeraldCustomColormap = build_EMerald_terrain_colormap(percentile_breaks)
|
|
336
|
+
else:
|
|
337
|
+
EMeraldCustomColormap = mpl.colormaps.get_cmap(color_palette_name)
|
|
338
|
+
EMeraldCustomColormap(0) #need this line for it to make a lut?!?
|
|
339
|
+
#print(EMeraldCustomColormap._lut)
|
|
340
|
+
|
|
341
|
+
# define output name
|
|
342
|
+
sbpath, ext = os.path.splitext(single_band_tiff_path)
|
|
343
|
+
suffix=f"{color_palette_name}_{data_min_max[0]}_to_{data_min_max[1]}_{cmap_method}"
|
|
344
|
+
new_multiband_lut_path = f"{sbpath}_{suffix}"
|
|
345
|
+
new_multiband_tiff_path = f"{sbpath}_rgba_{suffix}"
|
|
346
|
+
|
|
347
|
+
if plot_rgba_raster:
|
|
348
|
+
# clip the data to the min-max values specified
|
|
349
|
+
clipped_data_with_nan = clipped_data.copy().astype(float)
|
|
350
|
+
if no_data_value is not None:
|
|
351
|
+
clipped_data_with_nan[data==no_data_value]=np.nan
|
|
352
|
+
|
|
353
|
+
figsize = [15, 9]
|
|
354
|
+
fig,ax=plt.subplots(1,1,figsize=figsize)
|
|
355
|
+
ep.plot_bands(clipped_data_with_nan,
|
|
356
|
+
cmap = EMeraldCustomColormap,
|
|
357
|
+
title=f"{sbpath.split(os.path.sep)[-1]}\n{suffix.replace('_', ' ')}",
|
|
358
|
+
ax=ax,
|
|
359
|
+
)
|
|
360
|
+
plt.tight_layout()
|
|
361
|
+
plt.show()
|
|
362
|
+
|
|
363
|
+
outfilepaths = build_1_component_color_tables(cmap=EMerald_custom_colors_hexcolorcodes,
|
|
364
|
+
data_breaks=data_breaks,
|
|
365
|
+
data=data,
|
|
366
|
+
no_data_value=no_data_value,
|
|
367
|
+
new_multiband_lut_path=new_multiband_lut_path )
|
|
368
|
+
for fp in outfilepaths:
|
|
369
|
+
print(f"Wrote 1component LUT files to: '{fp}'")
|
|
370
|
+
|
|
371
|
+
outfilepaths = build_4_component_color_tables(single_band_tiff_path=single_band_tiff_path,
|
|
372
|
+
cmap=EMeraldCustomColormap,
|
|
373
|
+
data=data,
|
|
374
|
+
no_data_value=no_data_value,
|
|
375
|
+
percentile_breaks=percentile_breaks,
|
|
376
|
+
data_breaks=data_breaks,
|
|
377
|
+
outfile=new_multiband_tiff_path)
|
|
378
|
+
for fp in outfilepaths:
|
|
379
|
+
print(f"wrote 4component Lut files to: '{fp}''")
|
|
380
|
+
|
|
381
|
+
if output_tif:
|
|
382
|
+
# apply EMeraldCustomColormap to data
|
|
383
|
+
rgba_data = EMeraldCustomColormap(normalized_data) * (colormap_length-1) # Scale to 0-255 range
|
|
384
|
+
|
|
385
|
+
# 3. Convert to RGB Channels:
|
|
386
|
+
rgb_data = rgba_data[:, :, :3] # Extract RGB channels
|
|
387
|
+
|
|
388
|
+
# 4. Generate an Alpha Channel:
|
|
389
|
+
alpha_channel = (data != no_data_value).astype('uint8') * (colormap_length-1)
|
|
390
|
+
rgba_data[:, :, 3] = alpha_channel
|
|
391
|
+
|
|
392
|
+
# 5. Write the New RGBA GeoTIFF:
|
|
393
|
+
newprofile = origprofile.copy()
|
|
394
|
+
newprofile.update(count=4, dtype='uint8', nodata=None) # RGBA format
|
|
395
|
+
|
|
396
|
+
with rasterio.open(f"{new_multiband_tiff_path}.tif", 'w', **newprofile) as dst:
|
|
397
|
+
dst.write(rgba_data[:, :, 0].astype('uint8'), 1) #red
|
|
398
|
+
dst.write(rgba_data[:, :, 1].astype('uint8'), 2) #green
|
|
399
|
+
dst.write(rgba_data[:, :, 2].astype('uint8'), 3) #blue
|
|
400
|
+
dst.write(rgba_data[:, :, 3].astype('uint8'), 4) #alpha
|
|
401
|
+
|
|
402
|
+
print(f"New RGBA geotiff '{new_multiband_tiff_path}' generated successfully!")
|
|
403
|
+
return EMeraldCustomColormap, data_breaks, percentile_breaks
|
|
404
|
+
|
|
405
|
+
######################################
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import numpy as np
|
|
3
|
+
import rasterio
|
|
4
|
+
import datetime
|
|
5
|
+
|
|
6
|
+
def nowTime():
|
|
7
|
+
return datetime.datetime.now().strftime("%H:%M:%S")
|
|
8
|
+
def now():
|
|
9
|
+
return datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
10
|
+
def snow():
|
|
11
|
+
return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
12
|
+
def today():
|
|
13
|
+
return datetime.datetime.now().strftime("%Y-%m-%d")
|
|
14
|
+
def stoday():
|
|
15
|
+
return datetime.datetime.now().strftime("%Y%m%d")
|
|
16
|
+
|
|
17
|
+
def generate_LUT_based_mapfile(single_band_tiff_path, mapfile_path, writeLUTs=True, writeTifs=False, writeHillshades=True):
|
|
18
|
+
'''
|
|
19
|
+
funtion to take two geotiffs (single band and multiband) and generate a multi-layer mapsource mapfile
|
|
20
|
+
single_band_tiff_path: path to single band geotiff
|
|
21
|
+
rgba_tiff_path: path to multiband geotiff
|
|
22
|
+
mapfile_path: path of output mapfile
|
|
23
|
+
'''
|
|
24
|
+
|
|
25
|
+
#print(f"single_band_tiff_path = {single_band_tiff_path}")
|
|
26
|
+
single_band_tiff_dir = os.path.dirname(single_band_tiff_path)
|
|
27
|
+
#print(f"single_band_tiff_dir = {single_band_tiff_dir}")
|
|
28
|
+
single_band_file = (single_band_tiff_path.split(single_band_tiff_dir)[1]).split(os.path.sep)[1]
|
|
29
|
+
#print(f"single_band_file = {single_band_file}")
|
|
30
|
+
|
|
31
|
+
lut_files_1b = []
|
|
32
|
+
lut_files_4b = []
|
|
33
|
+
for file in os.listdir(single_band_tiff_dir):
|
|
34
|
+
if file.startswith(os.path.splitext(single_band_file)[0]):
|
|
35
|
+
if file.endswith("_r.lut"):
|
|
36
|
+
lut_files_1b.append(file[:-6])
|
|
37
|
+
elif np.logical_and('rgba' in file, file.endswith(".lut")):
|
|
38
|
+
lut_files_4b.append(file)
|
|
39
|
+
#print(f"lut_files = {lut_files}")
|
|
40
|
+
|
|
41
|
+
hillshade_files = []
|
|
42
|
+
tif_files = []
|
|
43
|
+
for file in os.listdir(single_band_tiff_dir):
|
|
44
|
+
if file.startswith(os.path.splitext(single_band_file)[0]):
|
|
45
|
+
#if file.endswith("hillshade.tif"):
|
|
46
|
+
if np.logical_and('hillshade' in file, file.endswith(".tif")):
|
|
47
|
+
hillshade_files.append(file)
|
|
48
|
+
elif file.endswith(".tif"):
|
|
49
|
+
tif_files.append(file)
|
|
50
|
+
tif_files = [tiff for tiff in tif_files if tiff!=single_band_file]
|
|
51
|
+
hillshade_files = sorted(hillshade_files)
|
|
52
|
+
tif_files = sorted(tif_files)
|
|
53
|
+
|
|
54
|
+
# Open the single-band GeoTIFF
|
|
55
|
+
with rasterio.open(single_band_tiff_path, 'r') as src:
|
|
56
|
+
data = src.read(1) # Read the first band
|
|
57
|
+
#origprofile = src.profile
|
|
58
|
+
extent = src.bounds
|
|
59
|
+
size = (src.width, src.height)
|
|
60
|
+
epsg_code = src.crs.to_epsg() if src.crs else None
|
|
61
|
+
no_data_value = src.nodata # Get the no-data value from the GeoTIFF
|
|
62
|
+
|
|
63
|
+
no_data_value = np.array(no_data_value, dtype=data[0,0].dtype).tolist()
|
|
64
|
+
data_min_max = np.min(data[data!=no_data_value]), np.max(data)
|
|
65
|
+
#print(data_min_max)
|
|
66
|
+
|
|
67
|
+
# Define the paths to your GeoTIFF files
|
|
68
|
+
name = single_band_file.split('.')[0]
|
|
69
|
+
|
|
70
|
+
# Create a basic Mapfile template
|
|
71
|
+
mapfile_template = f"""## Mapfile written on {today()} at {nowTime()}
|
|
72
|
+
MAP
|
|
73
|
+
NAME "{name}"
|
|
74
|
+
EXTENT {np.round(extent.left, 7)} {np.round(extent.bottom, 7)} {np.round(extent.right, 7)} {np.round(extent.top, 7)}
|
|
75
|
+
SIZE {size[0]} {size[1]}
|
|
76
|
+
PROJECTION
|
|
77
|
+
"init=EPSG:{epsg_code}" # Set the EPSG code
|
|
78
|
+
END
|
|
79
|
+
|
|
80
|
+
WEB
|
|
81
|
+
METADATA
|
|
82
|
+
'wms_title' '{name}'
|
|
83
|
+
'wms_enable_request' '*'
|
|
84
|
+
'wms_srs' 'EPSG:{epsg_code}'
|
|
85
|
+
END
|
|
86
|
+
END
|
|
87
|
+
|
|
88
|
+
LAYER
|
|
89
|
+
NAME "{single_band_file.split('.')[0]}"
|
|
90
|
+
DATA "{single_band_file}"
|
|
91
|
+
TYPE RASTER
|
|
92
|
+
STATUS ON
|
|
93
|
+
EXTENT {np.round(extent.left, 7)} {np.round(extent.bottom, 7)} {np.round(extent.right, 7)} {np.round(extent.top, 7)}
|
|
94
|
+
PROJECTION
|
|
95
|
+
"init=EPSG:{epsg_code}"
|
|
96
|
+
END
|
|
97
|
+
PROCESSING "NODATA={no_data_value}" # Set your desired Nodata value
|
|
98
|
+
PROCESSING "LUT={data_min_max[0]}:0, {data_min_max[1]}:255" # Define the LUT (elevation:color)
|
|
99
|
+
END
|
|
100
|
+
"""
|
|
101
|
+
if writeLUTs:
|
|
102
|
+
for lut in lut_files_1b:
|
|
103
|
+
mapfile_template = f"""{mapfile_template}
|
|
104
|
+
LAYER
|
|
105
|
+
NAME "{lut}"
|
|
106
|
+
DATA "{single_band_file}"
|
|
107
|
+
TYPE RASTER
|
|
108
|
+
STATUS ON
|
|
109
|
+
EXTENT {np.round(extent.left, 7)} {np.round(extent.bottom, 7)} {np.round(extent.right, 7)} {np.round(extent.top, 7)}
|
|
110
|
+
PROJECTION
|
|
111
|
+
"init=EPSG:{epsg_code}"
|
|
112
|
+
END
|
|
113
|
+
PROCESSING "BANDS=1,1,1,1"
|
|
114
|
+
PROCESSING "LUT_1={lut}_r.lut"
|
|
115
|
+
PROCESSING "LUT_2={lut}_g.lut"
|
|
116
|
+
PROCESSING "LUT_3={lut}_b.lut"
|
|
117
|
+
PROCESSING "LUT_4={lut}_a.lut"
|
|
118
|
+
END
|
|
119
|
+
"""
|
|
120
|
+
for lut in lut_files_4b:
|
|
121
|
+
mapfile_template = f"""{mapfile_template}
|
|
122
|
+
LAYER
|
|
123
|
+
NAME "{lut}"
|
|
124
|
+
DATA "{single_band_file}"
|
|
125
|
+
TYPE RASTER
|
|
126
|
+
STATUS ON
|
|
127
|
+
EXTENT {np.round(extent.left, 7)} {np.round(extent.bottom, 7)} {np.round(extent.right, 7)} {np.round(extent.top, 7)}
|
|
128
|
+
PROJECTION
|
|
129
|
+
"init=EPSG:{epsg_code}"
|
|
130
|
+
END
|
|
131
|
+
PROCESSING "BANDS=1,1,1,1"
|
|
132
|
+
PROCESSING "LUT={lut}"
|
|
133
|
+
END
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
if writeTifs:
|
|
137
|
+
for tiff in tif_files:
|
|
138
|
+
# Open the single-band GeoTIFF
|
|
139
|
+
with rasterio.open(os.path.join(single_band_tiff_dir, tiff), 'r') as src:
|
|
140
|
+
#data = src.read(1) # Read the first band
|
|
141
|
+
#origprofile = src.profile
|
|
142
|
+
extent = src.bounds
|
|
143
|
+
size = (src.width, src.height)
|
|
144
|
+
epsg_code = src.crs.to_epsg() if src.crs else None
|
|
145
|
+
mapfile_template = f"""{mapfile_template}
|
|
146
|
+
LAYER
|
|
147
|
+
NAME "{tiff.split('.')[0]}"
|
|
148
|
+
DATA "{tiff}"
|
|
149
|
+
TYPE RASTER
|
|
150
|
+
STATUS ON
|
|
151
|
+
EXTENT {np.round(extent.left, 7)} {np.round(extent.bottom, 7)} {np.round(extent.right, 7)} {np.round(extent.top, 7)}
|
|
152
|
+
PROJECTION
|
|
153
|
+
"init=EPSG:{epsg_code}"
|
|
154
|
+
END
|
|
155
|
+
END
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
if writeHillshades:
|
|
159
|
+
for hillshade in hillshade_files:
|
|
160
|
+
# Open the single-band GeoTIFF
|
|
161
|
+
with rasterio.open(os.path.join(single_band_tiff_dir, hillshade), 'r') as src:
|
|
162
|
+
#data = src.read(1) # Read the first band
|
|
163
|
+
#origprofile = src.profile
|
|
164
|
+
extent = src.bounds
|
|
165
|
+
size = (src.width, src.height)
|
|
166
|
+
epsg_code = src.crs.to_epsg() if src.crs else None
|
|
167
|
+
mapfile_template = f"""{mapfile_template}
|
|
168
|
+
LAYER
|
|
169
|
+
NAME "{hillshade.split('.')[0]}"
|
|
170
|
+
DATA "{hillshade}"
|
|
171
|
+
TYPE RASTER
|
|
172
|
+
STATUS ON
|
|
173
|
+
EXTENT {np.round(extent.left, 7)} {np.round(extent.bottom, 7)} {np.round(extent.right, 7)} {np.round(extent.top, 7)}
|
|
174
|
+
PROJECTION
|
|
175
|
+
"init=EPSG:{epsg_code}"
|
|
176
|
+
END
|
|
177
|
+
COMPOSITE
|
|
178
|
+
OPACITY 50
|
|
179
|
+
END
|
|
180
|
+
END
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
mapfile_template = f"""{mapfile_template}
|
|
184
|
+
END
|
|
185
|
+
"""
|
|
186
|
+
|
|
187
|
+
# Write the Mapfile to a file
|
|
188
|
+
print(mapfile_template)
|
|
189
|
+
with open(mapfile_path, 'w') as mapfile:
|
|
190
|
+
mapfile.write(mapfile_template)
|
|
191
|
+
|
|
192
|
+
print(f"Mapfile '{mapfile_path}' generated successfully!")
|
|
193
|
+
|
|
194
|
+
######################################
|
|
195
|
+
|
|
196
|
+
def generate_tiff_based_mapfile(single_band_tiff_path, rgba_tiff_path, mapfile_path):
|
|
197
|
+
'''
|
|
198
|
+
funtion to take two geotiffs (single band and multiband) and generate a multi-layer mapsource mapfile
|
|
199
|
+
single_band_tiff_path: path to single band geotiff
|
|
200
|
+
rgba_tiff_path: path to multiband geotiff
|
|
201
|
+
mapfile_path: path of output mapfile
|
|
202
|
+
'''
|
|
203
|
+
# Open the single-band GeoTIFF
|
|
204
|
+
with rasterio.open(single_band_tiff_path, 'r') as src:
|
|
205
|
+
data = src.read(1) # Read the first band
|
|
206
|
+
origprofile = src.profile
|
|
207
|
+
extent = src.bounds
|
|
208
|
+
size = (src.width, src.height)
|
|
209
|
+
epsg_code = src.crs.to_epsg() if src.crs else None
|
|
210
|
+
|
|
211
|
+
# Define the paths to your GeoTIFF files
|
|
212
|
+
single_band_file = single_band_tiff_path.split(os.path.sep)[-1]
|
|
213
|
+
rgba_file = rgba_tiff_path.split(os.path.sep)[-1]
|
|
214
|
+
name = single_band_file.split('.')[0]
|
|
215
|
+
|
|
216
|
+
# Create a basic Mapfile template
|
|
217
|
+
mapfile_template = f"""## Mapfile written on {today()} at {nowTime()}
|
|
218
|
+
MAP
|
|
219
|
+
NAME "{name}"
|
|
220
|
+
EXTENT {extent.left} {extent.bottom} {extent.right} {extent.top}
|
|
221
|
+
SIZE {size[0]} {size[1]}
|
|
222
|
+
# IMAGECOLOR 255 255 255 #white background - exclude for transparent background
|
|
223
|
+
PROJECTION
|
|
224
|
+
"init=EPSG:{epsg_code}" # Set the EPSG code
|
|
225
|
+
END
|
|
226
|
+
|
|
227
|
+
LAYER
|
|
228
|
+
NAME "SingleBandLayer"
|
|
229
|
+
DATA "{single_band_file}"
|
|
230
|
+
TYPE RASTER
|
|
231
|
+
STATUS ON
|
|
232
|
+
EXTENT {extent.left} {extent.bottom} {extent.right} {extent.top}
|
|
233
|
+
PROJECTION
|
|
234
|
+
"init=EPSG:{epsg_code}"
|
|
235
|
+
END
|
|
236
|
+
END
|
|
237
|
+
|
|
238
|
+
LAYER
|
|
239
|
+
NAME "RGBALayer"
|
|
240
|
+
DATA "{rgba_file}"
|
|
241
|
+
TYPE RASTER
|
|
242
|
+
STATUS ON
|
|
243
|
+
EXTENT {extent.left} {extent.bottom} {extent.right} {extent.top}
|
|
244
|
+
PROJECTION
|
|
245
|
+
"init=EPSG:{epsg_code}"
|
|
246
|
+
END
|
|
247
|
+
END
|
|
248
|
+
END
|
|
249
|
+
"""
|
|
250
|
+
|
|
251
|
+
# Write the Mapfile to a file
|
|
252
|
+
with open(mapfile_path, 'w') as mapfile:
|
|
253
|
+
mapfile.write(mapfile_template)
|
|
254
|
+
|
|
255
|
+
print(f"Mapfile '{mapfile_path}' generated successfully!")
|
|
256
|
+
|
|
257
|
+
######################################
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: disco-tif
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Geotiff processing utilities
|
|
5
|
+
Home-page: https://github.com/emerald-geomodelling/disco-tif
|
|
6
|
+
Author: Benjamin Bloss
|
|
7
|
+
Author-email: bb@emrld.no
|
|
8
|
+
Keywords: raster_processing
|
|
9
|
+
Requires-Dist: seaborn
|
|
10
|
+
Requires-Dist: rasterio
|
|
11
|
+
Requires-Dist: numpy
|
|
12
|
+
Requires-Dist: pandas
|
|
13
|
+
Requires-Dist: matplotlib
|
|
14
|
+
Requires-Dist: earthpy
|
|
15
|
+
Requires-Dist: scikit-learn
|
|
16
|
+
|
|
17
|
+
Geotiff processing utilities
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
HISTORY.md
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
setup.py
|
|
5
|
+
disco_tif/__init__.py
|
|
6
|
+
disco_tif/geotiff_plotting.py
|
|
7
|
+
disco_tif/hillshades_pca.py
|
|
8
|
+
disco_tif/process_sb_tiff.py
|
|
9
|
+
disco_tif/write_mapfile.py
|
|
10
|
+
disco_tif.egg-info/PKG-INFO
|
|
11
|
+
disco_tif.egg-info/SOURCES.txt
|
|
12
|
+
disco_tif.egg-info/dependency_links.txt
|
|
13
|
+
disco_tif.egg-info/requires.txt
|
|
14
|
+
disco_tif.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
disco_tif
|
disco-tif-0.0.1/setup.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
import os,sys
|
|
4
|
+
from setuptools import setup, find_packages
|
|
5
|
+
|
|
6
|
+
setup(name = 'disco-tif',
|
|
7
|
+
version = "0.0.1",
|
|
8
|
+
url = 'https://github.com/emerald-geomodelling/disco-tif',
|
|
9
|
+
author = "Benjamin Bloss",
|
|
10
|
+
author_email = 'bb@emrld.no',
|
|
11
|
+
description = "Geotiff processing utilities",
|
|
12
|
+
install_requires = ["seaborn",
|
|
13
|
+
"rasterio",
|
|
14
|
+
"numpy",
|
|
15
|
+
"pandas",
|
|
16
|
+
"matplotlib",
|
|
17
|
+
"earthpy",
|
|
18
|
+
"scikit-learn",
|
|
19
|
+
],
|
|
20
|
+
long_description = "Geotiff processing utilities",
|
|
21
|
+
include_package_data = True,
|
|
22
|
+
keywords = 'raster_processing',
|
|
23
|
+
packages = find_packages(),
|
|
24
|
+
)
|