samgis_core 3.0.5__py3-none-any.whl → 3.0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,7 +70,8 @@ def get_inference_embedding(
70
70
 
71
71
 
72
72
  def get_raster_inference_using_existing_embedding(
73
- embedding: dict, prompt: ListDict, models_instance: SegmentAnythingONNX2) -> TupleNdarrayInt:
73
+ embedding: dict, prompt: ListDict, models_instance: SegmentAnythingONNX2, folder_write_tmp_on_disk: str = None,
74
+ key: str = None) -> TupleNdarrayInt:
74
75
  """
75
76
  Get inference output for a given image using a SegmentAnythingONNX model, using an existing embedding instead of a
76
77
  new ndarray or PIL image
@@ -79,6 +80,8 @@ def get_raster_inference_using_existing_embedding(
79
80
  embedding: dict
80
81
  prompt: list of prompt dict
81
82
  models_instance: SegmentAnythingONNX instance model
83
+ folder_write_tmp_on_disk: output folder where to write debug images
84
+ key: embedding key
82
85
 
83
86
  Returns:
84
87
  raster prediction mask, prediction number
@@ -90,16 +93,27 @@ def get_raster_inference_using_existing_embedding(
90
93
  app_logger.info(f"Created {len_inference_out} prediction_masks,"
91
94
  f"shape:{inference_out.shape}, dtype:{inference_out.dtype}.")
92
95
  mask = zeros((inference_out.shape[2], inference_out.shape[3]), dtype=uint8)
96
+ write_tmp_img = bool(folder_write_tmp_on_disk)
93
97
  for n, m in enumerate(inference_out[0, :, :, :]):
94
98
  app_logger.debug(f"{n}th of prediction_masks shape {inference_out.shape}"
95
99
  f" => mask shape:{mask.shape}, {mask.dtype}.")
96
100
  mask[m > 0.0] = 255
101
+ if write_tmp_img:
102
+ from pathlib import Path
103
+ from datetime import datetime
104
+ from samgis_core.utilities.utilities import convert_ndarray_to_pil, normalize_array
105
+ m_normalized = normalize_array(m, type_normalization="float")
106
+ m_out = convert_ndarray_to_pil(m_normalized)
107
+ now = datetime.now().isoformat()
108
+ if len(m.shape) == 2:
109
+ m_out = m_out.convert("L")
110
+ m_out.save(Path(folder_write_tmp_on_disk) / f"mask_{key}_{now}_n{n}.png")
97
111
  return mask, len_inference_out
98
112
 
99
113
 
100
114
  def get_raster_inference_with_embedding_from_dict(
101
115
  img: PIL_Image | ndarray, prompt: ListDict, models_instance: SegmentAnythingONNX2, model_name: str,
102
- embedding_key: str, embedding_dict: dict) -> TupleNdarrayInt:
116
+ embedding_key: str, embedding_dict: dict, folder_write_tmp_on_disk: str = None) -> TupleNdarrayInt:
103
117
  """
104
118
  Get inference output using a SegmentAnythingONNX model, but get the image embedding from the given embedding dict
105
119
  instead of creating a new embedding. This function needs the img argument to update the embedding dict if necessary
