Download dataloader.py from embed2scale/S1-single-ship-downstream: direct link, hf CLI and curl.
- Browser
- Download file 9.73 kB
-
https://huggingface.co/datasets/embed2scale/S1-single-ship-downstream/resolve/main/dataloader.py
- Command line
-
hf download hf://datasets/embed2scale/S1-single-ship-downstream/dataloader.py
-
curl -L -o dataloader.py https://huggingface.co/datasets/embed2scale/S1-single-ship-downstream/resolve/main/dataloader.py
9.73 kB
| import glob | |
| import numpy as np | |
| import os | |
| import pandas as pd | |
| from pyproj import Transformer | |
| import rasterio | |
| from rasterio.transform import rowcol | |
| import torch | |
| from torch.utils.data import Dataset | |
| from shapely.geometry import Polygon | |
| from shapely import wkt | |
| import xarray as xr | |
| S2L1C_MEAN = [2607.345, 2393.068, 2320.225, 2373.963, 2562.536, 3110.071, 3392.832, 3321.154, 3583.77, 1838.712, 1021.753, 3205.112, 2545.798] | |
| S2L1C_STD = [786.523, 849.702, 875.318, 1143.578, 1126.248, 1161.98, 1273.505, 1246.79, 1342.755, 576.795, 45.626, 1340.347, 1145.036] | |
| S2L2A_MEAN = [1793.243, 1924.863, 2184.553, 2340.936, 2671.402, 3240.082, 3468.412, 3563.244, 3627.704, 3711.071, 3416.714, 2849.625] | |
| S2L2A_STD = [1160.144, 1201.092, 1219.943, 1397.225, 1400.035, 1373.136, 1429.17, 1485.025, 1447.836, 1652.703, 1471.002, 1365.307] | |
| S1GRD_MEAN = [-12.577, -20.265] | |
| S1GRD_STD = [5.179, 5.872] | |
| class ShipDataloader(Dataset): | |
| def __init__(self, | |
| data_path: str, | |
| metadata_path: str = None, | |
| transform = None, | |
| concat: bool = True, | |
| output_file_name: bool = False, | |
| output_metadata: bool = False, | |
| load_s2: bool = False, | |
| shift_s2_channels: bool = True, | |
| ): | |
| """Dataset class for the SSL4EO downstream dataset. | |
| Parameters | |
| ---------- | |
| data_path : str, path-like | |
| Path to challenge data. Assumes that under data_path there is at least one folder with the name `s1`, optionally also `s2l1c` and `s2l2a` folders. | |
| transform : torch.Compose | |
| Transformations to apply to the data | |
| concat : bool | |
| Toggle concatenating the modalities along the channel dimension. Default is True. | |
| output_file_name : bool | |
| Toggle output of the file name. | |
| output_metadata : bool | |
| Toggle outputting metadata with bounding box, transform, ship location in pixel. | |
| load_s2 : bool | |
| Toggle loading of optional Sentinel-2 data. | |
| shift_s2_channels : bool | |
| Toggle shifting the S2 channels by 1000 to align to SSL4EO-S12 v1.1. Default is True, where the challenge data S2 channels are shifted upward 1000 to have the same range as SSL4EO-S12 v1.1. The background is that ESA decided. This argument is only used if load_s2=True. | |
| from 2022-01-25 to shift the DN values of S2 by 1000 upward. SSL4EO-S12 v1.1 includes this shift, while the provided S2 data does not. | |
| Returns | |
| ------- | |
| dict | |
| By default only includes field 'data', with either a torch.Tensor (if concat=True), or a dict with keys the modalities and torch.Tensors as values (if concat=False). | |
| If output_file_name=True, dictionary includes field 'file_name' with a list of file names corrsponding to the loaded files. | |
| If output_metadata=True, dictionary includes field 'metadata' with a disctionary contatining metadata for the samples. | |
| """ | |
| if output_metadata: | |
| assert metadata_path is not None, f"metadata_path must be provided to output metadata." | |
| self.data_path = data_path | |
| self.metadata_path = metadata_path | |
| self.transform = transform | |
| self.dataset_name = 'bands' | |
| self.concat = concat | |
| self.output_file_name = output_file_name | |
| self.output_metadata = output_metadata | |
| self.load_s2 = load_s2 | |
| self.shift_s2_channels = shift_s2_channels | |
| # Get S1 samples | |
| self.samples = glob.glob(os.path.join(data_path, 's1', '*.tif')) | |
| self.file_names = [os.path.basename(p).replace('.tif', '') for p in self.samples] | |
| # Get optional metadata | |
| if metadata_path is not None: | |
| df = pd.read_csv(metadata_path) | |
| # Filter samples and metadata to contain the same samples | |
| df = df[df['file_name'].isin(self.file_names)] | |
| meta_file_names = df['file_name'].unique().tolist() | |
| self.samples = [s for s in self.samples if os.path.basename(s).replace('.tif', '') in meta_file_names] | |
| # Update file name list | |
| self.file_names = [os.path.basename(p).replace('.tif', '') for p in self.samples] | |
| # Store metadata | |
| self.metadata = df.set_index('file_name').to_dict(orient='index') | |
| def __len__(self): | |
| return len(self.samples) | |
| def __getitem__(self, idx): | |
| sample_path = self.samples[idx] | |
| file_name = os.path.splitext(os.path.basename(sample_path))[0].replace('.tif', '') | |
| data = {} | |
| # Load S1 data | |
| with rasterio.open(sample_path) as f: | |
| data['s1'] = f.read()[None, None, ...] | |
| raster_crs = f.crs | |
| raster_transform = f.transform | |
| # Optionally load s2 data | |
| if self.load_s2: | |
| # Load S2 data | |
| s2_sample_paths = {m: os.path.join(self.data_path, m, file_name + '.zarr.zip') for m in ['s2l1c', 's2l2a']} | |
| for modality, s2_sample_path in s2_sample_paths.items(): | |
| data[modality] = xr.open_zarr(s2_sample_path)[self.dataset_name].values | |
| # Copy S1 data as many times as the season dimension of S2, dimension -4 | |
| data['s1'] = np.repeat(data['s1'], data['s2l1c'].shape[-4], axis=-4) | |
| # Add shift to align S2 channels with SSL4EO-S12 v1.1 | |
| if self.shift_s2_channels and (modality in ['s2l1c', 's2l2a']): | |
| data[modality] += 1000 | |
| n_bands_per_modality = {m: d.shape[-3] for m, d in data.items()} | |
| start_ind_of_modality = {m: n for m, n in zip(data.keys(), [0] + np.cumsum(list(n_bands_per_modality.values())).tolist())} | |
| modalities = list(data.keys()) | |
| # Concatenate data | |
| data = np.concatenate(list(data.values()), axis=-3) | |
| data = data.astype(np.float32) | |
| data = torch.from_numpy(data) | |
| # Transform | |
| if self.transform is not None: | |
| data = self.transform(data) | |
| if not self.concat: | |
| data = {m: data[..., start_ind_of_modality[m]: start_ind_of_modality[m] + n_bands_per_modality[m], :, :] for m in modalities} | |
| output = {} | |
| output['data'] = data | |
| if self.output_file_name: | |
| output['file_name'] = file_name | |
| if self.output_metadata: | |
| # Get metadata | |
| metadata = self.metadata[file_name] | |
| # Convert latitude, longitude WKT polygon bounding box | |
| geometry = metadata['geometry'] | |
| pixel_coords = convert_wgs84_to_pixel_polygon(geometry, raster_crs, raster_transform) | |
| # Add metadata | |
| metadata['geometry_pixel'] = pixel_coords_to_wkt(pixel_coords) | |
| metadata['crs'] = raster_crs | |
| metadata['transform'] = raster_transform | |
| output['metadata'] = metadata | |
| return output | |
| def collate_fn(batch): | |
| if isinstance(batch, dict) or isinstance(batch, torch.Tensor): | |
| # Single sample | |
| return batch | |
| elif isinstance(batch, list) and isinstance(batch[0], torch.Tensor): | |
| # Concatenate tensors along sample dim | |
| return torch.concat(batch, dim=0) | |
| elif isinstance(batch, list) and isinstance(batch[0], dict): | |
| data = [sample['data'] for sample in batch] | |
| includes_file_names = False | |
| if 'file_name' in batch[0]: | |
| file_names = [sample['file_name'] for sample in batch] | |
| includes_file_names = True | |
| includes_metadata = False | |
| if 'metadata' in batch[0]: | |
| metadata = [sample['metadata'] for sample in batch] | |
| includes_metadata = True | |
| if isinstance(data[0], torch.Tensor): | |
| data = torch.concat(data, dim=0) | |
| elif isinstance(data[0], dict): | |
| data = { | |
| m: torch.concat([b[m] for b in data], dim=0) | |
| for m in data[0].keys() | |
| } | |
| output = {'data': data} | |
| if includes_file_names: | |
| output['file_name'] = [fn for fn in file_names] | |
| if includes_metadata: | |
| output['metadata'] = [m for m in metadata] | |
| return output | |
| def transform_coords(coord_seq, transformer): | |
| x, y = transformer.transform(coord_seq[0], coord_seq[1]) | |
| return (x, y) | |
| def convert_wgs84_to_pixel_polygon(wkt_str, raster_crs, raster_transform): | |
| poly_wgs84 = wkt.loads(wkt_str) | |
| # Set up a transformer: WGS84 (EPSG:4326) → raster CRS | |
| transformer = Transformer.from_crs( | |
| "EPSG:4326", | |
| raster_crs, | |
| always_xy=True # ensure order (lon, lat) → (x, y) | |
| ) | |
| exterior = [transform_coords(pt, transformer) for pt in poly_wgs84.exterior.coords] | |
| # Transform interior rings (holes) if any | |
| interiors = [ | |
| [_transform_coords(pt, transformer) for pt in ring.coords] | |
| for ring in poly_wgs84.interiors | |
| ] | |
| # Re‑build the polygon in raster CRS | |
| geom_raster_crs = Polygon(exterior, interiors) | |
| # To get the pixel coordinates for the whole polygon, transform each vertex. | |
| pixel_coords = [ | |
| rowcol(raster_transform, *pt) # returns (row, col) | |
| for pt in geom_raster_crs.exterior.coords | |
| ] | |
| return pixel_coords | |
| def pixel_coords_to_wkt(pixel_coords): | |
| # Flip each pair to (col, row) so that x=col, y=row | |
| pts = [(c, r) for r, c in pixel_coords] | |
| # Close the ring if it isn't already | |
| if pts[0] != pts[-1]: | |
| pts.append(pts[0]) | |
| # Build the coordinate string | |
| coord_str = ", ".join(f"{x} {y}" for x, y in pts) | |
| # Return the WKT polygon string | |
| return f"POLYGON(({coord_str}))" | |