Skip to content
Snippets Groups Projects
Commit a0858708 authored by GRUPO3_HACKATHON's avatar GRUPO3_HACKATHON :christmas_tree:
Browse files

Update file hackathon.ipynb

parent 5d3eaf22
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:bf1e1f14-3a8f-4346-9268-0638f16257f2 tags: %% Cell type:markdown id:bf1e1f14-3a8f-4346-9268-0638f16257f2 tags:
# Agricultura Familiar Conectada: Plataforma Web para Optimizar Cultivos con NDVI y NDWI # Agricultura Familiar Conectada: Plataforma Web para Optimizar Cultivos con NDVI y NDWI
%% Cell type:markdown id:d9e05d42-0175-41fd-a589-680e8354f145 tags: %% Cell type:markdown id:d9e05d42-0175-41fd-a589-680e8354f145 tags:
### Casos de estudio ### Casos de estudio
* Cuenca del río Grande en el área Central de Panamá * Cuenca del río Grande en el área Central de Panamá
%% Cell type:markdown id:ae13de6f-8a8f-4bbe-995e-b1e1750b9999 tags: %% Cell type:markdown id:ae13de6f-8a8f-4bbe-995e-b1e1750b9999 tags:
### Objetivo General ### Objetivo General
"Desarrollar una plataforma web innovadora y accesible para agricultores familiares, basada en cálculos de los índices NDVI y NDWI, que les permita mejorar la toma de decisiones y optimizar el manejo de cultivos mediante el monitoreo de la salud de las plantas y la disponibilidad de agua en sus terrenos agrícolas ee identificar posibles zonas inundables en el area." "Desarrollar una plataforma web innovadora y accesible para agricultores familiares, basada en cálculos de los índices NDVI y NDWI, que les permita mejorar la toma de decisiones y optimizar el manejo de cultivos mediante el monitoreo de la salud de las plantas y la disponibilidad de agua en sus terrenos agrícolas ee identificar posibles zonas inundables en el area."
%% Cell type:markdown id:622f4ddd-b1ce-447d-83c4-b0f5c8538271 tags: %% Cell type:markdown id:622f4ddd-b1ce-447d-83c4-b0f5c8538271 tags:
### Objetivos Específicos ### Objetivos Específicos
* Desarrollar la plataforma web: Crear una plataforma en línea que sea intuitiva, fácil de usar y accesible desde diversos dispositivos (como computadoras, tabletas y teléfonos móviles) para garantizar que los agricultores familiares puedan acceder a ella y utilizarla de manera efectiva. * Desarrollar la plataforma web: Crear una plataforma en línea que sea intuitiva, fácil de usar y accesible desde diversos dispositivos (como computadoras, tabletas y teléfonos móviles) para garantizar que los agricultores familiares puedan acceder a ella y utilizarla de manera efectiva.
* Integrar datos de teledetección: Automatizar la descarga de datos de los satilites y delimitados por las parcelas que el usuario seleccione. * Integrar datos de teledetección: Automatizar la descarga de datos de los satilites y delimitados por las parcelas que el usuario seleccione.
* Identificar la calidad de la cobertura vegetal * Identificar la calidad de la cobertura vegetal
* Identificar las potencialidades de concentración de agua superficial * Identificar las potencialidades de concentración de agua superficial
* Definir los principales usos de suelo * Definir los principales usos de suelo
* Delimitación de áreas de inundación por influencia topográfica * Delimitación de áreas de inundación por influencia topográfica
* Establecer bases de datos de parcelas agrícolas * Establecer bases de datos de parcelas agrícolas
* Implementar alertas y notificaciones cuando se detecten cambios significativos en los índices NDVI y NDWI, señalando posibles situaciones de estrés hídrico o problemas en el crecimiento de los cultivos. * Implementar alertas y notificaciones cuando se detecten cambios significativos en los índices NDVI y NDWI, señalando posibles situaciones de estrés hídrico o problemas en el crecimiento de los cultivos.
* Facilitar la interacción y colaboración al implementar funciones de interacción social en la plataforma para que los agricultores familiares puedan compartir experiencias, hacer preguntas y recibir asesoramiento de otros agricultores y expertos agrícolas. * Facilitar la interacción y colaboración al implementar funciones de interacción social en la plataforma para que los agricultores familiares puedan compartir experiencias, hacer preguntas y recibir asesoramiento de otros agricultores y expertos agrícolas.
%% Cell type:markdown id:5c773f94-cbd3-4bc4-9a9c-73f23173ca1d tags: %% Cell type:markdown id:5c773f94-cbd3-4bc4-9a9c-73f23173ca1d tags:
## Metodología ## Metodología
### Planteamiento del problema ### Planteamiento del problema
Las áreas geográficas de provincias centrales en Panamá presentan características naturales morfológicas favorables para los procesos de inundaciones. Estas áreas geográficas presentan importantes actividades económicas de explotación del sector primario y sobresalientes ecosistemas. Las áreas geográficas de provincias centrales en Panamá presentan características naturales morfológicas favorables para los procesos de inundaciones. Estas áreas geográficas presentan importantes actividades económicas de explotación del sector primario y sobresalientes ecosistemas.
De igual manera nuestros agricultores se enfrentan a retos nunca antes vistos, fenómenos climáticos extremos como sequias, inundaciones, Ciclones tropicales, degradación de la tierra, entre otros. Estos fenómenos naturales alteran en gran medida los valores nutricionales y químicos de los suelos en que los cultivos regularmente se desarrollan. De igual manera nuestros agricultores se enfrentan a retos nunca antes vistos, fenómenos climáticos extremos como sequias, inundaciones, Ciclones tropicales, degradación de la tierra, entre otros. Estos fenómenos naturales alteran en gran medida los valores nutricionales y químicos de los suelos en que los cultivos regularmente se desarrollan.
Mediante el presente análisis, se proyecta identificar las áreas potenciales de concentración de agua superficial como datos relevantes para delimitar áreas de inundación por la naturaleza del territorio y como potencialidad para el aprovechamiento del recursos hídricos para actividades económicas importantes como la agricultura. Mediante el presente análisis, se proyecta identificar las áreas potenciales de concentración de agua superficial como datos relevantes para delimitar áreas de inundación por la naturaleza del territorio y como potencialidad para el aprovechamiento del recursos hídricos para actividades económicas importantes como la agricultura.
%% Cell type:markdown id:4d5b2e96-7255-487f-81f9-ab9ecc136d17 tags: %% Cell type:markdown id:4d5b2e96-7255-487f-81f9-ab9ecc136d17 tags:
## Procedimiento ## Procedimiento
1. Delimitacion de Zonas agricolas mediante el uso de mapa de cobertura boscosa y uso de suelo gestionando de información de carácter satelital del sitio de Copernicus y procesadas en QGIS 3.22 1. Delimitacion de Zonas agricolas mediante el uso de mapa de cobertura boscosa y uso de suelo gestionando de información de carácter satelital del sitio de Copernicus y procesadas en QGIS 3.22
%% Cell type:markdown id:595feab2-b299-4eed-89d6-629021683bdc tags: %% Cell type:markdown id:595feab2-b299-4eed-89d6-629021683bdc tags:
<img src="./img/landcover.png" /> <img src="./img/landcover.png" />
%% Cell type:markdown id:9c2060e1-9132-425d-be8f-a43790e150b3 tags: %% Cell type:markdown id:9c2060e1-9132-425d-be8f-a43790e150b3 tags:
# for Raster files 'tiff' manipulation # for Raster files 'tiff' manipulation
import rasterio import rasterio
# libraries for array manipulation # libraries for array manipulation
import numpy as np import numpy as np
import pandas as pd import pandas as pd
%% Cell type:code id:c177b48b tags: %% Cell type:code id:c177b48b tags:
``` python ``` python
def readTiffBand(tiff_file, band_number): def readTiffBand(tiff_file, band_number):
""" """
Reading the specific band from the 'tiff' file. Reading the specific band from the 'tiff' file.
""" """
with rasterio.open(tiff_file) as dataset: with rasterio.open(tiff_file) as dataset:
band = dataset.read(band_number) band = dataset.read(band_number)
return band return band
``` ```
%% Cell type:markdown id:a18e63b6-1b41-4f15-aeca-676956e3d3cb tags: %% Cell type:markdown id:a18e63b6-1b41-4f15-aeca-676956e3d3cb tags:
2. Calculamos el Índice Normalizado de Diferencia de Vegetación, utilizando codigos en Python 2. Calculamos el Índice Normalizado de Diferencia de Vegetación, utilizando codigos en Python
NDVI = (NIR-Red) / (NIR+Red) NDVI = (NIR-Red) / (NIR+Red)
NIR= luz del infrarrojo cercano y NIR= luz del infrarrojo cercano y
Rojo= luz roja visible Rojo= luz roja visible
Entre los valores de referencia de índice que se interpretarán calculando el NDVI, se encuentran los siguientes: Entre los valores de referencia de índice que se interpretarán calculando el NDVI, se encuentran los siguientes:
| Min | Max | State | | Min | Max | State |
|------|------|-----------------------------| |------|------|-----------------------------|
| 0.1 | 0.2 | Suelo desnudo | | 0.1 | 0.2 | Suelo desnudo |
| 0.2 | 1 | Plantas | | 0.2 | 1 | Plantas |
| 0.5 | 0.5 | Vegetación densa y saludable| | 0.5 | 0.5 | Vegetación densa y saludable|
| 0.2 | 0.5 | Vegetación dispersa | | 0.2 | 0.5 | Vegetación dispersa |
Valores negativos = Concentración de agua, estructuras artificiales y rocas entre otros. Valores negativos = Concentración de agua, estructuras artificiales y rocas entre otros.
%% Cell type:code id:5868bef0 tags: %% Cell type:code id:5868bef0 tags:
``` python ``` python
def calculateNDVI(band_red, band_nir): def calculateNDVI(band_red, band_nir):
""" """
Calculating NDVI index given the red and near infrared band. Calculating NDVI index given the red and near infrared band.
""" """
# In case you don't have cero values over the bands # In case you don't have cero values over the bands
#ndvi = (band_nir - band_red) / (band_nir + band_red) #ndvi = (band_nir - band_red) / (band_nir + band_red)
# Cero values won't be valid # Cero values won't be valid
element1 = (band_nir - band_red) element1 = (band_nir - band_red)
element2 = (band_nir + band_red) element2 = (band_nir + band_red)
ndvi = np.divide(element1, element2, out=np.zeros_like(element1), where=element2!=0) ndvi = np.divide(element1, element2, out=np.zeros_like(element1), where=element2!=0)
return ndvi return ndvi
``` ```
%% Cell type:markdown id:64302660-61a1-445b-a35c-3ebfafb71c8a tags: %% Cell type:markdown id:64302660-61a1-445b-a35c-3ebfafb71c8a tags:
<img src="./img/NDVI.png" /> <img src="./img/NDVI.png" />
%% Cell type:markdown id:c87217b4-0fcd-46c5-a492-4d99c8be0be6 tags: %% Cell type:markdown id:c87217b4-0fcd-46c5-a492-4d99c8be0be6 tags:
4. Cálculo de Índice de Agua de Diferencia Normalizada (NDWI), con la finalidad de identificar concentraciones de agua sobre la superficie de la tierra. Se aplicará la siguiente fórmula 4. Cálculo de Índice de Agua de Diferencia Normalizada (NDWI), con la finalidad de identificar concentraciones de agua sobre la superficie de la tierra. Se aplicará la siguiente fórmula
NDWI = (Green – NIR)/(Green + NIR) NDWI = (Green – NIR)/(Green + NIR)
Green = luz de banda verde Green = luz de banda verde
NIR = luz del infrarrojo cercano NIR = luz del infrarrojo cercano
| Min | Max | State | | Min | Max | State |
|------|-----|--------------------------------------| |------|-----|--------------------------------------|
| 0.2 | 1 | Superficie del agua | | 0.2 | 1 | Superficie del agua |
| 0,0 | 0,2 | Inundación, humedad | | 0,0 | 0,2 | Inundación, humedad |
|- 0,3 | 0,0 | Sequía moderada, superficies sin agua| |- 0,3 | 0,0 | Sequía moderada, superficies sin agua|
| -1 | -0,3| Sequía, superficies sin agua | | -1 | -0,3| Sequía, superficies sin agua |
%% Cell type:code id:6a97d07d tags: %% Cell type:code id:6a97d07d tags:
``` python ``` python
def calculateNDWI(band_green, band_nir): def calculateNDWI(band_green, band_nir):
""" """
Calculating NDWI index given the green and near infrared band. Calculating NDWI index given the green and near infrared band.
""" """
# In case you don't have cero values over the bands # In case you don't have cero values over the bands
#ndwi = (band_green - band_nir) / (band_green + band_nir) #ndwi = (band_green - band_nir) / (band_green + band_nir)
# Cero values won't be valid # Cero values won't be valid
element1 = (band_green - band_nir) element1 = (band_green - band_nir)
element2 = (band_green + band_nir) element2 = (band_green + band_nir)
ndwi = np.divide(element1, element2, out=np.zeros_like(element1), where=element2!=0) ndwi = np.divide(element1, element2, out=np.zeros_like(element1), where=element2!=0)
return ndwi return ndwi
``` ```
%% Cell type:markdown id:71134f4a-04fe-4976-9f16-4b2bea08db92 tags: %% Cell type:markdown id:71134f4a-04fe-4976-9f16-4b2bea08db92 tags:
<img src="./img/NDWI.png" /> <img src="./img/NDWI.png" />
%% Cell type:code id:3ba41e31 tags: %% Cell type:code id:3ba41e31 tags:
``` python ``` python
def write_index_to_tiff(index_array, output_tiff_file, tiff_metadata): def write_index_to_tiff(index_array, output_tiff_file, tiff_metadata):
""" """
Write the computed index array to the new 'tiff' file with the same metadata as the input 'tiff' file. Write the computed index array to the new 'tiff' file with the same metadata as the input 'tiff' file.
""" """
with rasterio.open(output_tiff_file, 'w', **tiff_metadata) as dst: with rasterio.open(output_tiff_file, 'w', **tiff_metadata) as dst:
dst.write(index_array, 1) dst.write(index_array, 1)
``` ```
%% Cell type:code id:d8bdbf9f tags: %% Cell type:code id:d8bdbf9f tags:
``` python ``` python
def update_index_metadata(band_file, name_index, index_array): def update_index_metadata(band_file, name_index, index_array):
""" """
Update metada from the computed index array Update metada from the computed index array
""" """
# Reading metadata from 'tiff' file # Reading metadata from 'tiff' file
with rasterio.open(band_file) as dataset: with rasterio.open(band_file) as dataset:
tiff_metadata = dataset.profile tiff_metadata = dataset.profile
# Updating metadata from computed index array # Updating metadata from computed index array
tiff_metadata.update(count=1, dtype=str(index_array.dtype)) tiff_metadata.update(count=1, dtype=str(index_array.dtype))
# Saving computed index array to a 'tiff' file # Saving computed index array to a 'tiff' file
output_index_tiff = f'./outputs/output_{name_index}.tif' output_index_tiff = f'./outputs/output_{name_index}.tif'
write_index_to_tiff(index_array, output_index_tiff, tiff_metadata) write_index_to_tiff(index_array, output_index_tiff, tiff_metadata)
``` ```
%% Cell type:code id:6a1e0f4f tags: %% Cell type:code id:6a1e0f4f tags:
``` python ``` python
# Reading green band (band 3), red band (band 4) and near infrared band (band 8) from 'tiff' files # Reading green band (band 3), red band (band 4) and near infrared band (band 8) from 'tiff' files
band3_file = './Files/sentinel_2/banda_3/T17PNK20230427T155529B03_10m.tif' band3_file = './sentinel_2/banda_3/T17PNK20230427T155529B03_10m.tif'
band4_file = './Files/sentinel_2/banda_4/T17PNK20230427T155529B04_10m.tif' band4_file = './sentinel_2/banda_4/T17PNK20230427T155529B04_10m.tif'
band8_file = './Files/sentinel_2/banda_8/T17PNK20230427T155529B08_10m.tif' band8_file = './sentinel_2/banda_8/T17PNK20230427T155529B08_10m.tif'
band_green = readTiffBand(band3_file, 1).astype('float64') band_green = readTiffBand(band3_file, 1).astype('float64')
band_red = readTiffBand(band4_file, 1).astype('float64') band_red = readTiffBand(band4_file, 1).astype('float64')
band_nir = readTiffBand(band8_file, 1).astype('float64') band_nir = readTiffBand(band8_file, 1).astype('float64')
# Calculating NDVI # Calculating NDVI
ndvi = calculateNDVI(band_red, band_nir) ndvi = calculateNDVI(band_red, band_nir)
update_index_metadata(band8_file, "ndvi", ndvi) update_index_metadata(band8_file, "ndvi", ndvi)
# Calculating NDWI # Calculating NDWI
ndwi = calculateNDWI(band_green, band_nir) ndwi = calculateNDWI(band_green, band_nir)
update_index_metadata(band8_file, "ndwi", ndwi) update_index_metadata(band8_file, "ndwi", ndwi)
``` ```
%% Cell type:code id:75bcf2dd tags: %% Cell type:code id:75bcf2dd tags:
``` python ``` python
#Dataset for the calculated ndvi index #Dataset for the calculated ndvi index
df_ndvi = pd.DataFrame(ndvi) df_ndvi = pd.DataFrame(ndvi)
df_ndvi.to_csv("ndvi_index.csv", index=False) df_ndvi.to_csv("ndvi_index.csv", index=False)
#df_ndvi #df_ndvi
``` ```
%% Cell type:code id:3d50f7f7 tags: %% Cell type:code id:3d50f7f7 tags:
``` python ``` python
#Dataset for the calculated ndwi index #Dataset for the calculated ndwi index
df_ndwi = pd.DataFrame(ndwi) df_ndwi = pd.DataFrame(ndwi)
df_ndwi.to_csv("ndwi_index.csv", index=False) df_ndwi.to_csv("ndwi_index.csv", index=False)
#df_ndwi #df_ndwi
``` ```
%% Cell type:code id:889a6819 tags: %% Cell type:code id:889a6819 tags:
``` python ``` python
``` ```
%% Cell type:code id:836a614b-9dcb-44c6-8114-dd96b52fd513 tags: %% Cell type:code id:836a614b-9dcb-44c6-8114-dd96b52fd513 tags:
``` python ``` python
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment