Py.Cafe

AnavApp/

geemap-composite-visualization-0

Geospatial Data Visualization

DocsPricing
  • app.py
  • requirements.txt
app.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
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
import streamlit as st
import numpy as np
import pandas as pd
import ee
import geemap.foliumap as geemap
from google.oauth2 import id_token
from google.auth.transport import requests
from google.auth import compute_engine
import json

st.set_page_config(layout="wide")

Map = None
vegetation_image = None
evapotranspiration_image = None
composite_image = None


def app():
    global Map
    st.title("Streamlit App - Composite - evapotranspiration and vegetation")


    # Replace contents of service account json file corresponding to your account from here:
    # https://console.cloud.google.com/iam-admin/serviceaccounts

    json_data = '''
    {
        "type": "service_account",
        "project_id": "vegetation-2023-408901",
        "private_key_id": "15e3efcc0c9cf688ecda768f9babceb9d23288e1",
        "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCzy/kqR7D4aWQL\n3Cb5wqmh3HA1zD0FDP5dFLsUh58LHl2lQc5TV5+Ce4ltWspgL9bQTM4Ab7Kf/mKG\noXnhUWvbXvX2JgcZxQExID5JJCAeXptW+AMa+7oPLTxtWrtuPJgqBdBe/87kAFqB\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PorA/Z4GpyN3j4Y7kvNJ8KnUQ1dVAoGAfRav\n4WDOqNMOh8dEfKKm0PJxpzI53wQLSjy/ue48BYi0xy0+d9b2TMhT8w+Uk7bYdWv+\n8nJSI5hE/0Sx7HpNZgtTiHuxi3UBFYKiRjPg421rC3wH2FkA3kE3WNtVemqr46tq\n9Ov+xE+GgbBY7IeM/1UnVm1lt09H5F56NsFRhP8CgYBhzHh4w26rXeWIgZImqeFT\n2PcRi3YCp6Q9MBpKm2L2K4QVmD+6YebrwXXQTv8uQZBKika6k6lCOOh+4fyoAcNR\ngmTcLz+NPJwnEkhvAIvDg2g8mwWe48Rn+uJKupI6iK6HU90jMRfiyGaPa0IfEe3u\nxUgdzlJxtI0tpBSMGkUKSQ==\n-----END PRIVATE KEY-----\n",
        "client_email": "vegetation-public-service@vegetation-2023-408901.iam.gserviceaccount.com",
        "client_id": "114235178928524820853",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/vegetation-public-service%40vegetation-2023-408901.iam.gserviceaccount.com",
        "universe_domain": "googleapis.com
    }
    '''
    # Preparing values
    json_object = json.loads(json_data, strict=False)
    service_account = json_object['client_email']
    json_object = json.dumps(json_object)
    # Authorising the app
    credentials = ee.ServiceAccountCredentials(service_account, key_data=json_object)
    print("credentials = ", credentials)
    ee.Initialize(credentials)

    Map = geemap.Map()
    add_evapotranspiration_layer()
    add_vegetation_layer()

    # Create composite image with above layers
    concat_images()
    # combine_images_method_2()

def add_vegetation_layer():
    print("in add_vegetation_layer")
    global Map
    global vegetation_image

    # Load the image collection
    dataset = ee.ImageCollection('MODIS/061/MOD13A2') \
        .filterDate('2015-01-01', '2015-01-31') \
        .mean()

    # Select the NDVI band
    ndvi = dataset.select('NDVI')

    # Visualization parameters
    ndviVis = {
        'min': 0,
        'max': 9000,
        'palette': [
            'ffffff', 'ce7e45', 'df923d', 'f1b555', 'fcd163', '99b718', '74a901',
            '66a000', '529400', '3e8601', '207401', '056201', '004c00', '023b01',
            '012e01', '011d01', '011301'
        ]
    }

    try:
        print("Adding NDVI vegetation layer/loading to streamlit")
        # Add the NDVI layer to the map
        vegetation_image = ndvi
        print("vegetation_image:", vegetation_image.getInfo())

        # # Map.addLayer(ndvi, ndviVis, 'NDVI vegetation layer')
        ## Map.addLayer(vegetation_image, ndviVis, 'NDVI vegetation layer')
        # Map.addLayer(eval(ee_asset))
        # st.write(Map)
        # Map.to_streamlit()
    except Exception as e:
        st.error(f"Error adding NDVI vegetation layer/loading to streamlit: {e}")


def add_evapotranspiration_layer():
    print("in add_evapotranspiration_layer")
    global Map
    global evapotranspiration_image

    # Load the image collection
    dataset = ee.ImageCollection("CSIC/SPEI/2_9") \
        .filterDate('2015-01-01', '2015-01-31') \
        .mean()

    # Select the 24-month analysis
    spei24 = dataset.select('SPEI_24_month')

    # Set the visualization parameters
    visParams = {
        'min': -2.33,
        'max': 2.33,
        'palette': [
            '8b1a1a', 'de2929', 'f3641d',
            'fdc404', '9afa94', '03f2fd',
            '12adf3', '1771de', '00008b',
        ]
    }

    try:
        # Display the SPEI 24-month layer
        print("Adding SPEI 24-month evapotranspiration layer/loading to streamlit")
        # evapotranspiration_image = spei24.filterBounds(regionOfInterest).first()
        evapotranspiration_image = spei24
        print("evapotranspiration_image:", evapotranspiration_image.getInfo())

        # Map.addLayer(spei24, visParams, 'SPEI 24 month evapotranspiration layer')
        ##Map.addLayer(evapotranspiration_image, visParams, 'SPEI 24 month evapotranspiration layer')
        # Map.to_streamlit()
    except Exception as e:
        st.error(f"Error adding SPEI 24-month evapotranspiration layer/loading to streamlit: {e}")

def concat_images():
    print("in concat_images")
    global Map
    global vegetation_image
    global evapotranspiration_image

    try:
        # Create a concat image with vegetation_image and evapotranspiration_image
        composite_image = ee.Image.cat([evapotranspiration_image, vegetation_image])
        print("composite_image =", composite_image)
        Map.addLayer(composite_image, {'bands': ['SPEI_24_month', 'NDVI'], 'min': -1, 'max': 1}, 'Composite Image')
        #Map.addLayer(composite_image, name='Concat Image')

        evapotranspiration_viz_params = {
            'bands': ['SPEI_24_month', 'NDVI'],
            'min': -1,
            'max': 1
            # 'palette': [
            #     '8b1a1a', 'de2929', 'f3641d',
            #     'fdc404', '9afa94', '03f2fd',
            #     '12adf3', '1771de', '00008b',
            # ]
        }

        #Map.addLayer(composite_image, name='Concat Image', viz_params=evapotranspiration_viz_params)        

        Map.to_streamlit()
    except Exception as e:
        st.error(f"Error creating concat image: {e}")

def combine_images():
    print("in combine_images")
    global Map
    global vegetation_image
    global evapotranspiration_image
    # try:
    # Method 1
    # Create a combined image with vegetation_image and evapotranspiration_image
    composite_image = ee.Image.combine_([evapotranspiration_image, vegetation_image])
    print("Combined image:", composite_image.getInfo())
    # Map.addLayer(composite_image, {'bands': ['SPEI_24_month', 'NDVI']}, name='Composite Image')
    Map.addLayer(composite_image, {'bands': ['SPEI_24_month', 'NDVI'], 'min': -1, 'max': 1}, 'Composite Image')

    # Map.addLayer(composite_image, name='Combined Image')

    Map.to_streamlit()
    # except Exception as e:
    #     st.error(f"Error creating combined image: {e}")

def combine_images_method_2():
    print("in combine_images_method_2")
    global Map
    global vegetation_image
    global evapotranspiration_image
    # try:
    # Method 2
    # try:
    # Create a combined image with vegetation_image and evapotranspiration_image
    print("evapotranspiration_image image:", evapotranspiration_image)
    print("vegetation_image image:", vegetation_image.getInfo())
    # composite_image = evapotranspiration_image.addBands(vegetation_image)
    composite_image = vegetation_image.addBands(evapotranspiration_image)
    # print("Combined image:", composite_image.getInfo())

    viz_params = {
        'bands': ['SPEI_24_month', 'NDVI'],
        'min': -1,
        'max': 1,
        'gamma': [1, 1, 1]  # Adjust gamma if needed
    }

    evapotranspiration_viz_params = {
        'min': -2.33,
        'max': 2.33,
        'palette': [
            '8b1a1a', 'de2929', 'f3641d',
            'fdc404', '9afa94', '03f2fd',
            '12adf3', '1771de', '00008b',
        ]
    }

    Map.addLayer(composite_image, name='Combined Image', viz_params=evapotranspiration_viz_params)
    Map.to_streamlit()
    # except Exception as e:
    #     st.error(f"Error creating combined image: {e}")

app()