alessandro trinca tornidor commited on
Commit
7d48fbe
1 Parent(s): d93d81f

[feat] add option to dump temp images during ML recognition operations

Browse files
README.md CHANGED
@@ -133,6 +133,7 @@ It's possible to use the project in a bare metal installation (not within a dock
133
  export PYTORCH_KERNEL_CACHE_PATH="$HOME/.cache/torch/kernels"
134
  export FASTAPI_STATIC="$HOME/workspace/samgis-lisa-on-cuda/static"
135
  export VIS_OUTPUT="$HOME/workspace/samgis-lisa-on-cuda/vis_output"
 
136
  ```
137
 
138
  - execute the script `baremetal_entrypoint.sh` instead than `docker_entrypoint.sh`.
 
133
  export PYTORCH_KERNEL_CACHE_PATH="$HOME/.cache/torch/kernels"
134
  export FASTAPI_STATIC="$HOME/workspace/samgis-lisa-on-cuda/static"
135
  export VIS_OUTPUT="$HOME/workspace/samgis-lisa-on-cuda/vis_output"
136
+ export WRITE_TMP_ON_DISK=${VIS_OUTPUT}
137
  ```
138
 
139
  - execute the script `baremetal_entrypoint.sh` instead than `docker_entrypoint.sh`.
samgis_lisa_on_cuda/io/raster_helpers.py CHANGED
@@ -1,8 +1,11 @@
1
  """helpers for computer vision duties"""
2
  import numpy as np
3
  from numpy import ndarray, bitwise_not
 
4
 
 
5
  from samgis_lisa_on_cuda import app_logger
 
6
  from samgis_lisa_on_cuda.utilities.type_hints import XYZTerrainProvidersNames
7
 
8
 
@@ -292,3 +295,37 @@ def check_empty_array(arr: ndarray, val: float) -> bool:
292
  check5 = np.array_equal(arr_check5_tmp, arr_check5)
293
  app_logger.debug(f"array checks:{check1}, {check2}, {check3}, {check4}, {check5}.")
294
  return check1 or check2 or check3 or check4 or check5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """helpers for computer vision duties"""
2
  import numpy as np
3
  from numpy import ndarray, bitwise_not
4
+ from rasterio import open as rasterio_open
5
 
6
+ from samgis_lisa_on_cuda import PROJECT_ROOT_FOLDER
7
  from samgis_lisa_on_cuda import app_logger
8
+ from samgis_lisa_on_cuda.utilities.constants import OUTPUT_CRS_STRING
9
  from samgis_lisa_on_cuda.utilities.type_hints import XYZTerrainProvidersNames
10
 
11
 
 
295
  check5 = np.array_equal(arr_check5_tmp, arr_check5)
296
  app_logger.debug(f"array checks:{check1}, {check2}, {check3}, {check4}, {check5}.")
297
  return check1 or check2 or check3 or check4 or check5
298
+
299
+
300
+ def write_raster_png(arr, transform, prefix: str, suffix: str, folder_output_path="/tmp"):
301
+ from pathlib import Path
302
+ from rasterio.plot import reshape_as_raster
303
+
304
+ output_filename = Path(folder_output_path) / f"{prefix}_{suffix}.png"
305
+
306
+ with rasterio_open(
307
+ output_filename, 'w', driver='PNG',
308
+ height=arr.shape[0],
309
+ width=arr.shape[1],
310
+ count=3,
311
+ dtype=str(arr.dtype),
312
+ crs=OUTPUT_CRS_STRING,
313
+ transform=transform) as dst:
314
+ dst.write(reshape_as_raster(arr))
315
+ app_logger.info(f"written:{output_filename} as PNG, use {OUTPUT_CRS_STRING} as CRS.")
316
+
317
+
318
+ def write_raster_tiff(arr, transform, prefix: str, suffix: str, folder_output_path="/tmp"):
319
+ from pathlib import Path
320
+ output_filename = Path(folder_output_path) / f"{prefix}_{suffix}.tiff"
321
+
322
+ with rasterio_open(
323
+ output_filename, 'w', driver='GTiff',
324
+ height=arr.shape[0],
325
+ width=arr.shape[1],
326
+ count=1,
327
+ dtype=str(arr.dtype),
328
+ crs=OUTPUT_CRS_STRING,
329
+ transform=transform) as dst:
330
+ dst.write(arr, 1)
331
+ app_logger.info(f"written:{output_filename} as TIFF, use {OUTPUT_CRS_STRING} as CRS.")
samgis_lisa_on_cuda/prediction_api/lisa.py CHANGED
@@ -1,10 +1,15 @@
 
 
 
 
1
  from samgis_lisa_on_cuda import app_logger
