8
8
from datetime import datetime , timedelta
9
9
import numpy as np
10
10
11
-
12
11
def generate_image (raster_path , csv_path , data_path , shapefile_path = None ):
13
12
# Definir la ruta del logo y la ruta de guardado del PNG
14
13
logo_path = os .path .join (data_path , "instituteLogo.jpg" )
15
14
png_file = os .path .join (os .path .dirname (raster_path ), os .path .basename (raster_path ).replace (".tif" , "_image.png" ))
16
15
17
16
date = os .path .basename (raster_path ).split ("_" )[1 ].split ("." )[0 ]
18
17
date_obj = datetime .strptime (date , "%Y-%m-%d" )
19
- # Sumar un día
20
18
new_date_obj = date_obj + timedelta (days = 1 )
21
-
22
- # Convertir el objeto datetime de nuevo a string
23
19
new_date_str = new_date_obj .strftime ("%Y-%m-%d" )
24
-
25
20
csv_title = os .path .basename (csv_path ).split ("_" )[1 ].replace (".csv" , "" )
26
21
27
22
# Leer los rangos de colores desde el CSV
28
23
color_ranges = pd .read_csv (csv_path )
29
24
30
25
with rasterio .open (raster_path ) as src :
31
- # Leer la primera banda como un arreglo numpy
32
26
band = src .read (1 )
33
27
raster_bounds = src .bounds
34
28
raster_crs = src .crs
35
29
30
+ if 'season' in color_ranges .columns :
31
+ current_date = datetime .now ()
32
+ current_season = determine_season (current_date )
33
+ filtered_ranges = color_ranges [color_ranges ['season' ] == current_season ]
34
+ else :
35
+ filtered_ranges = color_ranges
36
36
37
- min_vals = color_ranges ['min' ].astype (float ).tolist ()
38
- max_vals = color_ranges ['max' ].astype (float ).tolist ()
39
- cmap_colors = color_ranges ['color' ].tolist ()
37
+ min_vals = filtered_ranges ['min' ].astype (float ).tolist ()
38
+ max_vals = filtered_ranges ['max' ].astype (float ).tolist ()
39
+ cmap_colors = filtered_ranges ['color' ].tolist ()
40
40
41
41
# Crear los límites y colores para el mapa de colores
42
42
boundaries = max_vals
43
43
boundaries .insert (0 , min_vals [0 ])
44
44
cmap = LinearSegmentedColormap .from_list ('custom_cmap' , cmap_colors )
45
45
norm = BoundaryNorm (boundaries , cmap .N )
46
46
47
- title = f"CENAOS/WRF { csv_title } desde { date } hasta { new_date_str } " # Título que deseas agregar
47
+ title = f"CENAOS/WRF { csv_title } desde { date } hasta { new_date_str } "
48
48
49
49
# Configurar la figura de Matplotlib con tamaño personalizado
50
- fig , ax = plt .subplots (figsize = (12 , 8 ))
50
+ fig , ax = plt .subplots (figsize = (14 , 10 ))
51
51
52
+ alpha = 0.8
53
+ interpolation = 'nearest'
52
54
# Mostrar el mapa de colores
53
- im = ax .imshow (band , cmap = cmap , norm = norm , extent = [raster_bounds .left , raster_bounds .right , raster_bounds .bottom , raster_bounds .top ])
55
+ im = ax .imshow (band , cmap = cmap , norm = norm , extent = [raster_bounds .left , raster_bounds .right , raster_bounds .bottom , raster_bounds .top ], alpha = alpha , interpolation = interpolation )
54
56
55
57
# Añadir el shapefile si se proporciona
56
58
if shapefile_path and os .path .exists (shapefile_path ):
@@ -59,22 +61,42 @@ def generate_image(raster_path, csv_path, data_path, shapefile_path=None):
59
61
gdf .plot (ax = ax , facecolor = 'none' , edgecolor = 'black' )
60
62
61
63
# Añadir título
62
- ax .set_title (title , fontsize = 20 )
64
+ ax .set_title (title , fontsize = 18 )
65
+
66
+ # Añadir etiquetas a los ejes
67
+ ax .set_xlabel ('Longitud' , fontsize = 12 )
68
+ ax .set_ylabel ('Latitud' , fontsize = 12 )
63
69
64
70
# Añadir logo en posición absoluta
65
71
if os .path .exists (logo_path ):
66
72
logo = plt .imread (logo_path )
67
- imagebox = OffsetImage (logo , zoom = 0.2 )
68
- ab = AnnotationBbox (imagebox , (0.87 , 0.11 ), frameon = False , xycoords = 'axes fraction' ) # Coordenadas fraccionarias del eje (0.87, 0.11 )
73
+ imagebox = OffsetImage (logo , zoom = 0.15 )
74
+ ab = AnnotationBbox (imagebox , (0.85 , 0.1 ), frameon = False , xycoords = 'axes fraction' )
69
75
ax .add_artist (ab )
70
76
71
77
# Añadir barra de colores (colorbar) abajo a la izquierda
72
78
cbar = fig .colorbar (im , ticks = boundaries , orientation = 'horizontal' , boundaries = boundaries , pad = 0.1 , aspect = 30 , fraction = 0.02 )
73
79
cbar .set_label (csv_title , fontsize = 12 )
74
80
cbar .ax .tick_params (labelsize = 10 )
81
+ cbar .ax .set_xticklabels ([str (int (b )) for b in boundaries ])
75
82
76
83
# Guardar la visualización como un archivo PNG
77
- plt .savefig (png_file , bbox_inches = 'tight' )
84
+ plt .savefig (png_file , bbox_inches = 'tight' , dpi = 300 )
78
85
plt .close () # Cerrar la figura para liberar recursos de memoria
79
86
80
- print (f'Imagen procesada guardada en: { png_file } ' )
87
+ print (f'Imagen procesada guardada en: { png_file } ' )
88
+
89
+ def determine_season (date ):
90
+ # Definir los rangos de fechas para cada temporada
91
+ season1_start = datetime (date .year , 1 , 1 )
92
+ season1_end = datetime (date .year , 6 , 30 )
93
+ season2_start = datetime (date .year , 7 , 1 )
94
+ season2_end = datetime (date .year , 12 , 31 )
95
+
96
+ # Determinar la temporada basada en la fecha
97
+ if season1_start <= date <= season1_end :
98
+ return 1
99
+ elif season2_start <= date <= season2_end :
100
+ return 2
101
+ else :
102
+ return None
0 commit comments