Skip to content

Commit 40b3aa6

Browse files
committed
Add support for S1 images stored as tif on onda + test
1 parent ece33e8 commit 40b3aa6

File tree

3 files changed

+80
-16
lines changed

3 files changed

+80
-16
lines changed

cropclassification/calc_timeseries.py

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ def calc_timeseries_task(
6666
with open(config_used_filepath, 'w') as config_used_file:
6767
conf.config.write(config_used_file)
6868

69+
# TODO: this shouldn't be hardcoded!
6970
input_parcel_filename = conf.calc_timeseries_params.getpath('input_parcel_filename')
7071
input_features_filename = Path(f"{input_parcel_filename.stem}_bufm5{input_parcel_filename.suffix}")
7172
input_preprocessed_dir = conf.dirs.getpath('input_preprocessed_dir')

cropclassification/preprocess/timeseries_calc_dias_onda_per_image.py

+27-16
Original file line numberDiff line numberDiff line change
@@ -454,13 +454,14 @@ def format_progress_message(
454454
message = f"{hours_to_go}:{min_to_go} left for {nb_todo-nb_done_total} todo at {nb_per_hour:0.0f}/h ({nb_per_hour_latestbatch:0.0f}/h last batch)"
455455
return message
456456

457-
def prepare_calc(features_filepath: Path,
458-
id_column: str,
459-
image_path: Path,
460-
output_filepath: Path,
461-
temp_dir: Path,
462-
log_dir: Path,
463-
nb_parallel_max: int = 16) -> dict:
457+
def prepare_calc(
458+
features_filepath: Path,
459+
id_column: str,
460+
image_path: Path,
461+
output_filepath: Path,
462+
temp_dir: Path,
463+
log_dir: Path,
464+
nb_parallel_max: int = 16) -> dict:
464465
"""
465466
Prepare the inputs for a calculation.
466467
@@ -473,18 +474,20 @@ def prepare_calc(features_filepath: Path,
473474
logger.propagate = False
474475
log_filepath = log_dir / f"{datetime.now():%Y-%m-%d_%H-%M-%S}_prepare_calc_{os.getpid()}.log"
475476
fh = logging.FileHandler(filename=log_filepath)
476-
fh.setLevel(logging.DEBUG)
477+
fh.setLevel(logging.INFO)
477478
fh.setFormatter(logging.Formatter('%(asctime)s|%(levelname)s|%(name)s|%(funcName)s|%(message)s'))
478479
logger.addHandler(fh)
479480

480481
ret_val = {}
481482

482483
# Prepare the image
484+
logger.info(f"Start prepare_image for {image_path} to {temp_dir}")
483485
image_prepared_path = prepare_image(image_path, temp_dir)
484486
logger.debug(f"Preparing ready, result: {image_prepared_path}")
485487
ret_val['image_prepared_path'] = image_prepared_path
486488

487489
# Get info about the image
490+
logger.info(f"Start get_image_info for {image_prepared_path}")
488491
image_info = get_image_info(image_prepared_path)
489492
logger.info(f"image_info: {image_info}")
490493

@@ -542,7 +545,7 @@ def prepare_calc(features_filepath: Path,
542545
try:
543546
features_gdf_batch.to_pickle(pickle_filepath)
544547
except Exception as ex:
545-
raise Exception(f"Exception writing pickle: {pickle_filepath}") from ex
548+
raise Exception(f"Exception writing pickle: {pickle_filepath}: {ex}") from ex
546549
batch_info["filepath"] = pickle_filepath
547550
batch_info["nb_items"] = len(features_gdf_batch.index)
548551
ret_val["feature_batches"].append(batch_info)
@@ -986,9 +989,18 @@ def get_image_info(image_path: Path) -> dict:
986989
image_datadir = image_path / image_datadirname
987990
band_filepaths = list(image_datadir.glob("*.img"))
988991

989-
# If no files were found, error!
992+
# If no files were found, check if the images are in .tif format!
993+
if len(band_filepaths) == 0:
994+
tif_path = image_path / "Gamma0_VH.tif"
995+
if tif_path.exists():
996+
band_filepaths.append(tif_path)
997+
tif_path = image_path / "Gamma0_VV.tif"
998+
if tif_path.exists():
999+
band_filepaths.append(tif_path)
1000+
1001+
# If no files were found, error
9901002
if len(band_filepaths) == 0:
991-
message = f"No image files found in {image_datadir}!"
1003+
message = f"No image files found in {image_datadir} or {image_path}!"
9921004
logger.error(message)
9931005
raise Exception(message)
9941006

@@ -1003,19 +1015,18 @@ def get_image_info(image_path: Path) -> dict:
10031015
image_info['image_crs'] = str(src.crs)
10041016
image_info['image_epsg'] = image_info['image_crs'].upper().replace('EPSG:', '')
10051017
#logger.debug(f"Image metadata read: {image_info}")
1006-
band_filename = os.path.basename(band_filepath)
1007-
if band_filename == "Gamma0_VH.img":
1018+
if band_filepath.stem == 'Gamma0_VH':
10081019
band = 'VH'
1009-
elif band_filename == "Gamma0_VV.img":
1020+
elif band_filepath.stem == 'Gamma0_VV':
10101021
band = 'VV'
10111022
else:
10121023
raise NotImplementedError(f"Filename not supported: {band_filepath}")
10131024

10141025
# Add specific info about the band
10151026
image_info['bands'][band] = {}
10161027
image_info['bands'][band]['filepath'] = band_filepath
1017-
image_info['bands'][band]['relative_filepath'] = os.path.join(image_datadirname, band_filename)
1018-
image_info['bands'][band]['filename'] = band_filename
1028+
image_info['bands'][band]['relative_filepath'] = str(band_filepath).replace(str(image_path) + os.pathsep, "")
1029+
image_info['bands'][band]['filename'] = band_filepath.name
10191030
image_info['bands'][band]['bandindex'] = 0
10201031

10211032
except Exception as ex:

tests/test_calc_timeseries.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import datetime
2+
from pathlib import Path
3+
import sys
4+
sys.path.insert(0, str(Path(__file__).resolve().parent / '..'))
5+
6+
from cropclassification.preprocess import timeseries_calc_dias_onda_per_image as calc_ts
7+
8+
def get_testdata_dir() -> Path:
9+
return Path(__file__).resolve().parent / 'data'
10+
11+
def test_calc_stats_per_image_s1_bs(tmpdir):
12+
13+
# Test raw version
14+
input_features_filepath = Path('/srv/data/playground/_inputdata_preprocessed/Prc_BEFL_2020_2020-07-01_bufm5.shp')
15+
input_image_filepaths = [Path('/mnt/NAS3/CARD/FLANDERS/S1A/L1TC/2020/07/11/S1A_IW_GRDH_1SDV_20200711T172447_20200711T172512_033410_03DF06_66B7_Orb_RBN_RTN_Cal_TC_20200714T100938.L1TC.CARD')]
16+
tmp_dir = Path(tmpdir) / 'raw'
17+
try:
18+
start_time = datetime.datetime.now()
19+
calc_ts.calc_stats_per_image(
20+
features_filepath=input_features_filepath,
21+
id_column='UID',
22+
image_paths=input_image_filepaths,
23+
bands=['VV', 'VH'],
24+
output_dir=tmp_dir,
25+
temp_dir=tmp_dir / 'tmp',
26+
log_dir=tmp_dir / 'log')
27+
print(f"calc_stats_per_image ready in {(datetime.datetime.now()-start_time).total_seconds():.2f}")
28+
except Exception as ex:
29+
raise Exception(f"Exception calculating for {input_features_filepath} on {input_image_filepaths}") from ex
30+
31+
# Test .tif version
32+
input_image_filepaths = [Path('/mnt/NAS5/SAMPLES_CARD/S1A_IW_GRDH_1SDV_20200711T172447_20200711T172512_033410_03DF06_66B7_Orb_RBN_RTN_Cal_TC_20200722T143946.L1TC.CARD')]
33+
tmp_dir = Path(tmpdir) / 'tif'
34+
try:
35+
start_time = datetime.datetime.now()
36+
calc_ts.calc_stats_per_image(
37+
features_filepath=input_features_filepath,
38+
id_column='UID',
39+
image_paths=input_image_filepaths,
40+
bands=['VV', 'VH'],
41+
output_dir=tmp_dir,
42+
temp_dir=tmp_dir / 'tmp',
43+
log_dir=tmp_dir / 'log')
44+
print(f"calc_stats_per_image ready in {(datetime.datetime.now()-start_time).total_seconds():.2f}")
45+
except Exception as ex:
46+
raise Exception(f"Exception calculating for {input_features_filepath} on {input_image_filepaths}") from ex
47+
48+
if __name__ == '__main__':
49+
import tempfile
50+
tmpdir = '/srv/data/playground/tmp'#tempfile.gettempdir()
51+
print(f"tmpdir used for test: {tmpdir}")
52+
test_calc_stats_per_image_s1_bs(tmpdir)

0 commit comments

Comments
 (0)