Copernicus-Bench / deprecated /cloud_s3olci /dataset_cloud_s3olci.py
wangyi111's picture
Rename deprecated/cloud_s3olci/old/dataset_cloud_s3olci.py to deprecated/cloud_s3olci/dataset_cloud_s3olci.py
16dff42 verified
import torch
from torch.utils.data import Dataset, DataLoader
import os
import rasterio
import numpy as np
from datetime import date
from pyproj import Transformer
S3_OLCI_SCALE = [0.0139465,0.0133873,0.0121481,0.0115198,0.0100953,0.0123538,0.00879161,0.00876539,
0.0095103,0.00773378,0.00675523,0.0071996,0.00749684,0.0086512,0.00526779,0.00530267,
0.00493004,0.00549962,0.00502847,0.00326378,0.00324118]
Cls_index_binary = {
'invalid': 0,
'clear': 1,
'cloud': 2,
}
Cls_index_multi = {
'invalid': 0,
'clear': 1,
'cloud-sure': 2,
'cloud-ambiguous': 3,
'cloud shadow': 4,
'snow and ice': 5,
}
class S3OLCI_CloudDataset(Dataset):
'''
1596/399 train/test images 256x256
21 bands
nodata: nan
'''
def __init__(self, root_dir, split='train', mode='multi', meta=True):
self.root_dir = root_dir
self.meta = meta
self.img_dir = os.path.join(root_dir, split, 's3_olci')
self.fpaths = os.listdir(self.img_dir)
self.fpaths = [f for f in self.fpaths if f.endswith('.tif')]
if mode == 'multi':
self.cloud_dir = os.path.join(root_dir, split, 'cloud_multi')
elif mode == 'binary':
self.cloud_dir = os.path.join(root_dir, split, 'cloud_binary')
if self.meta:
self.reference_date = date(1970, 1, 1)
def __len__(self):
return len(self.fpaths)
def __getitem__(self, idx):
fpath = self.fpaths[idx]
fpath_img = os.path.join(self.img_dir, fpath)
fpath_cloud = os.path.join(self.cloud_dir, fpath)
with rasterio.open(fpath_img) as src:
img = src.read()
# convert nan pixels to 0
img[np.isnan(img)] = 0
for b in range(21):
img[b] = img[b] * S3_OLCI_SCALE[b]
if self.meta:
cx,cy = src.xy(src.height // 2, src.width // 2)
crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326')
lon, lat = crs_transformer.transform(cx,cy)
img_fname = os.path.basename(fpath_img)
date_str = img_fname.split('____')[1][:8]
date_obj = date(int(date_str[:4]), int(date_str[4:6]), int(date_str[6:8]))
delta = (date_obj - self.reference_date).days
meta_info = np.array([lon, lat, delta, np.nan]).astype(np.float32)
else:
meta_info = np.array([np.nan,np.nan,np.nan,np.nan]).astype(np.float32)
img = torch.from_numpy(img).float()
with rasterio.open(fpath_cloud) as src:
cloud = src.read(1)
cloud = torch.from_numpy(cloud).long()
return img, cloud, meta_info
if __name__ == '__main__':
dataset = S3OLCI_CloudDataset(root_dir='./cloud_s3olci', split='train', mode='multi')
dataloader = DataLoader(dataset, batch_size=2, shuffle=False)
for img, cloud, meta in dataloader:
print(img.shape, cloud.shape, meta.shape)
break