## Version 1 : Button Click
from osgeo import gdal,osr
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
def Load_image_by_Gdal(file_path):
= gdal.Open(file_path, gdal.GA_ReadOnly)
img_file = img_file.RasterCount
img_bands = img_file.RasterYSize
img_height = img_file.RasterXSize
img_width = img_file.ReadAsArray()
img_arr = img_file.GetGeoTransform()
geomatrix = img_file.GetProjectionRef()
projection return img_bands,img_arr, geomatrix, projection
# Define the tiff reading function
def read_tiff(file):
=Load_image_by_Gdal(file)
img_bands,img_arr, geomatrix, projection if img_bands >1 :
=img_arr.transpose(( 1, 2,0))
img_arrreturn img_arr, geomatrix, projection
# Function to calculate and visualize slope from a DEM
def calculate_slope(files,colormap='terrain'):
print(files.name,colormap)
=files.name
file_patchs=read_tiff(file_patchs)
img_arr,_,_=img_arr.copy()
dem_arrayprint(dem_array.shape,np.max(dem_array))
# Calculate gradient in the x and y direction
= np.gradient(dem_array, axis=1)
x_gradient = np.gradient(dem_array, axis=0)
y_gradient
# Calculate slope
= np.sqrt(x_gradient**2 + y_gradient**2)
slope print(dem_array.shape,np.max(slope),np.min(slope))
= np.clip(slope, 0, 90)/90
slope = plt.get_cmap(colormap)
cmap = cmap(slope)
colormapped_slope = colormapped_slope[:, :, :3] # Extract the RGB bands
slope_array return dem_array/np.max(dem_array),slope_array
def showslope(dem_array,colormap='terrain'):
= np.gradient(dem_array, axis=1)
x_gradient = np.gradient(dem_array, axis=0)
y_gradient = np.sqrt(x_gradient**2 + y_gradient**2)
slope print(dem_array.shape,np.max(slope),np.min(slope))
= np.clip(slope, 0, 90)/90
slope = plt.get_cmap(colormap)
cmap = cmap(slope)
colormapped_slope = colormapped_slope[:, :, :3]
slope_array return slope_array
# Define the reset function
def reset_state():
return None,None,None
# Define the visulization function
def show_dem(files):
# print(files.name)
=files.name
file_patchs=read_tiff(file_patchs)
img_arr, _, _=img_arr.copy()
dem_arrayreturn dem_array/np.max(dem_array),dem_array
with gr.Blocks(theme="Gstaff/Xkcd") as demo: # other theme: ["Default", "Glass", "Monochrome","Gstaff/Xkcd", "NoCrypt/Miku", "gradio/soft"]
=gr.State(None) # Define the temporary variable
demarray# Add an HTML header
"""
gr.HTML( <center>
<h1> DEM and Slope Visulization 🛰️ </h1>
<b> jason.yu.mail@qq.com 📧<b>
</center>
""")
= gr.UploadButton("Click to Upload a DEM File", file_types=["image"], file_count="single")
upload_button with gr.Row():
with gr.Column(scale=50):
=gr.Radio(choices=["rainbow","plasma","terrain"],label="Colormap")
choicewith gr.Column(scale=50):
= gr.Button("Showdem",variant="primary")
showdem = gr.Button("Restart",variant="secondary") # different button theme, variant="primary"
emptyBtn with gr.Row():
=gr.Image(label="DEM")
showimg= gr.Image(label="Slope")
img_output
# Use temporary variable to recieve the result of the show_dem function
upload_button.upload(show_dem, upload_button, [showimg,demarray]) # Define button click event to show the slope image
showdem.click(showslope,[demarray,choice],[img_output])
=[upload_button,showimg,img_output],show_progress=True)
emptyBtn.click(reset_state,outputs
demo.launch()
DEMO 3-3: DEM Visualization and Slope Analysis App
## Version 2 : Event Listeners
from osgeo import gdal,osr
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
def Load_image_by_Gdal(file_path):
= gdal.Open(file_path, gdal.GA_ReadOnly)
img_file = img_file.RasterCount
img_bands = img_file.RasterYSize
img_height = img_file.RasterXSize
img_width = img_file.ReadAsArray()
img_arr = img_file.GetGeoTransform()
geomatrix = img_file.GetProjectionRef()
projection return img_bands,img_arr, geomatrix, projection
# Define the tiff reading function
def read_tiff(file):
=Load_image_by_Gdal(file)
img_bands,img_arr, geomatrix, projection if img_bands >1 :
=img_arr.transpose(( 1, 2,0))
img_arrreturn img_arr, geomatrix, projection
# Function to calculate and visualize slope from a DEM
def calculate_slope(files,colormap='terrain'):
print(files.name,colormap)
=files.name
file_patchs=read_tiff(file_patchs)
img_arr,_,_=img_arr.copy()
dem_arrayprint(dem_array.shape,np.max(dem_array))
# Calculate gradient in the x and y direction
= np.gradient(dem_array, axis=1)
x_gradient = np.gradient(dem_array, axis=0)
y_gradient
# Calculate slope
= np.sqrt(x_gradient**2 + y_gradient**2)
slope print(dem_array.shape,np.max(slope),np.min(slope))
= np.clip(slope, 0, 90)/90
slope = plt.get_cmap(colormap)
cmap = cmap(slope)
colormapped_slope = colormapped_slope[:, :, :3] # Extract the RGB bands
slope_array return dem_array/np.max(dem_array),slope_array
# Define the reset function
def reset_state():
return None,None,None
# Define the visulization function
def show_dem(files):
# print(files.name)
=files.name
file_patchs=read_tiff(file_patchs)
img_arr, _, _=img_arr.copy()
dem_arrayreturn dem_array/np.max(dem_array),dem_array
with gr.Blocks(theme="Gstaff/Xkcd") as demo: # other theme: ["Default", "Glass", "Monochrome","Gstaff/Xkcd", "NoCrypt/Miku", "gradio/soft"]
# Add an HTML header
"""
gr.HTML( <center>
<h1> DEM and Slope Visulization 🛰️ </h1>
<b> jason.yu.mail@qq.com 📧<b>
</center>
""")
= gr.UploadButton("Click to Upload a DEM File", file_types=["image"], file_count="single")
upload_button with gr.Row():
with gr.Column(scale=50):
=gr.Radio(choices=["rainbow","plasma","terrain"],label="Colormap")
choicewith gr.Column(scale=50):
= gr.Button("Restart",variant="secondary") # different button theme, variant="primary"
emptyBtn with gr.Row():
=gr.Image(label="DEM")
showimg= gr.Image(label="Slope")
img_output
# Use button event listeners to active the show_dem function to process uploaded files
upload_button.upload(calculate_slope, [upload_button], [showimg,img_output])
choice.change(calculate_slope, [upload_button,choice], [showimg,img_output])
=[upload_button,showimg,img_output],show_progress=True)
emptyBtn.click(reset_state,outputs
demo.launch()