2
  from samgis_lisa_on_cuda.io.geo_helpers import get_vectorized_raster_as_geojson
 
3
  from samgis_lisa_on_cuda.io.tms2geotiff import download_extent
4
  from samgis_lisa_on_cuda.prediction_api.global_models import models_dict
5
  from samgis_lisa_on_cuda.utilities.constants import DEFAULT_URL_TILES
6
- from samgis_core.utilities.type_hints import llist_float, list_dict, dict_str_int
7
- from lisa_on_cuda.utils import app_helpers
8
 
9
 
10
  def lisa_predict(
@@ -32,6 +37,8 @@ def lisa_predict(
32
  Returns:
33
  Affine transform
34
  """
 
 
35
  app_logger.info("start lisa inference...")
36
  if models_dict[inference_function_name_key]["inference"] is None:
37
  app_logger.info(f"missing inference function {inference_function_name_key}, instantiating it now!")
@@ -44,9 +51,19 @@ def lisa_predict(
44
  pt0, pt1 = bbox
45
  app_logger.info(f"tile_source: {source}: downloading geo-referenced raster with bbox {bbox}, zoom {zoom}.")
46
  img, transform = download_extent(w=pt1[1], s=pt1[0], e=pt0[1], n=pt0[0], zoom=zoom, source=source)
47
-
48
  app_logger.info(
49
  f"img type {type(img)} with shape/size:{img.size}, transform type: {type(transform)}, transform:{transform}.")
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  _, mask, output_string = inference_fn(prompt, img)
52
  # app_logger.info(f"created {n_predictions} masks, preparing conversion to geojson...")
 
1
+ from datetime import datetime
2
+
3
+ from lisa_on_cuda.utils import app_helpers
4
+ from samgis_core.utilities.type_hints import llist_float, dict_str_int
5
  from samgis_lisa_on_cuda import app_logger
6
  from samgis_lisa_on_cuda.io.geo_helpers import get_vectorized_raster_as_geojson
7
+ from samgis_lisa_on_cuda.io.raster_helpers import write_raster_png, write_raster_tiff
8
  from samgis_lisa_on_cuda.io.tms2geotiff import download_extent
9
  from samgis_lisa_on_cuda.prediction_api.global_models import models_dict
10
  from samgis_lisa_on_cuda.utilities.constants import DEFAULT_URL_TILES
11
+
12
+ msg_write_tmp_on_disk = "found option to write images and geojson output..."
13
 
14
 
15
  def lisa_predict(
 
37
  Returns:
38
  Affine transform
39
  """
40
+ from os import getenv
41
+
42
  app_logger.info("start lisa inference...")
43
  if models_dict[inference_function_name_key]["inference"] is None:
44
  app_logger.info(f"missing inference function {inference_function_name_key}, instantiating it now!")
 
51
  pt0, pt1 = bbox
52
  app_logger.info(f"tile_source: {source}: downloading geo-referenced raster with bbox {bbox}, zoom {zoom}.")
53
  img, transform = download_extent(w=pt1[1], s=pt1[0], e=pt0[1], n=pt0[0], zoom=zoom, source=source)
 
54
  app_logger.info(
55
  f"img type {type(img)} with shape/size:{img.size}, transform type: {type(transform)}, transform:{transform}.")
56
+ folder_write_tmp_on_disk = getenv("WRITE_TMP_ON_DISK", "")
57
+ if bool(folder_write_tmp_on_disk):
58
+ now = datetime.now().strftime('%Y%m%d_%H%M%S')
59
+ prefix = f"w{pt1[1]},s{pt1[0]},e{pt0[1]},n{pt0[0]}_"
60
+ app_logger.info(msg_write_tmp_on_disk + f"with coords {prefix}, shape:{img.shape}, {len(img.shape)}.")
61
+ if img.shape and len(img.shape) == 2:
62
+ write_raster_tiff(img, transform, f"{prefix}_{now}_", f"raw_tiff", folder_write_tmp_on_disk)
63
+ if img.shape and len(img.shape) == 3 and img.shape[2] == 3:
64
+ write_raster_png(img, transform, f"{prefix}_{now}_", f"raw_img", folder_write_tmp_on_disk)
65
+ else:
66
+ app_logger.info("keep all temp data in memory...")
67
 
68
  _, mask, output_string = inference_fn(prompt, img)
69
  # app_logger.info(f"created {n_predictions} masks, preparing conversion to geojson...")