mikonvergence commited on
Commit
cf37891
·
verified ·
1 Parent(s): 6735449

Create extras/thumbnail_dem.py

Browse files
Files changed (1) hide show
  1. extras/thumbnail_dem.py +77 -0
extras/thumbnail_dem.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NOTE: Major TOM standard does not require any specific type of thumbnail to be computed.
3
+
4
+ Instead these are shared as optional help since this is how the Core dataset thumbnails have been computed.
5
+ """
6
+
7
+ from rasterio.io import MemoryFile
8
+ from PIL import Image
9
+ import numpy as np
10
+ import os
11
+ from pathlib import Path
12
+ import rasterio as rio
13
+ from matplotlib.colors import LightSource
14
+
15
+ def get_grayscale(x):
16
+ """
17
+ Normalized grayscale visualisation
18
+ """
19
+
20
+ # normalize
21
+ x_n = x-x.min()
22
+ x_n = x_n/x_n.max()
23
+
24
+ return np.uint8(x_n*255)
25
+
26
+ def get_hillshade(x, azdeg=315, altdeg=45,ve=1):
27
+ """
28
+ Hillshade visualisation for DEM
29
+ """
30
+ ls = LightSource(azdeg=azdeg, altdeg=altdeg)
31
+
32
+ return np.uint8(255*ls.hillshade(x, vert_exag=ve))
33
+
34
+ def dem_thumbnail(dem, dem_NODATA = -32768.0, hillshade=True):
35
+ """
36
+ Takes vv and vh numpy arrays along with the corresponding NODATA values (default is -32768.0)
37
+
38
+ Returns a numpy array with the thumbnail
39
+ """
40
+ if hillshade:
41
+ return get_hillshade(dem)
42
+ else:
43
+ return get_grayscale(dem)
44
+
45
+
46
+ def dem_thumbnail_from_datarow(datarow):
47
+ """
48
+ Takes a datarow directly from one of the data parquet files
49
+
50
+ Returns a PIL Image
51
+ """
52
+
53
+ with MemoryFile(datarow['DEM'][0].as_py()) as mem_f:
54
+ with mem_f.open(driver='GTiff') as f:
55
+ dem=f.read().squeeze()
56
+ dem_NODATA = f.nodata
57
+
58
+ img = dem_thumbnail(dem, dem_NODATA)
59
+
60
+ return Image.fromarray(img,'L')
61
+
62
+ if __name__ == '__main__':
63
+ from fsspec.parquet import open_parquet_file
64
+ import pyarrow.parquet as pq
65
+
66
+ print('[example run] reading file from HuggingFace...')
67
+ url = "https://huggingface.co/datasets/Major-TOM/Core-DEM/resolve/main/images/part_01001.parquet"
68
+ with open_parquet_file(url) as f:
69
+ with pq.ParquetFile(f) as pf:
70
+ first_row_group = pf.read_row_group(1)
71
+
72
+ print('[example run] computing the thumbnail...')
73
+ thumbnail = dem_thumbnail_from_datarow(first_row_group)
74
+
75
+ thumbnail_fname = 'example_thumbnail.png'
76
+ thumbnail.save(thumbnail_fname, format = 'PNG')
77
+ print('[example run] saved as "{}"'.format(thumbnail_fname))