mikonvergence commited on
Commit
aeea03d
1 Parent(s): 4f852c0

Create extras/thumbnail_s2.py

Browse files
Files changed (1) hide show
  1. extras/thumbnail_s2.py +68 -0
extras/thumbnail_s2.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ def s2l1c_thumbnail(B04, B03, B02, gain=1.3, gamma=0.6):
12
+ """
13
+ Takes B04, B03, B02 numpy arrays along with the corresponding NODATA values (default is -32768.0)
14
+
15
+ Returns a numpy array with the thumbnail
16
+ """
17
+
18
+ # concatenate
19
+ thumb = np.stack([B04, B03, B02], -1)
20
+
21
+ # apply gain & gamma
22
+ thumb = gain*((thumb/10_000)**gamma)
23
+
24
+ return (thumb.clip(0,1)*255).astype(np.uint8)
25
+
26
+ def s2l1c_thumbnail_from_datarow(datarow):
27
+ """
28
+ Takes a datarow directly from one of the data parquet files
29
+
30
+ Returns a PIL Image
31
+ """
32
+
33
+ # red
34
+ with MemoryFile(datarow['B04'][0].as_py()) as mem_f:
35
+ with mem_f.open(driver='GTiff') as f:
36
+ B04=f.read().squeeze()
37
+ B04_NODATA = f.nodata
38
+
39
+ # green
40
+ with MemoryFile(datarow['B03'][0].as_py()) as mem_f:
41
+ with mem_f.open(driver='GTiff') as f:
42
+ B03=f.read().squeeze()
43
+ B03_NODATA = f.nodata
44
+
45
+ # blue
46
+ with MemoryFile(datarow['B02'][0].as_py()) as mem_f:
47
+ with mem_f.open(driver='GTiff') as f:
48
+ B02=f.read().squeeze()
49
+ B02_NODATA = f.nodata
50
+
51
+ img = s2l1c_thumbnail(B04,B03,B02)
52
+
53
+ return Image.fromarray(img)
54
+
55
+ if __name__ == '__main__':
56
+ from fsspec.parquet import open_parquet_file
57
+ import pyarrow.parquet as pq
58
+
59
+ print('[example run] reading file from HuggingFace...')
60
+ url = "https://huggingface.co/datasets/Major-TOM/Core-S2L1C/resolve/main/images/part_01000.parquet"
61
+ with open_parquet_file(url, columns = ["B04", "B03", "B02"]) as f:
62
+ with pq.ParquetFile(f) as pf:
63
+ first_row_group = pf.read_row_group(1, columns = ["B04", "B03", "B02"])
64
+
65
+ print('[example run] computing the thumbnail...')
66
+ thumbnail = s2l1c_thumbnail_from_datarow(first_row_group)
67
+
68
+ thumbnail.save('example_thumbnail.png', format = 'PNG')