@@ -111,6 +125,7 @@ def get_raster_inference_with_embedding_from_dict(
111
125
  model_name: model name string
112
126
  embedding_key: embedding id
113
127
  embedding_dict: embedding images dict
128
+ folder_write_tmp_on_disk: output folder where to write debug images
114
129
 
115
130
  Returns:
116
131
  raster prediction mask, prediction number
@@ -122,4 +137,5 @@ def get_raster_inference_with_embedding_from_dict(
122
137
  embedding = embedding_dict[embedding_key]
123
138
  n_keys = len(embedding_dict)
124
139
  app_logger.info(f"embedding created ({n_keys} keys in embedding dict), running predict_masks with prompt {prompt}.")
125
- return get_raster_inference_using_existing_embedding(embedding, prompt, models_instance)
140
+ return get_raster_inference_using_existing_embedding(
141
+ embedding, prompt, models_instance, folder_write_tmp_on_disk=folder_write_tmp_on_disk, key=embedding_key)
@@ -1,12 +1,15 @@
1
+ import structlog.stdlib
1
2
  from numpy import ndarray
2
3
  from matplotlib import pyplot as plt
3
4
 
4
- from samgis_core.utilities.type_hints import ListStr, TupleInt
5
-
5
+ from samgis_core.utilities.type_hints import ListStr, MatplotlibBackend
6
6
 
7
7
  FigAxes = tuple[plt.Figure, plt.Axes]
8
8
 
9
9
 
10
+ logger = structlog.stdlib.get_logger(__file__)
11
+
12
+
10
13
  def helper_imshow_output_expected(
11
14
  img_list: list[ndarray], titles_list: ListStr, cmap: str = "gist_rainbow", plot_size: int = 5,
12
15
  show=False, debug: bool = False, close_after: float = 0.0) -> FigAxes:
@@ -47,10 +50,9 @@ def helper_imshow_output_expected(
47
50
  return fig, ax
48
51
 
49
52
 
50
-
51
53
  def imshow_raster(
52
54
  raster, title, cmap: str = "gist_rainbow", interpolation: str = None, alpha=None, transform=None, plot_size=5,
53
- show=False, debug: bool = False, close_after: float = 0.0) -> FigAxes:
55
+ show=False, debug: bool = False, close_after: float = 0.0, backend: MatplotlibBackend = None) -> FigAxes:
54
56
  """
55
57
  Displays raster images lists/arrays with titles, legend, alpha transparency, figure sizes
56
58
  and geographic transformations, if not none (leveraging rasterio.plot)
@@ -66,6 +68,7 @@ def imshow_raster(
66
68
  show: fire plt.show() action if needed
67
69
  debug: workaround useful in an interactive context, like Pycharm debugger
68
70
  close_after: close after give seconds (useful in tests, contrasted to 'debug' option)
71
+ backend: matplotlib backend string
69
72
 
70
73
  Returns:
71
74
  tuple of matplotlib Figure, Axes
@@ -73,6 +76,11 @@ def imshow_raster(
73
76
  """
74
77
  from rasterio import plot
75
78
 
79
+ if not backend:
80
+ backend = plt.get_backend()
81
+ plt.rcParams["backend"] = backend
82
+ logger.info(f"use {backend} as matplotlib backend...")
83
+
76
84
  fig, ax = plt.subplots(figsize=(plot_size, plot_size))
77
85
  raster_ax = raster[0] if transform is not None else raster
78
86
  image_hidden = ax.imshow(raster_ax, cmap=cmap, interpolation=interpolation, alpha=alpha)
@@ -67,5 +67,32 @@ class EmbeddingPILImage(TypedDict):
67
67
  resized_size: TupleInt2
68
68
 
69
69
 
70
+ class MatplotlibBackend(StrEnum):
71
+ gtk3agg = "gtk3agg"
72
+ gtk3cairo = "gtk3cairo"
73
+ gtk4agg = "gtk4agg"
74
+ gtk4cairo = "gtk4cairo"
75
+ macosx = "macosx"
76
+ nbagg = "nbagg"
77
+ notebook = "notebook"
78
+ qtagg = "qtagg"
79
+ qtcairo = "qtcairo"
80
+ qt5agg = "qt5agg"
81
+ qt5cairo = "qt5cairo"
82
+ tkagg = "tkagg"
83
+ tkcairo = "tkcairo"
84
+ webagg = "webagg"
85
+ wx = "wx"
86
+ wxagg = "wxagg"
87
+ wxcairo = "wxcairo"
88
+ agg = "agg"
89
+ cairo = "cairo"
90
+ pdf = "pdf"
91
+ pgf = "pgf"
92
+ ps = "ps"
93
+ svg = "svg"
94
+ template = "template"
95
+
96
+
70
97
  EmbeddingDict = dict[str, EmbeddingImage]
71
98
  EmbeddingPILDict = dict[str, EmbeddingPILImage]
@@ -1,6 +1,7 @@
1
1
  """Various utilities (logger, time benchmark, args dump, numerical and stats info)"""
2
2
  from copy import deepcopy
3
3
 
4
+ import numpy as np
4
5
  from numpy import ndarray, float32
5
6
 
6
7
  from samgis_core import app_logger
@@ -136,3 +137,12 @@ def apply_coords(coords: ndarray, embedding: EmbeddingPILImage):
136
137
  coords[..., 1] = coords[..., 1] * (resized_height / orig_height)
137
138
 
138
139
  return coords.astype(float32)
140
+
141
+
142
+ def normalize_array(arr: ndarray, new_h: int | float = 255., type_normalization: str = "int") -> ndarray:
143
+ arr = arr.astype(float)
144
+ arr_max = np.nanmax(arr)
145
+ arr_min = np.nanmin(arr)
146
+ scaled_arr = (arr - arr_min) / (arr_max - arr_min)
147
+ multiplied_arr = scaled_arr * new_h
148
+ return multiplied_arr.astype(int) if type_normalization == "int" else multiplied_arr
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: samgis_core
3
- Version: 3.0.5
3
+ Version: 3.0.6
4
4
  Summary: SamGIS CORE
5
5
  License: MIT
6
6
  Author: alessandro trinca tornidor
@@ -2,16 +2,16 @@ samgis_core/__init__.py,sha256=4e1lkiD-cLi_YLjJ4DUpu8LrUgjCHfhO_wnOGyEv_m0,673
2
2
  samgis_core/__version__.py,sha256=x-8LeQkljky-ao1MyT98tSQE1xNvJp3LelqsAdCb9Og,94
3
3
  samgis_core/prediction_api/__init__.py,sha256=_jUZhspS26ygiSzBJywfZ4fQf9X7oC8w6oxvhd9S2hQ,57
4
4
  samgis_core/prediction_api/sam_onnx2.py,sha256=8mORGMl_pE6YjOKGz6L7Lsav_xGteOUma3GzQXIbTFU,8260
5
- samgis_core/prediction_api/sam_onnx_inference.py,sha256=EkdPr1oBm93Ny4skJUj9cKJGjvoKUCrKVDMc6Wu3S_I,5543
5
+ samgis_core/prediction_api/sam_onnx_inference.py,sha256=WFRc8TNMOix4g0IAteNbDAs040lWXC3YEZYHcnCHRcE,6493
6
6
  samgis_core/utilities/__init__.py,sha256=nL9pzdB4SdEF8m5gCbtlVCtdGLg9JjPm-FNxKBsIBZA,32
7
7
  samgis_core/utilities/constants.py,sha256=0xBdfGYwCg4O0OXFtTcMVNj-kryjbajcxOZhMVkVP7U,227
8
8
  samgis_core/utilities/create_folders_if_not_exists.py,sha256=Ee_4l83suZvY5r24D26SNKGJVH3KAHregsiWs-0W-gQ,3202
9
- samgis_core/utilities/plot_images.py,sha256=O2QhPSWrWBgli-u1rKx_pJxH--V35bhT6M7z7qrihA8,3153
9
+ samgis_core/utilities/plot_images.py,sha256=1pwTJC2_ju-QhJXDonvEw6FMK_9i1kQhLnC4tjn2EH0,3469
10
10
  samgis_core/utilities/serialize.py,sha256=aIjhEoibBpV_gpgOg6LiVxZCWjOkYxlzcboDZLQctJE,2689
11
11
  samgis_core/utilities/session_logger.py,sha256=mlzLaeSC2b_MF3wLywyXYQsSPIvEd3OnhlD7_4VhMzo,5704
12
- samgis_core/utilities/type_hints.py,sha256=YhTSsD7ICVZtLRoq-P6O5AP9BEGg5hSHJaboS1qbpuw,1101
13
- samgis_core/utilities/utilities.py,sha256=RXobQKpzqi8uGzbCSIi7jDlYLnmAoHBNnrlQSGDRGV8,3617
14
- samgis_core-3.0.5.dist-info/LICENSE,sha256=cmg7mi2IynvK5xYN_TJBikA008n6IJNjQIig1c3ge9Q,1083
15
- samgis_core-3.0.5.dist-info/METADATA,sha256=b2ySELtINqH5EdulwKdAk0JInz56ahI_7g-bS2dTZm8,1109
16
- samgis_core-3.0.5.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
17
- samgis_core-3.0.5.dist-info/RECORD,,
12
+ samgis_core/utilities/type_hints.py,sha256=anbm8pHFWr_C1upCmncYOK-q9Iq82fO9_yftTqXeizc,1649
13
+ samgis_core/utilities/utilities.py,sha256=4EBnsTBontnmaZRVtI4VAbvISdmYyg2yEnn8Sb28dUc,4014
14
+ samgis_core-3.0.6.dist-info/LICENSE,sha256=cmg7mi2IynvK5xYN_TJBikA008n6IJNjQIig1c3ge9Q,1083
15
+ samgis_core-3.0.6.dist-info/METADATA,sha256=cF143cyh8z5hhFc3_ZXad95rLjfin9prTKMBBteZLfo,1109
16
+ samgis_core-3.0.6.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
17
+ samgis_core-3.0.6.dist-info/RECORD,,