-
Notifications
You must be signed in to change notification settings - Fork 20
/
cw_base.py
1800 lines (1579 loc) · 62.6 KB
/
cw_base.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pycoast, Writing of coastlines, borders and rivers to images in Python
#
# Copyright (C) 2011-2022 PyCoast Developers
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Base class for contour writers."""
from __future__ import annotations
import ast
import configparser
import hashlib
import json
import logging
import math
import os
from typing import Generator
import numpy as np
import pyproj
import shapefile
from PIL import Image
try:
from pyresample import AreaDefinition
except ImportError:
AreaDefinition = None
logger = logging.getLogger(__name__)
def get_resolution_from_area(area_def):
"""Get the best resolution for an area definition."""
x_size = area_def.width
y_size = area_def.height
prj = Proj(area_def.crs if hasattr(area_def, "crs") else area_def.proj_str)
if prj.is_latlong():
x_ll, y_ll = prj(area_def.area_extent[0], area_def.area_extent[1])
x_ur, y_ur = prj(area_def.area_extent[2], area_def.area_extent[3])
x_resolution = (x_ur - x_ll) / x_size
y_resolution = (y_ur - y_ll) / y_size
else:
x_resolution = (area_def.area_extent[2] - area_def.area_extent[0]) / x_size
y_resolution = (area_def.area_extent[3] - area_def.area_extent[1]) / y_size
res = min(x_resolution, y_resolution)
if res > 25000:
return "c"
elif res > 5000:
return "l"
elif res > 1000:
return "i"
elif res > 200:
return "h"
else:
return "f"
class _CoordConverter:
"""Convert coordinates from one space to in-bound image pixel column and row.
Convert the coordinate (x,y) in the coordinates
reference system ('lonlat' or 'image') into an image
x,y coordinate.
Uses the area_def methods if coord_ref is 'lonlat'.
Raises ValueError if pixel coordinates are outside the image bounds
defined by area_def.width and area_def.height.
"""
def __init__(self, coord_ref: str, area_def: AreaDefinition):
self._area_def = self._check_area_def(area_def)
convert_methods = {
"lonlat": self._lonlat_to_pixels,
"image": self._image_to_pixels,
}
if coord_ref not in convert_methods:
pretty_coord_refs = [f"'{cr_name}'" for cr_name in sorted(convert_methods.keys())]
raise ValueError(f"'coord_ref' must be one of {pretty_coord_refs}.")
self._convert_method = convert_methods[coord_ref]
def _check_area_def(self, area_def):
if AreaDefinition is None:
raise ImportError(
"Missing required 'pyresample' module, please "
"install it with 'pip install pyresample' or "
"'conda install pyresample'."
)
if not isinstance(area_def, AreaDefinition):
raise ValueError("'area_def' must be an instance of AreaDefinition")
return area_def
def __call__(self, x, y):
return self._convert_method(x, y)
def _lonlat_to_pixels(self, x, y):
return self._area_def.get_array_indices_from_lonlat(x, y)
def _image_to_pixels(self, x, y):
area_def = self._area_def
x, y = (int(x), int(y))
if x < 0:
x += area_def.width
if y < 0:
y += area_def.height
if x < 0 or y < 0 or x >= area_def.width or y >= area_def.height:
raise ValueError(
"Image pixel coords out of image bounds " f"(width={area_def.width}, height={area_def.height})."
)
return x, y
def hash_dict(dict_to_hash: dict) -> str:
"""Hash dict object by serializing with json."""
dhash = hashlib.sha256()
encoded = json.dumps(dict_to_hash, sort_keys=True).encode()
dhash.update(encoded)
return dhash.hexdigest()
class Proj(pyproj.Proj):
"""Wrapper around pyproj to add in 'is_latlong'."""
def is_latlong(self):
if hasattr(self, "crs"):
return self.crs.is_geographic
# pyproj<2.0
return super(Proj, self).is_latlong()
class ContourWriterBase(object):
"""Base class for contourwriters. Do not instantiate.
:Parameters:
db_root_path : str
Path to root dir of GSHHS and WDBII shapefiles
"""
_draw_module = "FIXME"
# This is a flag to make _add_grid aware of which draw.text
# subroutine, from PIL, aggdraw or cairo is being used
# (unfortunately they are not fully compatible).
def __init__(self, db_root_path=None):
if db_root_path is None:
self.db_root_path = os.environ.get("GSHHS_DATA_ROOT")
else:
self.db_root_path = db_root_path
@property
def is_agg(self) -> bool:
"""Get if we are using the 'agg' backend."""
return self._draw_module == "AGG"
def _draw_text(self, draw, position, txt, font, align="cc", **kwargs):
"""Draw text with agg module."""
txt_width, txt_height = draw.textsize(txt, font)
x_pos, y_pos = position
ax, ay = align.lower()
if ax == "r":
x_pos = x_pos - txt_width
elif ax == "c":
x_pos = x_pos - txt_width / 2
if ay == "b":
y_pos = y_pos - txt_height
elif ay == "c":
y_pos = y_pos - txt_width / 2
self._engine_text_draw(draw, x_pos, y_pos, txt, font, **kwargs)
def _engine_text_draw(self, draw, pos, txt, font, **kwargs):
raise NotImplementedError("Text drawing undefined for render engine")
def _add_grid(
self,
image,
area_def,
Dlon,
Dlat,
dlon,
dlat,
font=None,
write_text=True,
**kwargs,
):
"""Add a lat lon grid to image."""
draw = self._get_canvas(image)
grid_drawer = _GridDrawer(self, draw, area_def, Dlon, Dlat, dlon, dlat, font, write_text, kwargs)
grid_drawer.draw_grid()
self._finalize(draw)
def _find_bounding_box(self, xys):
lons = [x for (x, y) in xys]
lats = [y for (x, y) in xys]
return [min(lons), min(lats), max(lons), max(lats)]
def _add_shapefile_shapes(self, image, area_def, filename, feature_type=None, **kwargs):
"""Draw all shapes (polygon/poly-lines) from a shape file onto a PIL Image."""
sf = shapefile.Reader(filename)
return self.add_shapes(image, area_def, sf.shapes(), feature_type=feature_type, **kwargs)
def _add_shapefile_shape(self, image, area_def, filename, shape_id, feature_type=None, **kwargs):
"""Draw a single shape (polygon/poly-line) definition.
Accesses single shape using shape_id from a custom shape file.
"""
sf = shapefile.Reader(filename)
shape = sf.shape(shape_id)
return self.add_shapes(image, area_def, [shape], feature_type=feature_type, **kwargs)
def _add_line(self, image, area_def, lonlats, **kwargs):
"""Draw a custom polyline.
Lon and lat coordinates given by the list lonlat.
"""
# create dummpy shapelike object
shape = type("", (), {})()
shape.points = lonlats
shape.parts = [0]
shape.bbox = self._find_bounding_box(lonlats)
self.add_shapes(image, area_def, [shape], feature_type="line", **kwargs)
def _add_polygon(self, image, area_def, lonlats, **kwargs):
"""Draw a custom polygon.
Lon and lat coordinates given by the list lonlat.
"""
# create dummpy shapelike object
shape = type("", (), {})()
shape.points = lonlats
shape.parts = [0]
shape.bbox = self._find_bounding_box(lonlats)
self.add_shapes(image, area_def, [shape], feature_type="polygon", **kwargs)
def add_shapes(
self,
image,
area_def,
shapes,
feature_type=None,
x_offset=0,
y_offset=0,
**kwargs,
):
"""Draw shape objects to PIL image.
:Parameters:
image : Image
PIL Image to draw shapes on
area_def : (proj_str, area_extent) or AreaDefinition
Geolocation information for the provided image
shapes: iterable
Series of shape objects from pyshp. Can also be a series
of 2-element tuples where the first element is the shape
object and the second is a dictionary of additional drawing
parameters for this shape.
feature_type: str
'polygon' or 'line' or None for what to draw shapes as.
Default is to draw the shape with the type in the shapefile.
kwargs:
Extra drawing keyword arguments for all shapes
.. versionchanged: 1.2.0
Interface changed to have `shapes` before `feature_type` to allow
`feature_type` to be optional and default to `None`.
"""
try:
proj_def = area_def.crs if hasattr(area_def, "crs") else area_def.proj_dict
area_extent = area_def.area_extent
except AttributeError:
proj_def = area_def[0]
area_extent = area_def[1]
draw = self._get_canvas(image)
# Area and projection info
x_size, y_size = image.size
prj = Proj(proj_def)
# Calculate min and max lons and lats of interest
lon_min, lon_max, lat_min, lat_max = _get_lon_lat_bounding_box(area_extent, x_size, y_size, prj)
# Iterate through shapes
for shape in shapes:
if isinstance(shape, (list, tuple)):
new_kwargs = kwargs.copy()
if shape[1]:
new_kwargs.update(shape[1])
shape = shape[0]
else:
new_kwargs = kwargs
if self._polygon_is_irrelevant(lon_min, lon_max, lat_min, lat_max, shape):
continue
self._add_shape(
shape,
feature_type,
area_extent,
x_size,
y_size,
prj,
x_offset,
y_offset,
draw,
new_kwargs,
)
self._finalize(draw)
@staticmethod
def _polygon_is_irrelevant(lon_min, lon_max, lat_min, lat_max, shape):
# Check if polygon is possibly relevant
s_lon_ll, s_lat_ll, s_lon_ur, s_lat_ur = shape.bbox
if lon_min <= lon_max:
# Area_extent west or east of dateline
shape_is_outside_lon = lon_max < s_lon_ll or lon_min > s_lon_ur
else:
# Area_extent spans over dateline
shape_is_outside_lon = lon_max < s_lon_ll and lon_min > s_lon_ur
shape_is_outside_lat = lat_max < s_lat_ll or lat_min > s_lat_ur
return shape_is_outside_lon or shape_is_outside_lat
def _add_shape(
self,
shape,
feature_type,
area_extent,
x_size,
y_size,
prj,
x_offset,
y_offset,
draw,
new_kwargs,
):
ftype = self._feature_type_for_shape(shape, feature_type)
# iterate over shape parts (some shapes split into parts)
# dummy shape part object
parts = list(shape.parts) + [len(shape.points)]
for i in range(len(parts) - 1):
# Get pixel index coordinates of shape
points = shape.points[parts[i] : parts[i + 1]]
index_arrays, is_reduced = _get_pixel_index(
points,
area_extent,
x_size,
y_size,
prj,
x_offset=x_offset,
y_offset=y_offset,
)
# Skip empty datasets
if len(index_arrays) == 0:
return
# Make PIL draw the polygon or line
for index_array in index_arrays:
if ftype == "polygon" and not is_reduced:
# Draw polygon if dataset has not been reduced
self._draw_polygon(draw, index_array.flatten().tolist(), **new_kwargs)
elif ftype == "line" or is_reduced:
# Draw line
self._draw_line(draw, index_array.flatten().tolist(), **new_kwargs)
else:
raise ValueError("Unknown contour type: %s" % ftype)
@staticmethod
def _feature_type_for_shape(shape, feature_type):
if feature_type is not None:
return feature_type.lower()
if shape.shapeType == shapefile.POLYLINE:
ftype = "line"
elif shape.shapeType == shapefile.POLYGON:
ftype = "polygon"
else:
raise ValueError("Unsupported shape type: " + str(shape.shapeType))
return ftype
def _add_feature(
self,
image,
area_def,
feature_type,
db_name,
tag=None,
zero_pad=False,
resolution="c",
level=1,
x_offset=0,
y_offset=0,
db_root_path=None,
**kwargs,
):
"""Add a contour feature to image."""
shape_generator = self._iterate_db(db_name, tag, resolution, level, zero_pad, db_root_path=db_root_path)
return self.add_shapes(
image,
area_def,
shape_generator,
feature_type=feature_type,
x_offset=x_offset,
y_offset=y_offset,
**kwargs,
)
def _iterate_db(self, db_name, tag, resolution, level, zero_pad, db_root_path=None):
"""Iterate through datasets."""
if db_root_path is None:
db_root_path = self.db_root_path
if db_root_path is None:
raise ValueError("'db_root_path' must be specified to use this method")
levels = range(1, level + 1) if not isinstance(level, list) else level
format_string, format_params = self._get_db_shapefile_format_and_params(db_name, resolution, tag, zero_pad)
shapefile_root_dir = os.path.join(db_root_path, f"{db_name}_shp", resolution)
for i in levels:
level_format_params = format_params + (i,)
shapefilename = os.path.join(shapefile_root_dir, format_string % level_format_params)
try:
s = shapefile.Reader(shapefilename)
shapes = s.shapes()
except AttributeError:
raise ValueError("Could not find shapefile %s" % shapefilename)
yield from shapes
@staticmethod
def _get_db_shapefile_format_and_params(db_name, resolution, tag, zero_pad):
format_string = "%s_%s_"
format_params = (db_name, resolution)
if tag is not None:
format_string += "%s_"
format_params = (db_name, tag, resolution)
if zero_pad:
format_string += "L%02i.shp"
else:
format_string += "L%s.shp"
return format_string, format_params
def _finalize(self, draw):
"""Do any need finalization of the drawing."""
pass
def _config_to_dict(self, config_file):
"""Convert a config file to a dict."""
config = configparser.ConfigParser()
try:
with open(config_file, "r"):
logger.info("Overlays config file %s found", str(config_file))
config.read(config_file)
except IOError:
logger.error("Overlays config file %s does not exist!", str(config_file))
raise
except configparser.NoSectionError:
logger.error("Error in %s", str(config_file))
raise
SECTIONS = [
"cache",
"coasts",
"rivers",
"borders",
"shapefiles",
"grid",
"cities",
"points",
]
overlays = {}
for section in config.sections():
if section in SECTIONS:
overlays[section] = {}
for option in config.options(section):
val = config.get(section, option)
try:
overlays[section][option] = ast.literal_eval(val)
except ValueError:
overlays[section][option] = val
return overlays
def add_overlay_from_dict(self, overlays, area_def, cache_epoch=None, background=None):
"""Create and return a transparent image adding all the overlays contained in the `overlays` dict.
Optionally caches overlay results for faster rendering of images with
the same provided AreaDefinition and parameters. Cached results are
identified by hashing the AreaDefinition and the overlays dictionary.
.. warning::
Font objects are ignored in parameter hashing as they can't be easily hashed.
Therefore font changes will not trigger a new rendering for the cache.
:Parameters:
overlays : dict
overlays configuration
area_def : object
Area Definition of the creating image
cache_epoch: seconds since epoch
The latest time allowed for cache the cache file. If the cache
file is older than this (mtime), the cache should be
regenerated. Defaults to 0 meaning always reuse the cached
file if it exists. Requires "cache" to be configured in the
provided dictionary (see below).
background: pillow image instance
The image on which to write the overlays on. If it's None (default),
a new image is created, otherwise the provide background is
used and changed *in place*.
The keys in `overlays` that will be taken into account are:
cache, coasts, rivers, borders, shapefiles, grid, cities, points
For all of them except `cache`, the items are the same as the
corresponding functions in pycoast, so refer to the docstrings of
these functions (add_coastlines, add_rivers, add_borders,
add_shapefile_shapes, add_grid, add_cities, add_points).
For cache, two parameters are configurable:
- `file`: specify the directory and the prefix
of the file to save the caches decoration to (for example
/var/run/black_coasts_red_borders)
- `regenerate`: True or False (default) to force the overwriting
of an already cached file.
"""
overlay_helper = _OverlaysFromDict(self, overlays, area_def, cache_epoch, background)
return overlay_helper.apply_overlays()
def add_overlay_from_config(self, config_file, area_def, background=None):
"""Create and return a transparent image adding all the overlays contained in a configuration file.
:Parameters:
config_file : str
Configuration file name
area_def : object
Area Definition of the creating image
"""
overlays = self._config_to_dict(config_file)
return self.add_overlay_from_dict(overlays, area_def, os.path.getmtime(config_file), background)
def draw_star(self, draw, symbol, x, y, ptsize, **kwargs):
# 5 <= n <= 8, symbol = string in ['star8', 'star7', 'star6', 'star5']
n = int(symbol[4])
alpha2 = math.pi / n
# r1 = outer radius (defaults to 0.5 * ptsize), r1 > r2 = inner radius
r1 = 0.5 * ptsize
r2 = r1 / (math.cos(alpha2) + math.sin(alpha2) * math.tan(2.0 * alpha2))
xy = []
alpha = 0.0
# Walk from star top ray CW around the symbol
for i in range(2 * n):
if (i % 2) == 0:
xy.append(x + r1 * math.sin(alpha))
xy.append(y - r1 * math.cos(alpha))
else:
xy.append(x + r2 * math.sin(alpha))
xy.append(y - r2 * math.cos(alpha))
alpha += alpha2
self._draw_polygon(draw, xy, **kwargs)
def draw_hexagon(self, draw, x, y, ptsize, **kwargs):
xy = [
x + 0.25 * ptsize,
y - 0.4330127 * ptsize,
x + 0.50 * ptsize,
y,
x + 0.25 * ptsize,
y + 0.4330127 * ptsize,
x - 0.25 * ptsize,
y + 0.4330127 * ptsize,
x - 0.50 * ptsize,
y,
x - 0.25 * ptsize,
y - 0.4330127 * ptsize,
]
self._draw_polygon(draw, xy, **kwargs)
def draw_pentagon(self, draw, x, y, ptsize, **kwargs):
xy = [
x,
y - 0.5 * ptsize,
x + 0.4755283 * ptsize,
y - 0.1545085 * ptsize,
x + 0.2938926 * ptsize,
y + 0.4045085 * ptsize,
x - 0.2938926 * ptsize,
y + 0.4045085 * ptsize,
x - 0.4755283 * ptsize,
y - 0.1545085 * ptsize,
]
self._draw_polygon(draw, xy, **kwargs)
def draw_triangle(self, draw, x, y, ptsize, **kwargs):
xy = [
x,
y - 0.5 * ptsize,
x + 0.4330127 * ptsize,
y + 0.25 * ptsize,
x - 0.4330127 * ptsize,
y + 0.25 * ptsize,
]
self._draw_polygon(draw, xy, **kwargs)
def add_cities(
self,
image,
area_def,
cities_list,
font_file,
font_size=12,
symbol="circle",
ptsize=6,
outline="black",
fill="white",
db_root_path=None,
**kwargs,
):
"""Add cities (symbol and UTF-8 names as description) to a PIL image object.
:Parameters:
image : object
PIL image object
area_def : object
Area Definition of the provided image
cities_list : list of city names ['City1', 'City2', City3, ..., 'CityN']
| a list of UTF-8 or ASCII strings. If either of these strings is found
| in file db_root_path/CITIES/cities.red, longitude and latitude is read
| and the city is added like a point with its UTF-8 name as description
| e.g. cities_list = ['Zurich', 'Oslo'] will add cities 'Zürich', 'Oslo'.
| Check the README_PyCoast.txt in archive cities2022.zip for more details.
font_file : str
Path to font file
font_size : int
Size of font
symbol : string
type of symbol, one of the elelments from the list
['circle', 'hexagon', 'pentagon', 'square', 'triangle',
'star8', 'star7', 'star6', 'star5', 'asterisk']
ptsize : int
Size of the point.
outline : str or (R, G, B), optional
Line color of the symbol
fill : str or (R, G, B), optional
Filling color of the symbol
:Optional keyword arguments:
width : float
Line width of the symbol
outline_opacity : int, optional {0; 255}
Opacity of the line of the symbol.
fill_opacity : int, optional {0; 255}
Opacity of the filling of the symbol
box_outline : str or (R, G, B), optional
Line color of the textbox borders.
box_linewidth : float
Line width of the the borders of the textbox
box_fill : str or (R, G, B), optional
Filling color of the background of the textbox.
box_opacity : int, optional {0; 255}
Opacity of the background filling of the textbox.
"""
if db_root_path is None:
db_root_path = self.db_root_path
if db_root_path is None:
raise ValueError("'db_root_path' must be specified to use this method")
try:
from pyresample.geometry import AreaDefinition
except ImportError:
raise ImportError("Missing required 'pyresample' module, please install it.")
if not isinstance(area_def, AreaDefinition):
raise ValueError("Expected 'area_def' is an instance of AreaDefinition object")
draw = self._get_canvas(image)
# cities.red is a reduced version of the files avalable at http://download.geonames.org
# Fields: 0=name (UTF-8), 1=asciiname, 2=longitude [°E], 3=latitude [°N], 4=countrycode
cities_filename = os.path.join(db_root_path, os.path.join("CITIES", "cities.txt"))
cities_parser = GeoNamesCitiesParser(cities_filename)
for city_name, lon, lat in cities_parser.iter_cities_names_lon_lat(cities_list):
try:
x, y = area_def.get_array_indices_from_lonlat(lon, lat)
except ValueError:
logger.info(
"City %s is out of the area, it will not be added to the image.",
city_name + " " + str((lon, lat)),
)
continue
# add symbol
if ptsize != 0:
half_ptsize = int(round(ptsize / 2.0))
dot_box = [
x - half_ptsize,
y - half_ptsize,
x + half_ptsize,
y + half_ptsize,
]
width = kwargs.get("width", 1.0)
outline_opacity = kwargs.get("outline_opacity", 255)
fill_opacity = kwargs.get("fill_opacity", 255)
self._draw_point_element(
draw,
symbol,
dot_box,
x,
y,
width,
ptsize,
outline,
outline_opacity,
fill,
fill_opacity,
)
text_position = [x + ptsize, y]
else:
text_position = [x, y]
font = self._get_font(outline, font_file, font_size)
new_kwargs = kwargs.copy()
box_outline = new_kwargs.pop("box_outline", "white")
box_opacity = new_kwargs.pop("box_opacity", 0)
# add text_box
self._draw_text_box(
draw,
text_position,
city_name,
font,
outline,
box_outline,
box_opacity,
**new_kwargs,
)
logger.info("%s added", city_name + " " + str((lon, lat)))
self._finalize(draw)
def add_points(
self,
image,
area_def,
points_list,
font_file,
font_size=12,
symbol="circle",
ptsize=6,
outline="black",
fill="white",
coord_ref="lonlat",
**kwargs,
):
"""Add a symbol and/or text at the point(s) of interest to a PIL image object.
:Parameters:
image : object
PIL image object
area_def : object
Area Definition of the provided image
points_list : list [((x, y), desc)]
| a list of points defined with (x, y) in float and a desc in string
| [((x1, y1), desc1), ((x2, y2), desc2)]
| See coord_ref (below) for the meaning of x, y.
| x : float
| longitude or pixel x of a point
| y : float
| latitude or pixel y of a point
| desc : str
| description of a point
font_file : str
Path to font file
font_size : int
Size of font
symbol : string
type of symbol, one of the elelments from the list
['circle', 'hexagon', 'pentagon', 'square', 'triangle',
'star8', 'star7', 'star6', 'star5, 'asterisk']
ptsize : int
Size of the point (should be zero if symbol:None).
outline : str or (R, G, B), optional
Line color of the symbol
fill : str or (R, G, B), optional
Filling color of the symbol
:Optional keyword arguments:
coord_ref : string
The interpretation of x,y in points_list:
'lonlat' (the default: x is degrees E, y is degrees N),
or 'image' (x is pixels right, y is pixels down).
If image coordinates are negative they are interpreted
relative to the end of the dimension like standard Python
indexing.
width : float
Line width of the symbol
outline_opacity : int, optional {0; 255}
Opacity of the line of the symbol.
fill_opacity : int, optional {0; 255}
Opacity of the filling of the symbol
box_outline : str or (R, G, B), optional
Line color of the textbox borders.
box_linewidth : float
Line width of the the borders of the textbox
box_fill : str or (R, G, B), optional
Filling color of the background of the textbox.
box_opacity : int, optional {0; 255}
Opacity of the background filling of the textbox.
"""
coord_converter = _CoordConverter(coord_ref, area_def)
draw = self._get_canvas(image)
# Iterate through points list
for point in points_list:
(x, y), desc = point
try:
x, y = coord_converter(x, y)
except ValueError:
logger.info(f"Point ({x}, {y}) is out of the image area, it will not be added to the image.")
continue
if ptsize != 0:
half_ptsize = int(round(ptsize / 2.0))
dot_box = [
x - half_ptsize,
y - half_ptsize,
x + half_ptsize,
y + half_ptsize,
]
width = kwargs.get("width", 1.0)
outline_opacity = kwargs.get("outline_opacity", 255)
fill_opacity = kwargs.get("fill_opacity", 255)
self._draw_point_element(
draw,
symbol,
dot_box,
x,
y,
width,
ptsize,
outline,
outline_opacity,
fill,
fill_opacity,
)
elif desc is None:
logger.error("'ptsize' is 0 and 'desc' is None, nothing will be added to the image.")
if desc is not None:
text_position = [
x + ptsize,
y,
] # draw the text box next to the point
font = self._get_font(outline, font_file, font_size)
new_kwargs = kwargs.copy()
box_outline = new_kwargs.pop("box_outline", "white")
box_opacity = new_kwargs.pop("box_opacity", 0)
# add text_box
self._draw_text_box(
draw,
text_position,
desc,
font,
outline,
box_outline,
box_opacity,
**new_kwargs,
)
logger.debug("Point %s has been added to the image", str((x, y)))
self._finalize(draw)
def _draw_point_element(
self,
draw,
symbol,
dot_box,
x,
y,
width,
ptsize,
outline,
outline_opacity,
fill,
fill_opacity,
):
if symbol == "circle":
# a 'circle' or a 'dot' i.e. circle with fill
self._draw_ellipse(
draw,
dot_box,
outline=outline,
width=width,
outline_opacity=outline_opacity,
fill=fill,
fill_opacity=fill_opacity,
)
# All regular polygons are drawn horizontally based
elif symbol == "hexagon":
self.draw_hexagon(
draw,
x,
y,
ptsize,
outline=outline,
width=width,
outline_opacity=outline_opacity,
fill=fill,
fill_opacity=fill_opacity,
)
elif symbol == "pentagon":
self.draw_pentagon(
draw,
x,
y,
ptsize,
outline=outline,
width=width,
outline_opacity=outline_opacity,
fill=fill,
fill_opacity=fill_opacity,
)
elif symbol == "square":
self._draw_rectangle(
draw,
dot_box,
outline=outline,
width=width,
outline_opacity=outline_opacity,
fill=fill,
fill_opacity=fill_opacity,
)
elif symbol == "triangle":
self.draw_triangle(
draw,
x,
y,
ptsize,
outline=outline,
width=width,
outline_opacity=outline_opacity,
fill=fill,
fill_opacity=fill_opacity,
)
# All stars are drawn with one vertical ray on top
elif symbol in ["star8", "star7", "star6", "star5"]:
self.draw_star(
draw,
symbol,
x,
y,
ptsize,
outline=outline,
width=width,
outline_opacity=outline_opacity,
fill=fill,
fill_opacity=fill_opacity,
)
elif symbol == "asterisk": # an '*' sign
self._draw_asterisk(
draw,
ptsize,
(x, y),
outline=outline,
width=width,
outline_opacity=outline_opacity,
)
elif symbol:
raise ValueError("Unsupported symbol type: " + str(symbol))
def _get_lon_lat_bounding_box(area_extent, x_size, y_size, prj):
"""Get extreme lon and lat values."""
bbox_lons, bbox_lats = _get_bounding_box_lonlat_sides(area_extent, x_size, y_size, prj)
lons_s1, lons_s2, lons_s3, lons_s4 = bbox_lons
lats_s1, lats_s2, lats_s3, lats_s4 = bbox_lats