marcossalinas commited on
Commit
cd0c3b0
1 Parent(s): 5aa3885

Primer commit

Browse files
Files changed (4) hide show
  1. README.md +9 -12
  2. desertIArag/303/263n.png +0 -0
  3. desertificacion_ai.py +360 -0
  4. requirements.txt +5 -0
README.md CHANGED
@@ -1,12 +1,9 @@
1
- ---
2
- title: DesertIAragon
3
- emoji: 💻
4
- colorFrom: purple
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.2.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
1
+ # desertificacion-AI-Streamlit
2
+
3
+ ## AI Saturdays - I Edición Zaragoza - CURSO BÁSICO DE IA
4
+
5
+ ### Streamlit app
6
+
7
+ Enlace para lanzar la aplicación:
8
+
9
+ https://share.streamlit.io/desertificacion-ai/desertificacion-ai-streamlit/main/desertificacion_ai.py
 
 
 
desertIArag/303/263n.png ADDED
desertificacion_ai.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import numpy as np
3
+ import random
4
+ import skimage.io as skio
5
+ import streamlit as st
6
+
7
+ from PIL import Image
8
+ from rasterio import plot
9
+ from sklearn.ensemble import RandomForestRegressor
10
+ from sklearn.metrics import mean_squared_error
11
+
12
+ # Image.MAX_IMAGE_PIXELS = None
13
+
14
+ st.set_page_config(
15
+ page_title='Aplicación megachula',
16
+ page_icon=':cactus:',
17
+ layout='centered'
18
+ )
19
+
20
+ # Título
21
+ # ======
22
+
23
+ image = Image.open('desertIAragón.png')
24
+ st.image(image, width=700)
25
+
26
+ st.title('Desertificación en Aragón')
27
+ st.subheader('AI Saturdays - I Edición Zaragoza - CURSO BÁSICO DE IA')
28
+
29
+ # Librerías
30
+ # =========
31
+
32
+ st.markdown('---')
33
+ with st.expander('Librerías'):
34
+ st.markdown("""
35
+ * matplotlib   3.5.1
36
+ * numpy     1.22.2
37
+ * PIL         9.0.1
38
+ * rasterio     1.2.10
39
+ * scikit-image   0.19.2
40
+ * scikit-learn   1.0.2
41
+ * streamlit     1.5.1
42
+ """)
43
+
44
+ # Imágenes satelitales
45
+ # ====================
46
+
47
+ @st.cache
48
+ def lee_imagenes():
49
+ img_name_1 = 'imagen_1.tif'
50
+ img_name_2 = 'imagen_2.tif'
51
+ img_name_3 = 'imagen_3.tif'
52
+ img_name_4 = 'imagen_4.tif'
53
+ img_name_5 = 'imagen_5.tif'
54
+ img_name_6 = 'imagen_6.tif'
55
+
56
+ img1 = skio.imread(img_name_1, plugin='pil')
57
+ img2 = skio.imread(img_name_2, plugin='pil')
58
+ img3 = skio.imread(img_name_3, plugin='pil')
59
+ img4 = skio.imread(img_name_4, plugin='pil')
60
+ img5 = skio.imread(img_name_5, plugin='pil')
61
+ img6 = skio.imread(img_name_6, plugin='pil')
62
+
63
+ return img1, img2, img3, img4, img5, img6
64
+
65
+ img1 = lee_imagenes()[0]
66
+ img2 = lee_imagenes()[1]
67
+ img3 = lee_imagenes()[2]
68
+ img4 = lee_imagenes()[3]
69
+ img5 = lee_imagenes()[4]
70
+ img6 = lee_imagenes()[5]
71
+
72
+ # @st.cache
73
+ def muestra_imagenes():
74
+ st.markdown('---')
75
+ st.subheader('Imágenes satelitales')
76
+
77
+ col11, col12 = st.columns(2)
78
+ with col11:
79
+ st.write('1 - 20210316 - Tamaño:', img1.shape)
80
+ st.image(img1, width=350, clamp=True)
81
+ with col12:
82
+ st.write('2 - 20210405 - Tamaño:', img1.shape)
83
+ st.image(img2, width=350, clamp=True)
84
+
85
+ col21, col22 = st.columns(2)
86
+ with col21:
87
+ st.write('3 - 20210505 - Tamaño:', img1.shape)
88
+ st.image(img3, width=350, clamp=True)
89
+ with col22:
90
+ st.write('4 - 20210525 - Tamaño:', img1.shape)
91
+ st.image(img4, width=350, clamp=True)
92
+
93
+ col31, col32 = st.columns(2)
94
+ with col31:
95
+ st.write('5 - 20210614 - Tamaño:', img1.shape)
96
+ st.image(img5, width=350, clamp=True)
97
+ with col32:
98
+ st.write('6 - 20210624 - Tamaño:', img1.shape)
99
+ st.image(img6, width=350, clamp=True)
100
+
101
+ muestra_imagenes()
102
+
103
+ # Banda lateral
104
+ # =============
105
+
106
+ st.sidebar.markdown('# Cuadrícula de estudio')
107
+ st.sidebar.markdown("""
108
+ Cuadrícula de estudio dentro de la imagen, con un ancho y un alto en píxeles según lo indicado.
109
+
110
+ La esquina superior izquierda de la cuadrícula se determinará con las coodenadas $x_0$ e $y_0$.
111
+ """
112
+ )
113
+
114
+ # Sidebar
115
+ # -------
116
+
117
+ x0 = 0
118
+ x1 = min(img1.shape[1], img2.shape[1], img3.shape[1], img4.shape[1], img5.shape[1], img6.shape[1])
119
+ y0 = 0
120
+ y1 = min(img1.shape[0], img2.shape[0], img3.shape[0], img4.shape[0], img5.shape[0], img6.shape[0])
121
+
122
+ coord_x = st.sidebar.slider('Coordenada x.0', x0, x1)
123
+ coord_y = st.sidebar.slider('Coordenada y.0', y0, y1)
124
+
125
+ a0 = 1
126
+ a1 = 250
127
+ ancho = st.sidebar.slider('Ancho/Alto de la cuadrícula', a0, a1, value=5)
128
+
129
+ if coord_x + ancho > x1:
130
+ coord_x = x1 - ancho
131
+ xn = x1
132
+ else:
133
+ xn = coord_x + ancho
134
+
135
+ if coord_y + ancho > y1:
136
+ coord_y = y1 - ancho
137
+ yn = y1
138
+ else:
139
+ yn = coord_y + ancho
140
+
141
+ # st.sidebar.write('x0', coord_x)
142
+ # st.sidebar.write('y0', coord_y)
143
+ # st.sidebar.write('xn', xn)
144
+ # st.sidebar.write('yn', yn)
145
+ # st.sidebar.write('ancho', ancho)
146
+ # st.sidebar.write('x1', x1)
147
+ # st.sidebar.write('y1', y1)
148
+
149
+ # Cuadrículas
150
+ # ===========
151
+
152
+ st.markdown('---')
153
+ st.subheader('Cuadriculas de estudio e índice de vegetación NDVI')
154
+
155
+ x0 = coord_x
156
+ y0 = coord_y
157
+
158
+ st.markdown(f'Coordenadas de la esquina superior izquierda:   $x_0$ * $y_0$ = {x0} * {y0} px')
159
+ st.markdown(f'Coordenadas de la esquina superior derecha:   $x_n$ * $y_n$ = {xn} * {yn} px')
160
+
161
+ cuadricula1 = img1[y0:yn, x0:xn]
162
+ cuadricula2 = img2[y0:yn, x0:xn]
163
+ cuadricula3 = img3[y0:yn, x0:xn]
164
+ cuadricula4 = img4[y0:yn, x0:xn]
165
+ cuadricula5 = img5[y0:yn, x0:xn]
166
+ cuadricula6 = img6[y0:yn, x0:xn]
167
+ cuadriculas = (cuadricula1, cuadricula2, cuadricula3, cuadricula4, cuadricula5, cuadricula6)
168
+
169
+ def zona_ndvi(ndvi):
170
+ """Zona de representación según el rango."""
171
+ if ndvi < 0:
172
+ return 'Zona sin vegetación'
173
+ elif ndvi > 0.3:
174
+ return 'Zona con vegetación'
175
+ else:
176
+ return 'Zona con algo de vegetación'
177
+
178
+ i = 0
179
+ for cuadricula in cuadriculas:
180
+ i += 1
181
+ st.markdown(f'')
182
+ st.markdown(f'##### Cuadrícula {i}')
183
+ st.image(cuadricula, width=400, clamp=True)
184
+
185
+ st.text('Valor NDVI de cada píxel de la cuadrícula:')
186
+ np_data = np.asarray(cuadricula)
187
+ st.write(np.round(np_data, 3))
188
+
189
+ np_data_mean = np_data.mean()
190
+ st.markdown(f'##### Valor promedio NDVI del conjunto de píxeles de la cuadrícula: &emsp; {np_data_mean:.3f}')
191
+
192
+ zona = zona_ndvi(np_data_mean)
193
+ st.markdown(f'##### Interpretación del valor promedio NDVI de la cuadrícula {i} &ensp; → &ensp; {zona}')
194
+
195
+ # Random Forest
196
+ # =============
197
+
198
+ st.markdown('---')
199
+ st.subheader('Predicción de la IA')
200
+ st.markdown(
201
+ """
202
+ El sistema se entrena con una porción igual de cada una de las imágenes 1 a 5. Esta porción es un recuadro de \
203
+ coordenadas aleatorias y dimensiones igual al ancho/alto de la cuadrícula indicado en la banda lateral.
204
+
205
+ La razón de elegir un recuadro reducido es el elevado coste computacional que tiene el entrenamiento del sistema. \
206
+ De esta forma la aplicación puede mostrar unos resultados de una forma relativamente ágil.
207
+
208
+ Para el test se ha elegido las imágenes de las cuadrículas 1 a 5 con las que se ha obtenido el índice NDVI.
209
+
210
+ La predicción se hace con la cuadrícula 6. Se compara la imagen original con la predicha por la IA.
211
+ """
212
+ )
213
+
214
+ # Imágenes de entrenamiento
215
+ # -------------------------
216
+ numpydata1 = np.asarray(img1)
217
+ numpydata2 = np.asarray(img2)
218
+ numpydata3 = np.asarray(img3)
219
+ numpydata4 = np.asarray(img4)
220
+ numpydata5 = np.asarray(img5)
221
+
222
+ # Imágenes para test
223
+ # ------------------
224
+ numpydata6 = np.asarray(img6)
225
+
226
+ X = []
227
+ y = []
228
+
229
+ dim = ancho
230
+ i0 = random.randint(0, x1 - dim) # Mitad izquierda de la imagen
231
+ j0 = random.randint(0, y1 - dim)
232
+ ik = i0 + dim - 2
233
+ jk = j0 + dim - 2
234
+
235
+ for i in range(i0, ik):
236
+ for j in range(j0, jk):
237
+ X.append(
238
+ [
239
+ numpydata1[i, j], numpydata1[i, j + 1], numpydata1[i, j + 2],
240
+ numpydata1[i + 1, j], numpydata1[i + 1, j + 1], numpydata1[i + 1, j + 2],
241
+ numpydata1[i + 2, j], numpydata1[i + 2, j + 1], numpydata1[i + 2, j + 2],
242
+ numpydata2[i, j], numpydata2[i, j + 1], numpydata2[i, j + 2],
243
+ numpydata2[i + 1, j], numpydata2[i + 1, j + 1], numpydata2[i + 1, j + 2],
244
+ numpydata2[i + 2, j], numpydata2[i + 2, j + 1], numpydata2[i + 2, j + 2],
245
+ numpydata3[i, j], numpydata3[i, j + 1], numpydata3[i, j + 2],
246
+ numpydata3[i + 1, j], numpydata3[i + 1, j + 1], numpydata3[i + 1, j + 2],
247
+ numpydata3[i + 2, j], numpydata3[i + 2, j + 1], numpydata3[i + 2, j + 2],
248
+ numpydata4[i, j], numpydata4[i, j + 1], numpydata4[i, j + 2],
249
+ numpydata4[i + 1, j], numpydata4[i + 1, j + 1], numpydata4[i + 1, j + 2],
250
+ numpydata4[i + 2, j], numpydata4[i + 2, j + 1], numpydata4[i + 2, j + 2],
251
+ numpydata5[i, j], numpydata5[i, j + 1], numpydata5[i, j + 2],
252
+ numpydata5[i + 1, j], numpydata5[i + 1, j + 1], numpydata5[i + 1, j + 2],
253
+ numpydata5[i + 2, j], numpydata5[i + 2, j + 1], numpydata5[i + 2, j + 2]
254
+ ]
255
+ )
256
+ y.append(numpydata6[i + 1, j + 1])
257
+
258
+ # Clasificador
259
+ # ------------
260
+
261
+ cls = RandomForestRegressor()
262
+
263
+ # Entrenamiento
264
+ # -------------
265
+
266
+ cls.fit(X, y)
267
+
268
+ A = []
269
+ b = []
270
+
271
+ i0 = x0
272
+ j0 = y0
273
+ ik = i0 + dim
274
+ jk = j0 + dim
275
+
276
+ for i in range(j0, jk):
277
+ for j in range(i0, ik):
278
+ A.append(
279
+ [
280
+ numpydata1[i, j], numpydata1[i, j + 1], numpydata1[i, j + 2],
281
+ numpydata1[i + 1, j], numpydata1[i + 1, j + 1], numpydata1[i + 1, j + 2],
282
+ numpydata1[i + 2, j], numpydata1[i + 2, j + 1], numpydata1[i + 2, j + 2],
283
+ numpydata2[i, j], numpydata2[i, j + 1], numpydata2[i, j + 2],
284
+ numpydata2[i + 1, j], numpydata2[i + 1, j + 1], numpydata2[i + 1, j + 2],
285
+ numpydata2[i + 2, j], numpydata2[i + 2, j + 1], numpydata2[i + 2, j + 2],
286
+ numpydata3[i, j], numpydata3[i, j + 1], numpydata3[i, j + 2],
287
+ numpydata3[i + 1, j], numpydata3[i + 1, j + 1], numpydata3[i + 1, j + 2],
288
+ numpydata3[i + 2, j], numpydata3[i + 2, j + 1], numpydata3[i + 2, j + 2],
289
+ numpydata4[i, j], numpydata4[i, j + 1], numpydata4[i, j + 2],
290
+ numpydata4[i + 1, j], numpydata4[i + 1, j + 1], numpydata4[i + 1, j + 2],
291
+ numpydata4[i + 2, j], numpydata4[i + 2, j + 1], numpydata4[i + 2, j + 2],
292
+ numpydata5[i, j], numpydata5[i, j + 1], numpydata5[i, j + 2],
293
+ numpydata5[i + 1, j], numpydata5[i + 1, j + 1], numpydata5[i + 1, j + 2],
294
+ numpydata5[i + 2, j], numpydata5[i + 2, j + 1], numpydata5[i + 2, j + 2]
295
+ ]
296
+ )
297
+ b.append(numpydata6[i + 1, j + 1])
298
+
299
+ b_predicho = cls.predict(A)
300
+ mse = mean_squared_error(b, b_predicho)
301
+
302
+ # Plot
303
+ # ----
304
+
305
+ tfreal = b
306
+ tfpredicho = b_predicho.tolist()
307
+
308
+ anp=np.array(tfpredicho)
309
+ anp=np.reshape(anp, (ik - i0, jk - j0))
310
+ org=np.array(tfreal)
311
+ org=np.reshape(org, (ik - i0, jk - j0))
312
+
313
+ st.markdown(f'Coordenadas de la esquina superior izquierda: &emsp; $i_0$ * $j_0$ = {i0} * {j0} px')
314
+ st.markdown(f'Coordenadas de la esquina superior derecha: &emsp; $i_n$ * $j_n$ = {ik} * {jk} px')
315
+
316
+ st.markdown(f'##### Error cuadrático promedio: &emsp; {mse:.5f}')
317
+
318
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
319
+ ax1.imshow(org.astype(np.float64), interpolation='nearest')
320
+ ax2.imshow(anp.astype(np.float64), interpolation='nearest')
321
+ ax1.set_title('Imagen original')
322
+ ax2.set_title('Imagen predicha por la IA')
323
+ st.pyplot(fig)
324
+
325
+ np_data_6 = np.asarray(cuadricula6)
326
+
327
+ np_data_mean_6 = np_data_6.mean()
328
+ np_data_mean_anp = anp.mean()
329
+
330
+ st.markdown(f'##### Valor promedio NDVI del conjunto de píxeles:')
331
+ st.markdown(f'##### Imagen original: &emsp; &emsp; &emsp; &emsp; &emsp; &emsp;{np_data_mean_6:.3f}')
332
+ st.markdown(f'##### Cuadrícula predicha por la IA: &emsp; {np_data_mean_anp:.3f}')
333
+
334
+ zona_6 = zona_ndvi(np_data_mean_6)
335
+ zona_anp = zona_ndvi(np_data_mean_anp)
336
+ st.markdown(f'##### Interpretación del valor promedio NDVI:')
337
+ st.markdown(f'##### Imagen original: &emsp; &emsp; &emsp; &emsp; &emsp; &ensp; → &ensp; {zona_6}')
338
+ st.markdown(f'##### Cuadrícula predicha por la IA: &emsp; → &ensp; {zona_anp}')
339
+
340
+ # Créditos
341
+ # ========
342
+
343
+ st.markdown('---')
344
+ with st.expander('Créditos'):
345
+ st.markdown(
346
+ """
347
+ 06/03/2022
348
+
349
+ Autores:
350
+
351
+ * [Eva de Miguel](https://www.linkedin.com/in/eva-de-miguel-morales-a63938a0/)
352
+ * [Pedro Biel](www.linkedin.com/in/pedrobiel)
353
+ * [Yinet Castiblanco](https://www.linkedin.com/in/yinethcastiblancorojas/)
354
+
355
+ ---
356
+
357
+ * **Artículo Medium** [Medium](https://medium.com/saturdays-ai/predicci%C3%B3n-de-zonas-de-desertificaci%C3%B3n-en-arag%C3%B3n-usando-ia-ee59c15c12a5)
358
+ * **Código fuente:** [GitHub](https://github.com/desertificacion-AI/desertificacion-AI)
359
+ """
360
+ )
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ matplotlib==3.5.1
2
+ rasterio==1.2.10
3
+ scikit-image==0.19.2
4
+ scikit-learn==1.0.2
5
+ streamlit==1.5.1