├── tools ├── __init__.py ├── tsne_feature_map │ ├── t_sne_plot.py │ └── space_tsne.py ├── cfg.py ├── geoseg_loveda_mask_convert.py ├── loveda_mask_convert.py ├── metric.py ├── uavid_patch_split.py └── vaihingen_patch_split.py ├── images ├── .gitkeep ├── logo.ico ├── logo.png ├── framework.png ├── iccv25-d2ls-poster.pdf └── iccv25-d2ls-poster.png ├── network ├── __init__.py ├── datasets │ ├── __init__.py │ ├── potsdam_dataset.py │ ├── cloud_dataset.py │ ├── grass_dataset.py │ ├── transform.py │ └── vaihingen_dataset.py ├── models │ └── __init__.py └── losses │ ├── __init__.py │ ├── wing_loss.py │ ├── soft_ce.py │ ├── shape.py │ ├── focal_cosine.py │ ├── soft_bce.py │ ├── custom.py │ ├── balanced_bce.py │ ├── joint_loss.py │ ├── focal.py │ ├── jaccard.py │ ├── soft_f1.py │ ├── useful_loss.py │ ├── cel1.py │ ├── lovasz.py │ ├── functional.py │ └── bitempered_loss.py ├── requirements.txt ├── config ├── grass │ └── d2ls.py ├── uavid │ └── d2ls.py ├── potsdam │ └── d2ls.py ├── vaihingen │ └── d2ls.py ├── cloud │ └── d2ls.py └── loveda │ └── d2ls.py ├── .gitignore ├── test_vaihingen.py ├── test_potsdam.py ├── test_loveda.py ├── train.py ├── test_uavid.py └── README.md /tools/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/.gitkeep: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /network/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /network/datasets/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /network/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/logo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XavierJiezou/D2LS/HEAD/images/logo.ico -------------------------------------------------------------------------------- /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XavierJiezou/D2LS/HEAD/images/logo.png -------------------------------------------------------------------------------- /images/framework.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XavierJiezou/D2LS/HEAD/images/framework.png -------------------------------------------------------------------------------- /images/iccv25-d2ls-poster.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XavierJiezou/D2LS/HEAD/images/iccv25-d2ls-poster.pdf -------------------------------------------------------------------------------- /images/iccv25-d2ls-poster.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XavierJiezou/D2LS/HEAD/images/iccv25-d2ls-poster.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | timm 2 | catalyst==20.09 3 | lightning 4 | albumentations 5 | ttach 6 | numpy 7 | tqdm 8 | opencv-python 9 | scipy 10 | matplotlib 11 | einops 12 | addict -------------------------------------------------------------------------------- /network/losses/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .balanced_bce import * 4 | from .bitempered_loss import * 5 | from .dice import * 6 | from .focal import * 7 | from .focal_cosine import * 8 | from .functional import * 9 | from .jaccard import * 10 | from .joint_loss import * 11 | from .lovasz import * 12 | from .soft_bce import * 13 | from .soft_ce import * 14 | from .soft_f1 import * 15 | from .wing_loss import * 16 | from .useful_loss import * 17 | -------------------------------------------------------------------------------- /network/losses/wing_loss.py: -------------------------------------------------------------------------------- 1 | from torch.nn.modules.loss import _Loss 2 | 3 | from . import functional as F 4 | 5 | __all__ = ["WingLoss"] 6 | 7 | 8 | class WingLoss(_Loss): 9 | def __init__(self, width=5, curvature=0.5, reduction="mean"): 10 | super(WingLoss, self).__init__(reduction=reduction) 11 | self.width = width 12 | self.curvature = curvature 13 | 14 | def forward(self, prediction, target): 15 | return F.wing_loss(prediction, target, self.width, self.curvature, self.reduction) 16 | -------------------------------------------------------------------------------- /network/losses/soft_ce.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from torch import nn, Tensor 3 | import torch.nn.functional as F 4 | from .functional import label_smoothed_nll_loss 5 | 6 | __all__ = ["SoftCrossEntropyLoss"] 7 | 8 | 9 | class SoftCrossEntropyLoss(nn.Module): 10 | """ 11 | Drop-in replacement for nn.CrossEntropyLoss with few additions: 12 | - Support of label smoothing 13 | """ 14 | 15 | __constants__ = ["reduction", "ignore_index", "smooth_factor"] 16 | 17 | def __init__(self, reduction: str = "mean", smooth_factor: float = 0.0, ignore_index: Optional[int] = -100, dim=1): 18 | super().__init__() 19 | self.smooth_factor = smooth_factor 20 | self.ignore_index = ignore_index 21 | self.reduction = reduction 22 | self.dim = dim 23 | 24 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 25 | log_prob = F.log_softmax(input, dim=self.dim) 26 | return label_smoothed_nll_loss( 27 | log_prob, 28 | target, 29 | epsilon=self.smooth_factor, 30 | ignore_index=self.ignore_index, 31 | reduction=self.reduction, 32 | dim=self.dim, 33 | ) 34 | -------------------------------------------------------------------------------- /network/losses/shape.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | __all__ = ["ShapeAwareLoss"] 8 | 9 | BINARY_MODE = "binary" 10 | MULTICLASS_MODE = "multiclass" 11 | MULTILABEL_MODE = "multilabel" 12 | 13 | 14 | class DiceLoss(nn.Module): 15 | def __init__(self, weight=None, size_average=True): 16 | super(DiceLoss, self).__init__() 17 | 18 | def forward(self, inputs, targets, smooth=1): 19 | inputs = inputs.reshape(-1) 20 | targets = targets.reshape(-1) 21 | 22 | intersection = (inputs * targets).sum() 23 | dice = (2. * intersection + smooth) / (inputs.sum() + targets.sum() + smooth) 24 | 25 | return 1 - dice 26 | 27 | class ShapeAwareLoss(nn.Module): 28 | def __init__(self, alpha=0.5): 29 | super(ShapeAwareLoss, self).__init__() 30 | self.alpha = alpha 31 | 32 | def forward(self, y_pred, y_true): 33 | dice_loss = DiceLoss() 34 | # print("y_pred size:", y_pred.size()) 35 | num_class = 6 36 | y_true = y_true.unsqueeze(1).expand(-1, num_class, -1, -1) 37 | # print("y_true size:", y_true.size()) 38 | dice_loss_value = dice_loss(y_pred, y_true) 39 | 40 | shape_loss = self.alpha * (1 - dice_loss_value) * y_pred.mean() 41 | combined_loss = dice_loss_value + shape_loss 42 | return combined_loss 43 | 44 | -------------------------------------------------------------------------------- /network/losses/focal_cosine.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from torch import nn, Tensor 3 | import torch.nn.functional as F 4 | import torch 5 | 6 | __all__ = ["FocalCosineLoss"] 7 | 8 | 9 | class FocalCosineLoss(nn.Module): 10 | """ 11 | Implementation Focal cosine loss from the "Data-Efficient Deep Learning Method for Image Classification 12 | Using Data Augmentation, Focal Cosine Loss, and Ensemble" (https://arxiv.org/abs/2007.07805). 13 | 14 | Credit: https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/203271 15 | """ 16 | 17 | def __init__(self, alpha: float = 1, gamma: float = 2, xent: float = 0.1, reduction="mean"): 18 | super(FocalCosineLoss, self).__init__() 19 | self.alpha = alpha 20 | self.gamma = gamma 21 | self.xent = xent 22 | self.reduction = reduction 23 | 24 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 25 | cosine_loss = F.cosine_embedding_loss( 26 | input, 27 | torch.nn.functional.one_hot(target, num_classes=input.size(-1)), 28 | torch.tensor([1], device=target.device), 29 | reduction=self.reduction, 30 | ) 31 | 32 | cent_loss = F.cross_entropy(F.normalize(input), target, reduction="none") 33 | pt = torch.exp(-cent_loss) 34 | focal_loss = self.alpha * (1 - pt) ** self.gamma * cent_loss 35 | 36 | if self.reduction == "mean": 37 | focal_loss = torch.mean(focal_loss) 38 | 39 | return cosine_loss + self.xent * focal_loss 40 | -------------------------------------------------------------------------------- /network/losses/soft_bce.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import torch.nn.functional as F 4 | from torch import nn, Tensor 5 | 6 | __all__ = ["SoftBCEWithLogitsLoss"] 7 | 8 | 9 | class SoftBCEWithLogitsLoss(nn.Module): 10 | """ 11 | Drop-in replacement for nn.BCEWithLogitsLoss with few additions: 12 | - Support of ignore_index value 13 | - Support of label smoothing 14 | """ 15 | 16 | __constants__ = ["weight", "pos_weight", "reduction", "ignore_index", "smooth_factor"] 17 | 18 | def __init__( 19 | self, weight=None, ignore_index: Optional[int] = -100, reduction="mean", smooth_factor=None, pos_weight=None 20 | ): 21 | super().__init__() 22 | self.ignore_index = ignore_index 23 | self.reduction = reduction 24 | self.smooth_factor = smooth_factor 25 | self.register_buffer("weight", weight) 26 | self.register_buffer("pos_weight", pos_weight) 27 | 28 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 29 | if self.smooth_factor is not None: 30 | soft_targets = ((1 - target) * self.smooth_factor + target * (1 - self.smooth_factor)).type_as(input) 31 | else: 32 | soft_targets = target.type_as(input) 33 | 34 | loss = F.binary_cross_entropy_with_logits( 35 | input, soft_targets, self.weight, pos_weight=self.pos_weight, reduction="none" 36 | ) 37 | 38 | if self.ignore_index is not None: 39 | not_ignored_mask: Tensor = target != self.ignore_index 40 | loss *= not_ignored_mask.type_as(loss) 41 | 42 | if self.reduction == "mean": 43 | loss = loss.mean() 44 | 45 | if self.reduction == "sum": 46 | loss = loss.sum() 47 | 48 | return loss 49 | -------------------------------------------------------------------------------- /tools/tsne_feature_map/t_sne_plot.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | from matplotlib.backends.backend_pdf import PdfPages 4 | import os 5 | 6 | # 配置参数 7 | input_paths = [ 8 | "data/grass/tsne/-1.csv", 9 | "data/grass/tsne/0.csv", 10 | "data/grass/tsne/1.csv", 11 | "data/grass/tsne/2.csv", 12 | "data/grass/tsne/2.csv" # 注意:这里路径重复,请确认是否应为 3.csv? 13 | ] 14 | 15 | output_pdf = "data/grass/tsne/all_plots.pdf" # 最终输出路径 16 | figsize = (8, 6) # 统一图片尺寸 17 | dpi = 300 # 打印级分辨率 18 | cmap = "viridis" # 统一配色方案 19 | 20 | def validate_csv(path): 21 | """检查CSV文件是否有效""" 22 | if not os.path.exists(path): 23 | raise FileNotFoundError(f"文件不存在: {path}") 24 | df = pd.read_csv(path) 25 | required_columns = {'x', 'y', 'label'} 26 | if not required_columns.issubset(df.columns): 27 | missing = required_columns - set(df.columns) 28 | raise ValueError(f"文件 {os.path.basename(path)} 缺少必要列: {missing}") 29 | return df 30 | 31 | def plot_single_page(df, pdf, page_num): 32 | """绘制单个PDF页面""" 33 | fig = plt.figure(figsize=figsize, dpi=dpi) 34 | 35 | # 绘制散点图 36 | plt.scatter( 37 | x=df['x'], 38 | y=df['y'], 39 | c=df['label'], 40 | cmap=cmap, 41 | alpha=0.7, 42 | s=10, # 适当增大点尺寸 43 | edgecolor='w', # 白色边缘增强对比 44 | linewidth=0.3 45 | ) 46 | 47 | # 添加页码和文件名 48 | filename = os.path.basename(input_paths[page_num]) 49 | plt.title(f"t-SNE Visualization - {filename}\nPage {page_num+1}", fontsize=10, pad=12) 50 | plt.axis('off') 51 | 52 | # 保存到PDF 53 | pdf.savefig(fig, bbox_inches='tight') 54 | plt.close() 55 | 56 | # 主处理流程 57 | with PdfPages(output_pdf) as pdf: 58 | for i, path in enumerate(input_paths): 59 | try: 60 | df = validate_csv(path) 61 | plot_single_page(df, pdf, i) 62 | print(f"成功处理第 {i+1} 页: {path}") 63 | except Exception as e: 64 | print(f"处理文件 {path} 时出错: {str(e)}") 65 | continue # 跳过错误文件 66 | 67 | print(f"PDF已生成至: {os.path.abspath(output_pdf)}") -------------------------------------------------------------------------------- /network/losses/custom.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | from torch import Tensor 6 | from torch.nn.modules.loss import _Loss 7 | import numpy as np 8 | 9 | from .functional import soft_dice_score 10 | 11 | __all__ = ["DistanceBasedDiceLoss"] 12 | 13 | 14 | # class ModifiedDiceLoss(_Loss): 15 | # def __init__(self, threshold: float, distance_weights=None): 16 | # super(ModifiedDiceLoss, self).__init__() 17 | # self.threshold = threshold 18 | # self.distance_weights = distance_weights 19 | # 20 | # def forward(self, y_pred: Tensor, y_true: Tensor, distances: Tensor) -> Tensor: 21 | # assert y_true.size() == y_pred.size() 22 | # assert y_true.size() == distances.size() 23 | # 24 | # # 경계 정보 추출 (Thresholding) 25 | # boundary_mask = (y_pred > self.threshold).float() 26 | # 27 | # # 거리 정보에 가중치 적용 28 | # if self.distance_weights is not None: 29 | # weighted_distances = distances * self.distance_weights 30 | # else: 31 | # weighted_distances = distances 32 | # 33 | # # 거리 기반 수정된 Dice 손실 계산 34 | # intersection = (boundary_mask * y_true).sum() 35 | # union = boundary_mask.sum() + y_true.sum() 36 | # 37 | # weighted_intersection = (weighted_distances * y_true).sum() 38 | # weighted_union = weighted_distances.sum() + y_true.sum() 39 | # 40 | # dice = 1.0 - (2.0 * weighted_intersection + 1e-7) / (weighted_union + intersection + 1e-7) 41 | # 42 | # return dice 43 | 44 | 45 | BINARY_MODE = "binary" 46 | MULTICLASS_MODE = "multiclass" 47 | MULTILABEL_MODE = "multilabel" 48 | 49 | def to_tensor(x, dtype=None) -> torch.Tensor: 50 | if isinstance(x, torch.Tensor): 51 | if dtype is not None: 52 | x = x.type(dtype) 53 | return x 54 | if isinstance(x, np.ndarray) and x.dtype.kind not in {"O", "M", "U", "S"}: 55 | x = torch.from_numpy(x) 56 | if dtype is not None: 57 | x = x.type(dtype) 58 | return x 59 | if isinstance(x, (list, tuple)): 60 | x = np.ndarray(x) 61 | x = torch.from_numpy(x) 62 | if dtype is not None: 63 | x = x.type(dtype) 64 | return x 65 | 66 | raise ValueError("Unsupported input type" + str(type(x))) 67 | 68 | -------------------------------------------------------------------------------- /tools/cfg.py: -------------------------------------------------------------------------------- 1 | import pydoc 2 | import sys 3 | from importlib import import_module 4 | from pathlib import Path 5 | from typing import Union 6 | 7 | from addict import Dict 8 | 9 | 10 | class ConfigDict(Dict): 11 | def __missing__(self, name): 12 | raise KeyError(name) 13 | 14 | def __getattr__(self, name): 15 | try: 16 | value = super().__getattr__(name) 17 | except KeyError: 18 | ex = AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") 19 | else: 20 | return value 21 | raise ex 22 | 23 | 24 | def py2dict(file_path: Union[str, Path]) -> dict: 25 | """Convert python file to dictionary. 26 | The main use - config parser. 27 | file: 28 | ``` 29 | a = 1 30 | b = 3 31 | c = range(10) 32 | ``` 33 | will be converted to 34 | {'a':1, 35 | 'b':3, 36 | 'c': range(10) 37 | } 38 | Args: 39 | file_path: path to the original python file. 40 | Returns: {key: value}, where key - all variables defined in the file and value is their value. 41 | """ 42 | file_path = Path(file_path).absolute() 43 | 44 | if file_path.suffix != ".py": 45 | raise TypeError(f"Only Py file can be parsed, but got {file_path.name} instead.") 46 | 47 | if not file_path.exists(): 48 | raise FileExistsError(f"There is no file at the path {file_path}") 49 | 50 | module_name = file_path.stem 51 | 52 | if "." in module_name: 53 | raise ValueError("Dots are not allowed in config file path.") 54 | 55 | config_dir = str(file_path.parent) 56 | 57 | sys.path.insert(0, config_dir) 58 | 59 | mod = import_module(module_name) 60 | sys.path.pop(0) 61 | cfg_dict = {name: value for name, value in mod.__dict__.items() if not name.startswith("__")} 62 | 63 | return cfg_dict 64 | 65 | 66 | def py2cfg(file_path: Union[str, Path]) -> ConfigDict: 67 | cfg_dict = py2dict(file_path) 68 | 69 | return ConfigDict(cfg_dict) 70 | 71 | 72 | def object_from_dict(d, parent=None, **default_kwargs): 73 | kwargs = d.copy() 74 | object_type = kwargs.pop("type") 75 | for name, value in default_kwargs.items(): 76 | kwargs.setdefault(name, value) 77 | 78 | if parent is not None: 79 | return getattr(parent, object_type)(**kwargs) # skipcq PTC-W0034 80 | 81 | return pydoc.locate(object_type)(**kwargs) -------------------------------------------------------------------------------- /network/losses/balanced_bce.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | from torch import nn, Tensor 6 | 7 | __all__ = ["BalancedBCEWithLogitsLoss", "balanced_binary_cross_entropy_with_logits"] 8 | 9 | 10 | def balanced_binary_cross_entropy_with_logits( 11 | logits: Tensor, targets: Tensor, gamma: float = 1.0, ignore_index: Optional[int] = None, reduction: str = "mean" 12 | ) -> Tensor: 13 | """ 14 | Balanced binary cross entropy loss. 15 | 16 | Args: 17 | logits: 18 | targets: This loss function expects target values to be hard targets 0/1. 19 | gamma: Power factor for balancing weights 20 | ignore_index: 21 | reduction: 22 | 23 | Returns: 24 | Zero-sized tensor with reduced loss if `reduction` is `sum` or `mean`; Otherwise returns loss of the 25 | shape of `logits` tensor. 26 | """ 27 | pos_targets: Tensor = targets.eq(1).sum() 28 | neg_targets: Tensor = targets.eq(0).sum() 29 | 30 | num_targets = pos_targets + neg_targets 31 | pos_weight = torch.pow(neg_targets / (num_targets + 1e-7), gamma) 32 | neg_weight = 1.0 - pos_weight 33 | 34 | pos_term = pos_weight.pow(gamma) * targets * torch.nn.functional.logsigmoid(logits) 35 | neg_term = neg_weight.pow(gamma) * (1 - targets) * torch.nn.functional.logsigmoid(-logits) 36 | 37 | loss = -(pos_term + neg_term) 38 | 39 | if ignore_index is not None: 40 | loss = torch.masked_fill(loss, targets.eq(ignore_index), 0) 41 | 42 | if reduction == "mean": 43 | loss = loss.mean() 44 | 45 | if reduction == "sum": 46 | loss = loss.sum() 47 | 48 | return loss 49 | 50 | 51 | class BalancedBCEWithLogitsLoss(nn.Module): 52 | """ 53 | Balanced binary cross-entropy loss. 54 | 55 | https://arxiv.org/pdf/1504.06375.pdf (Formula 2) 56 | """ 57 | 58 | __constants__ = ["gamma", "reduction", "ignore_index"] 59 | 60 | def __init__(self, gamma: float = 1.0, reduction="mean", ignore_index: Optional[int] = None): 61 | """ 62 | 63 | Args: 64 | gamma: 65 | ignore_index: 66 | reduction: 67 | """ 68 | super().__init__() 69 | self.gamma = gamma 70 | self.reduction = reduction 71 | self.ignore_index = ignore_index 72 | 73 | def forward(self, output: Tensor, target: Tensor) -> Tensor: 74 | return balanced_binary_cross_entropy_with_logits( 75 | output, target, gamma=self.gamma, ignore_index=self.ignore_index, reduction=self.reduction 76 | ) 77 | -------------------------------------------------------------------------------- /config/grass/d2ls.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from network.losses import * 3 | from network.datasets.grass_dataset import * 4 | from network.models.d2ls import DynamicDictionaryLearning 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 100 10 | ignore_index = 255 11 | train_batch_size = 4 12 | val_batch_size = 4 13 | lr = 1e-4 14 | weight_decay = 0.01 15 | backbone_lr = 0.001 16 | backbone_weight_decay = 0.01 17 | num_classes = len(CLASSES) 18 | token_length = num_classes 19 | classes = CLASSES 20 | 21 | weights_name = "d2ls" 22 | weights_path = "checkpoints/grass/{}".format(weights_name) 23 | test_weights_name = weights_name 24 | log_name = 'grass/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 1 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | pretrained_ckpt_path = None # the path for the pretrained model weight 31 | gpus = [0] # default or gpu ids:[0] or gpu nums: 2, more setting can refer to pytorch_lightning 32 | resume_ckpt_path = None #"checkpoints/grass/delta-0817l0.6/delta-0817l0.6.ckpt" # whether continue training with the checkpoint, default None 33 | strategy = None 34 | 35 | # define the network 36 | net = DynamicDictionaryLearning( 37 | model="convnext_base", 38 | token_length=token_length, 39 | l=3, 40 | ) 41 | # define the loss 42 | loss = UnetFormerLoss(ignore_index=ignore_index) 43 | 44 | use_aux_loss = True 45 | 46 | # define the dataloader 47 | 48 | train_dataset = GrassDataset(data_root='data/grass', img_dir='img_dir', mask_dir='ann_dir', 49 | mode='train', mosaic_ratio=0.25, transform=train_aug, img_size=(256, 256)) 50 | 51 | val_dataset = GrassDataset(data_root='data/grass', img_dir='img_dir', mask_dir='ann_dir', mode='val', 52 | mosaic_ratio=0.0, transform=test_aug, img_size=(256, 256)) 53 | 54 | 55 | train_loader = DataLoader(dataset=train_dataset, 56 | batch_size=train_batch_size, 57 | num_workers=4, 58 | pin_memory=True, 59 | shuffle=True, 60 | drop_last=True) 61 | 62 | val_loader = DataLoader(dataset=val_dataset, 63 | batch_size=val_batch_size, 64 | num_workers=4, 65 | shuffle=False, 66 | pin_memory=True, 67 | drop_last=False) 68 | 69 | # define the optimizer 70 | base_optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=weight_decay) 71 | optimizer = Lookahead(base_optimizer) 72 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epoch, eta_min=1e-6) 73 | 74 | -------------------------------------------------------------------------------- /config/uavid/d2ls.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from network.losses import * 3 | from network.datasets.uavid_dataset import * 4 | from network.models.d2ls import DynamicDictionaryLearning 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 45 10 | ignore_index = 255 11 | train_batch_size = 4 12 | val_batch_size = 4 13 | lr = 1e-4 14 | weight_decay = 0.01 15 | backbone_lr = 0.001 16 | backbone_weight_decay = 0.01 17 | num_classes = len(CLASSES) 18 | token_length = num_classes 19 | classes = CLASSES 20 | 21 | weights_name = "ours_l3" 22 | weights_path = "checkpoints/uavid/{}".format(weights_name) 23 | test_weights_name = weights_name 24 | log_name = 'uavid/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 1 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | pretrained_ckpt_path = None # the path for the pretrained model weight 31 | gpus = [0] # default or gpu ids:[0] or gpu nums: 2, more setting can refer to pytorch_lightning 32 | resume_ckpt_path = None #"checkpoints/uavid/delta-0817l0.6/delta-0817l0.6.ckpt" # whether continue training with the checkpoint, default None 33 | strategy = None 34 | 35 | # define the network 36 | net = DynamicDictionaryLearning( 37 | model="convnext_base", 38 | token_length=token_length, 39 | l=3, 40 | ) 41 | # define the loss 42 | loss = UnetFormerLoss(ignore_index=ignore_index) 43 | 44 | use_aux_loss = True 45 | 46 | # define the dataloader 47 | 48 | train_dataset = UAVIDDataset(data_root='data/uavid/train_val', img_dir='images', mask_dir='masks', 49 | mode='train', mosaic_ratio=0.25, transform=train_aug, img_size=(1024, 1024)) 50 | 51 | val_dataset = UAVIDDataset(data_root='data/uavid/val', img_dir='images', mask_dir='masks', mode='test', 52 | mosaic_ratio=0.0, transform=test_aug, img_size=(1024, 1024)) 53 | 54 | 55 | train_loader = DataLoader(dataset=train_dataset, 56 | batch_size=train_batch_size, 57 | num_workers=4, 58 | pin_memory=True, 59 | shuffle=True, 60 | drop_last=True) 61 | 62 | val_loader = DataLoader(dataset=val_dataset, 63 | batch_size=val_batch_size, 64 | num_workers=4, 65 | shuffle=False, 66 | pin_memory=True, 67 | drop_last=False) 68 | 69 | # define the optimizer 70 | base_optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=weight_decay) 71 | optimizer = Lookahead(base_optimizer) 72 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epoch, eta_min=1e-6) 73 | -------------------------------------------------------------------------------- /network/losses/joint_loss.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | from torch.nn.modules.loss import _Loss 3 | 4 | __all__ = ["JointLoss", "WeightedLoss"] 5 | 6 | 7 | class WeightedLoss(_Loss): 8 | """Wrapper class around loss function that applies weighted with fixed factor. 9 | This class helps to balance multiple losses if they have different scales 10 | """ 11 | 12 | def __init__(self, loss, weight=1.0): 13 | super().__init__() 14 | self.loss = loss 15 | self.weight = weight 16 | 17 | def forward(self, *input): 18 | return self.loss(*input) * self.weight 19 | 20 | 21 | 22 | 23 | class JointLoss(_Loss): 24 | """ 25 | Wrap two loss functions into one. This class computes a weighted sum of two losses. 26 | """ 27 | 28 | def __init__(self, first: nn.Module, second: nn.Module, first_weight=1.0, second_weight=1.0): 29 | super().__init__() 30 | self.first = WeightedLoss(first, first_weight) 31 | self.second = WeightedLoss(second, second_weight) 32 | 33 | def forward(self, *input): 34 | return self.first(*input) + self.second(*input) 35 | 36 | 37 | # class WeightedLoss(_Loss): 38 | # """ 39 | # Wrapper class around loss function that applies weighted with fixed factor and distance weights. 40 | # This class helps to balance multiple losses if they have different scales and incorporate distance weights. 41 | # """ 42 | # 43 | # def __init__(self, loss, weight=1.0, distance_weights=None): 44 | # super().__init__() 45 | # self.loss = loss 46 | # self.weight = weight 47 | # self.distance_weights = distance_weights 48 | # 49 | # def forward(self, logits, labels, distances): 50 | # loss_value = self.loss(logits, labels, distances) 51 | # 52 | # if self.distance_weights is not None: 53 | # weighted_distances = distances * self.distance_weights 54 | # loss_value = loss_value + (weighted_distances * self.weight) 55 | # else: 56 | # loss_value = loss_value * self.weight 57 | # 58 | # return loss_value 59 | # 60 | # class JointLoss(_Loss): 61 | # """ 62 | # Wrap two loss functions into one. This class computes a weighted sum of two losses 63 | # and incorporates distance information. 64 | # """ 65 | # 66 | # def __init__(self, first: nn.Module, second: nn.Module, first_weight=1.0, second_weight=1.0, distance_weights=None): 67 | # super().__init__() 68 | # self.first = WeightedLoss(first, first_weight, distance_weights) 69 | # self.second = WeightedLoss(second, second_weight, distance_weights) 70 | # 71 | # def forward(self, logits, labels, distances): 72 | # return self.first(logits, labels, distances) + self.second(logits, labels, distances) 73 | -------------------------------------------------------------------------------- /config/potsdam/d2ls.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from network.losses import * 3 | from network.datasets.potsdam_dataset import * 4 | from network.models.d2ls import DynamicDictionaryLearning 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 45 10 | ignore_index = len(CLASSES) 11 | train_batch_size = 4 12 | val_batch_size = 4 13 | lr = 1e-4 14 | weight_decay = 0.01 15 | backbone_lr = 1e-3 16 | backbone_weight_decay = 1e-2 17 | num_classes = len(CLASSES) 18 | token_length=num_classes 19 | classes = CLASSES 20 | 21 | test_time_aug = 'd4' 22 | output_mask_dir, output_mask_rgb_dir = None, None 23 | weights_name = "d2ls" 24 | weights_path = "checkpoints/potsdam/{}".format(weights_name) 25 | test_weights_name = weights_name 26 | log_name = 'potsdam/{}'.format(weights_name) 27 | monitor = 'val_F1' 28 | monitor_mode = 'max' 29 | save_top_k = 1 30 | save_last = True 31 | check_val_every_n_epoch = 1 32 | pretrained_ckpt_path = None # the path for the pretrained model weight 33 | gpus = [0] # default or gpu ids:[0] or gpu nums: 2, more setting can refer to pytorch_lightning 34 | resume_ckpt_path = None #"checkpoints/potsdam/delta-0817l0.8lr/delta-0817l0.8lr.ckpt" # whether continue training with the checkpoint, default None 35 | strategy = None 36 | 37 | # define the network 38 | net = DynamicDictionaryLearning( 39 | model="convnext_base", 40 | token_length=token_length, 41 | l=3, 42 | ) 43 | 44 | # define the loss 45 | loss = UnetFormerLoss(ignore_index=ignore_index) 46 | use_aux_loss = True 47 | 48 | # define the dataloader 49 | 50 | train_dataset = PotsdamDataset(data_root='data/potsdam/train', mode='train', 51 | mosaic_ratio=0.25, transform=train_aug) 52 | 53 | val_dataset = PotsdamDataset(transform=val_aug) 54 | test_dataset = PotsdamDataset(data_root='data/potsdam/test', 55 | transform=test_aug) 56 | 57 | train_loader = DataLoader(dataset=train_dataset, 58 | batch_size=train_batch_size, 59 | num_workers=4, 60 | pin_memory=True, 61 | shuffle=True, 62 | drop_last=True) 63 | 64 | val_loader = DataLoader(dataset=val_dataset, 65 | batch_size=val_batch_size, 66 | num_workers=4, 67 | shuffle=False, 68 | pin_memory=True, 69 | drop_last=False) 70 | 71 | # define the optimizer 72 | base_optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=weight_decay) 73 | optimizer = Lookahead(base_optimizer) 74 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epoch, eta_min=1e-6) 75 | 76 | -------------------------------------------------------------------------------- /config/vaihingen/d2ls.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from network.losses import * 3 | from network.datasets.vaihingen_dataset import * 4 | from network.models.d2ls import DynamicDictionaryLearning 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 45 10 | ignore_index = len(CLASSES) 11 | train_batch_size = 4 12 | val_batch_size = 4 13 | lr = 1e-4 14 | weight_decay = 0.01 15 | backbone_lr = 1e-3 16 | backbone_weight_decay = 1e-2 17 | num_classes = len(CLASSES) 18 | token_length=num_classes 19 | classes = CLASSES 20 | 21 | test_time_aug = 'd4' 22 | output_mask_dir, output_mask_rgb_dir = None, None 23 | weights_name = "d2ls" 24 | weights_path = "checkpoints/vaihingen/{}".format(weights_name) 25 | test_weights_name = weights_name 26 | log_name = 'vaihingen/{}'.format(weights_name) 27 | monitor = 'val_F1' 28 | monitor_mode = 'max' 29 | save_top_k = 1 30 | save_last = True 31 | check_val_every_n_epoch = 1 32 | pretrained_ckpt_path = None # the path for the pretrained model weight 33 | gpus = [0] # default or gpu ids:[0] or gpu nums: 2, more setting can refer to pytorch_lightning 34 | resume_ckpt_path = None #"checkpoints/potsdam/delta-0817l0.8lr/delta-0817l0.8lr.ckpt" # whether continue training with the checkpoint, default None 35 | strategy = None 36 | 37 | # define the network 38 | net = DynamicDictionaryLearning( 39 | model="convnext_base", 40 | token_length=token_length, 41 | l=3, 42 | ) 43 | 44 | # define the loss 45 | loss = UnetFormerLoss(ignore_index=ignore_index) 46 | use_aux_loss = True 47 | 48 | # define the dataloader 49 | 50 | # define the dataloader 51 | 52 | train_dataset = VaihingenDataset(data_root='data/vaihingen/train', mode='train', 53 | mosaic_ratio=0.25, transform=train_aug) 54 | 55 | val_dataset = VaihingenDataset(transform=val_aug) 56 | test_dataset = VaihingenDataset(data_root='data/vaihingen/test', 57 | transform=test_aug) 58 | 59 | train_loader = DataLoader(dataset=train_dataset, 60 | batch_size=train_batch_size, 61 | num_workers=4, 62 | pin_memory=True, 63 | shuffle=True, 64 | drop_last=True) 65 | 66 | val_loader = DataLoader(dataset=val_dataset, 67 | batch_size=val_batch_size, 68 | num_workers=4, 69 | shuffle=False, 70 | pin_memory=True, 71 | drop_last=False) 72 | 73 | # define the optimizer 74 | base_optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=weight_decay) 75 | optimizer = Lookahead(base_optimizer) 76 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epoch, eta_min=1e-6) 77 | 78 | -------------------------------------------------------------------------------- /config/cloud/d2ls.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from network.losses import * 3 | from network.datasets.cloud_dataset import * 4 | from network.models.d2ls import DynamicDictionaryLearning 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 100 10 | ignore_index = 255 11 | train_batch_size = 4 12 | val_batch_size = 4 13 | lr = 1e-4 14 | weight_decay = 0.01 15 | backbone_lr = 0.001 16 | backbone_weight_decay = 0.01 17 | num_classes = len(CLASSES) 18 | token_length = num_classes 19 | classes = CLASSES 20 | 21 | weights_name = "d2ls" 22 | weights_path = "checkpoints/cloud/{}".format(weights_name) 23 | test_weights_name = weights_name 24 | log_name = 'cloud/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 1 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | pretrained_ckpt_path = None # the path for the pretrained model weight 31 | gpus = [0] # default or gpu ids:[0] or gpu nums: 2, more setting can refer to pytorch_lightning 32 | resume_ckpt_path = None #"checkpoints/cloud/delta-0817l0.6/delta-0817l0.6.ckpt" # whether continue training with the checkpoint, default None 33 | strategy = None 34 | 35 | # define the network 36 | net = DynamicDictionaryLearning( 37 | model="convnext_base", 38 | token_length=token_length, 39 | l=3, 40 | ) 41 | # define the loss 42 | loss = UnetFormerLoss(ignore_index=ignore_index) 43 | 44 | use_aux_loss = True 45 | 46 | # define the dataloader 47 | 48 | train_dataset = CloudDataset(data_root='data/cloud', img_dir='img_dir', mask_dir='ann_dir', 49 | mode='train', mosaic_ratio=0.25, transform=train_aug, img_size=(512, 512)) 50 | 51 | val_dataset = CloudDataset(data_root='data/cloud', img_dir='img_dir', mask_dir='ann_dir', 52 | mode='test', mosaic_ratio=0.25, transform=train_aug, img_size=(512, 512)) 53 | 54 | test_dataset = CloudDataset(data_root='data/cloud', img_dir='img_dir', mask_dir='ann_dir', 55 | mode='test', mosaic_ratio=0.25, transform=train_aug, img_size=(512, 512)) 56 | 57 | train_loader = DataLoader(dataset=train_dataset, 58 | batch_size=train_batch_size, 59 | num_workers=4, 60 | pin_memory=True, 61 | shuffle=True, 62 | drop_last=True) 63 | 64 | val_loader = DataLoader(dataset=val_dataset, 65 | batch_size=val_batch_size, 66 | num_workers=4, 67 | shuffle=False, 68 | pin_memory=True, 69 | drop_last=False) 70 | 71 | # define the optimizer 72 | base_optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=weight_decay) 73 | optimizer = Lookahead(base_optimizer) 74 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epoch, eta_min=1e-6) 75 | 76 | -------------------------------------------------------------------------------- /network/losses/focal.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import torch 4 | from torch.nn.modules.loss import _Loss 5 | 6 | from .functional import focal_loss_with_logits 7 | 8 | __all__ = ["BinaryFocalLoss", "FocalLoss"] 9 | 10 | 11 | class BinaryFocalLoss(_Loss): 12 | def __init__( 13 | self, 14 | alpha=0.5, 15 | gamma: float = 2.0, 16 | ignore_index=None, 17 | reduction="mean", 18 | normalized=False, 19 | reduced_threshold=None, 20 | ): 21 | """ 22 | 23 | :param alpha: Prior probability of having positive value in target. 24 | :param gamma: Power factor for dampening weight (focal strenght). 25 | :param ignore_index: If not None, targets may contain values to be ignored. 26 | Target values equal to ignore_index will be ignored from loss computation. 27 | :param reduced: Switch to reduced focal loss. Note, when using this mode you should use `reduction="sum"`. 28 | :param threshold: 29 | """ 30 | super().__init__() 31 | self.ignore_index = ignore_index 32 | self.focal_loss_fn = partial( 33 | focal_loss_with_logits, 34 | alpha=alpha, 35 | gamma=gamma, 36 | reduced_threshold=reduced_threshold, 37 | reduction=reduction, 38 | normalized=normalized, 39 | ignore_index=ignore_index, 40 | ) 41 | 42 | def forward(self, label_input, label_target): 43 | """Compute focal loss for binary classification problem.""" 44 | loss = self.focal_loss_fn(label_input, label_target) 45 | return loss 46 | 47 | 48 | class FocalLoss(_Loss): 49 | def __init__(self, alpha=0.5, gamma=2, ignore_index=None, reduction="mean", normalized=False, reduced_threshold=None): 50 | """ 51 | Focal loss for multi-class problem. 52 | 53 | :param alpha: 54 | :param gamma: 55 | :param ignore_index: If not None, targets with given index are ignored 56 | :param reduced_threshold: A threshold factor for computing reduced focal loss 57 | """ 58 | super().__init__() 59 | self.ignore_index = ignore_index 60 | self.focal_loss_fn = partial( 61 | focal_loss_with_logits, 62 | alpha=alpha, 63 | gamma=gamma, 64 | reduced_threshold=reduced_threshold, 65 | reduction=reduction, 66 | normalized=normalized, 67 | ) 68 | 69 | def forward(self, label_input, label_target): 70 | num_classes = label_input.size(1) 71 | loss = 0 72 | 73 | # Filter anchors with -1 label from loss computation 74 | if self.ignore_index is not None: 75 | not_ignored = label_target != self.ignore_index 76 | 77 | for cls in range(num_classes): 78 | cls_label_target = (label_target == cls).long() 79 | cls_label_input = label_input[:, cls, ...] 80 | 81 | if self.ignore_index is not None: 82 | cls_label_target = cls_label_target[not_ignored] 83 | cls_label_input = cls_label_input[not_ignored] 84 | 85 | loss += self.focal_loss_fn(cls_label_input, cls_label_target) 86 | return loss 87 | -------------------------------------------------------------------------------- /tools/geoseg_loveda_mask_convert.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import numpy as np 4 | import cv2 5 | import multiprocessing.pool as mpp 6 | import multiprocessing as mp 7 | import time 8 | import argparse 9 | import torch 10 | import random 11 | 12 | SEED = 42 13 | 14 | CLASSES = ('background', 'building', 'road', 'water', 'barren', 'forest', 15 | 'agricultural') 16 | 17 | PALETTE = [[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255], 18 | [159, 129, 183], [0, 255, 0], [255, 195, 128]] 19 | 20 | 21 | def seed_everything(seed): 22 | random.seed(seed) 23 | os.environ['PYTHONHASHSEED'] = str(seed) 24 | np.random.seed(seed) 25 | torch.manual_seed(seed) 26 | torch.cuda.manual_seed(seed) 27 | torch.backends.cudnn.deterministic = True 28 | torch.backends.cudnn.benchmark = True 29 | 30 | 31 | def parse_args(): 32 | parser = argparse.ArgumentParser() 33 | parser.add_argument("--mask-dir", default="data/LoveDA/Train/Rural/masks_png") 34 | parser.add_argument("--output-mask-dir", default="data/LoveDA/Train/Rural/masks_png_convert") 35 | return parser.parse_args() 36 | 37 | 38 | def convert_label(mask): 39 | mask[mask == 0] = 8 40 | mask -= 1 41 | 42 | return mask 43 | 44 | 45 | def label2rgb(mask): 46 | h, w = mask.shape[0], mask.shape[1] 47 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 48 | mask_convert = mask[np.newaxis, :, :] 49 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 50 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 51 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [255, 255, 0] 52 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [0, 0, 255] 53 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [159, 129, 183] 54 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [0, 255, 0] 55 | mask_rgb[np.all(mask_convert == 6, axis=0)] = [255, 195, 128] 56 | return mask_rgb 57 | 58 | 59 | def patch_format(inp): 60 | (mask_path, masks_output_dir) = inp 61 | # print(mask_path, masks_output_dir) 62 | mask_filename = os.path.splitext(os.path.basename(mask_path))[0] 63 | mask = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED) 64 | label = convert_label(mask) 65 | rgb_label = label2rgb(label.copy()) 66 | rgb_label = cv2.cvtColor(rgb_label, cv2.COLOR_RGB2BGR) 67 | out_mask_path_rgb = os.path.join(masks_output_dir + '_rgb', "{}.png".format(mask_filename)) 68 | cv2.imwrite(out_mask_path_rgb, rgb_label) 69 | 70 | out_mask_path = os.path.join(masks_output_dir, "{}.png".format(mask_filename)) 71 | cv2.imwrite(out_mask_path, label) 72 | 73 | 74 | if __name__ == "__main__": 75 | seed_everything(SEED) 76 | args = parse_args() 77 | masks_dir = args.mask_dir 78 | masks_output_dir = args.output_mask_dir 79 | mask_paths = glob.glob(os.path.join(masks_dir, "*.png")) 80 | 81 | if not os.path.exists(masks_output_dir): 82 | os.makedirs(masks_output_dir) 83 | os.makedirs(masks_output_dir + '_rgb') 84 | 85 | inp = [(mask_path, masks_output_dir) for mask_path in mask_paths] 86 | 87 | t0 = time.time() 88 | mpp.Pool(processes=mp.cpu_count()).map(patch_format, inp) 89 | t1 = time.time() 90 | split_time = t1 - t0 91 | print('images spliting spends: {} s'.format(split_time)) -------------------------------------------------------------------------------- /tools/loveda_mask_convert.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import numpy as np 4 | import cv2 5 | import multiprocessing.pool as mpp 6 | import multiprocessing as mp 7 | import time 8 | import argparse 9 | import torch 10 | import random 11 | 12 | SEED = 42 13 | 14 | CLASSES = ('background', 'building', 'road', 'water', 'barren', 'forest', 15 | 'agricultural') 16 | 17 | PALETTE = [[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255], 18 | [159, 129, 183], [0, 255, 0], [255, 195, 128]] 19 | 20 | 21 | def seed_everything(seed): 22 | random.seed(seed) 23 | os.environ['PYTHONHASHSEED'] = str(seed) 24 | np.random.seed(seed) 25 | torch.manual_seed(seed) 26 | torch.cuda.manual_seed(seed) 27 | torch.backends.cudnn.deterministic = True 28 | torch.backends.cudnn.benchmark = True 29 | 30 | 31 | def parse_args(): 32 | parser = argparse.ArgumentParser() 33 | parser.add_argument("--mask-dir", default="data/LoveDA/Train/Rural/masks_png") 34 | parser.add_argument("--output-mask-dir", default="data/LoveDA/Train/Rural/masks_png_convert") 35 | return parser.parse_args() 36 | 37 | 38 | def convert_label(mask): 39 | mask[mask == 0] = 8 40 | mask -= 1 41 | 42 | return mask 43 | 44 | 45 | def label2rgb(mask): 46 | h, w = mask.shape[0], mask.shape[1] 47 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 48 | mask_convert = mask[np.newaxis, :, :] 49 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 50 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 51 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [255, 255, 0] 52 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [0, 0, 255] 53 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [159, 129, 183] 54 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [0, 255, 0] 55 | mask_rgb[np.all(mask_convert == 6, axis=0)] = [255, 195, 128] 56 | return mask_rgb 57 | 58 | 59 | def patch_format(inp): 60 | (mask_path, masks_output_dir) = inp 61 | # print(mask_path, masks_output_dir) 62 | mask_filename = os.path.splitext(os.path.basename(mask_path))[0] 63 | mask = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED) 64 | label = convert_label(mask) 65 | rgb_label = label2rgb(label.copy()) 66 | rgb_label = cv2.cvtColor(rgb_label, cv2.COLOR_RGB2BGR) 67 | out_mask_path_rgb = os.path.join(masks_output_dir + '_rgb', "{}.png".format(mask_filename)) 68 | cv2.imwrite(out_mask_path_rgb, rgb_label) 69 | 70 | out_mask_path = os.path.join(masks_output_dir, "{}.png".format(mask_filename)) 71 | cv2.imwrite(out_mask_path, label) 72 | 73 | 74 | if __name__ == "__main__": 75 | seed_everything(SEED) 76 | args = parse_args() 77 | masks_dir = args.mask_dir 78 | masks_output_dir = args.output_mask_dir 79 | mask_paths = glob.glob(os.path.join(masks_dir, "*.png")) 80 | 81 | if not os.path.exists(masks_output_dir): 82 | os.makedirs(masks_output_dir) 83 | os.makedirs(masks_output_dir + '_rgb') 84 | 85 | inp = [(mask_path, masks_output_dir) for mask_path in mask_paths] 86 | 87 | t0 = time.time() 88 | mpp.Pool(processes=mp.cpu_count()).map(patch_format, inp) 89 | t1 = time.time() 90 | split_time = t1 - t0 91 | print('images spliting spends: {} s'.format(split_time)) 92 | 93 | 94 | -------------------------------------------------------------------------------- /config/loveda/d2ls.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from network.losses import * 3 | from network.datasets.loveda_dataset import * 4 | from network.models.d2ls import DynamicDictionaryLearning 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 30 10 | ignore_index = len(CLASSES) 11 | train_batch_size = 8 12 | val_batch_size = 8 13 | lr = 8e-5 14 | weight_decay = 0.01 15 | # backbone_lr = 0.001 16 | backbone_weight_decay = 0.01 17 | num_classes = len(CLASSES) 18 | token_length=num_classes 19 | classes = CLASSES 20 | 21 | weights_name = "d2ls" 22 | weights_path = "checkpoints/loveda/{}".format(weights_name) 23 | test_weights_name = weights_name 24 | log_name = 'loveda/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 1 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | pretrained_ckpt_path = None # the path for the pretrained model weight 31 | gpus = [0] # default or gpu ids:[0] or gpu nums: 2, more setting can refer to pytorch_lightning 32 | resume_ckpt_path = None #"checkpoints/loveda/delta-0817l0.8lr/delta-0817l0.8lr.ckpt" # whether continue training with the checkpoint, default None 33 | 34 | # define the network 35 | net = DynamicDictionaryLearning( 36 | model="convnext_base", 37 | token_length=token_length, 38 | l=3 39 | ) 40 | 41 | # define the loss 42 | loss = UnetFormerLoss(ignore_index=ignore_index) 43 | use_aux_loss = True 44 | 45 | # define the dataloader 46 | 47 | def get_training_transform(): 48 | train_transform = [ 49 | albu.RandomRotate90(p=0.5), 50 | albu.HorizontalFlip(p=0.5), 51 | albu.VerticalFlip(p=0.5), 52 | albu.Normalize() 53 | ] 54 | return albu.Compose(train_transform) 55 | 56 | 57 | def train_aug(img, mask): 58 | crop_aug = Compose([RandomScale(scale_list=[0.75, 1.0, 1.25, 1.5], mode='value'), 59 | SmartCropV1(crop_size=512, max_ratio=0.75, ignore_index=ignore_index, nopad=False)]) 60 | img, mask = crop_aug(img, mask) 61 | img, mask = np.array(img), np.array(mask) 62 | aug = get_training_transform()(image=img.copy(), mask=mask.copy()) 63 | img, mask = aug['image'], aug['mask'] 64 | return img, mask 65 | 66 | 67 | train_dataset = LoveDATrainDataset(transform=train_aug, data_root='data/LoveDA/train_val') 68 | 69 | val_dataset = loveda_val_dataset 70 | 71 | test_dataset = LoveDATestDataset() 72 | 73 | train_loader = DataLoader(dataset=train_dataset, 74 | batch_size=train_batch_size, 75 | num_workers=4, 76 | pin_memory=True, 77 | shuffle=True, 78 | drop_last=True) 79 | 80 | val_loader = DataLoader(dataset=val_dataset, 81 | batch_size=val_batch_size, 82 | num_workers=4, 83 | shuffle=False, 84 | pin_memory=True, 85 | drop_last=False) 86 | 87 | # define the optimizer 88 | base_optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=weight_decay) 89 | optimizer = Lookahead(base_optimizer) 90 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_epoch, eta_min=1e-6) 91 | 92 | -------------------------------------------------------------------------------- /tools/metric.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Evaluator(object): 5 | def __init__(self, num_class): 6 | self.num_class = num_class 7 | self.confusion_matrix = np.zeros((self.num_class,) * 2) 8 | self.eps = 1e-8 9 | 10 | def get_tp_fp_tn_fn(self): 11 | tp = np.diag(self.confusion_matrix) 12 | fp = self.confusion_matrix.sum(axis=0) - np.diag(self.confusion_matrix) 13 | fn = self.confusion_matrix.sum(axis=1) - np.diag(self.confusion_matrix) 14 | tn = np.diag(self.confusion_matrix).sum() - np.diag(self.confusion_matrix) 15 | return tp, fp, tn, fn 16 | 17 | def Precision(self): 18 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 19 | precision = tp / (tp + fp) 20 | return precision 21 | 22 | def Recall(self): 23 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 24 | recall = tp / (tp + fn) 25 | return recall 26 | 27 | def F1(self): 28 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 29 | Precision = tp / (tp + fp) 30 | Recall = tp / (tp + fn) 31 | F1 = (2.0 * Precision * Recall) / (Precision + Recall) 32 | return F1 33 | 34 | def OA(self): 35 | OA = np.diag(self.confusion_matrix).sum() / (self.confusion_matrix.sum() + self.eps) 36 | return OA 37 | 38 | def Intersection_over_Union(self): 39 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 40 | IoU = tp / (tp + fn + fp) 41 | return IoU 42 | 43 | def Dice(self): 44 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 45 | Dice = 2 * tp / ((tp + fp) + (tp + fn)) 46 | return Dice 47 | 48 | def Pixel_Accuracy_Class(self): 49 | # TP TP+FP 50 | Acc = np.diag(self.confusion_matrix) / (self.confusion_matrix.sum(axis=0) + self.eps) 51 | return Acc 52 | 53 | def Frequency_Weighted_Intersection_over_Union(self): 54 | freq = np.sum(self.confusion_matrix, axis=1) / (np.sum(self.confusion_matrix) + self.eps) 55 | iou = self.Intersection_over_Union() 56 | FWIoU = (freq[freq > 0] * iou[freq > 0]).sum() 57 | return FWIoU 58 | 59 | def _generate_matrix(self, gt_image, pre_image): 60 | mask = (gt_image >= 0) & (gt_image < self.num_class) 61 | label = self.num_class * gt_image[mask].astype('int') + pre_image[mask] 62 | count = np.bincount(label, minlength=self.num_class ** 2) 63 | confusion_matrix = count.reshape(self.num_class, self.num_class) 64 | return confusion_matrix 65 | 66 | def add_batch(self, gt_image, pre_image): 67 | assert gt_image.shape == pre_image.shape, 'pre_image shape {}, gt_image shape {}'.format(pre_image.shape, 68 | gt_image.shape) 69 | self.confusion_matrix += self._generate_matrix(gt_image, pre_image) 70 | 71 | def reset(self): 72 | self.confusion_matrix = np.zeros((self.num_class,) * 2) 73 | 74 | 75 | if __name__ == '__main__': 76 | 77 | gt = np.array([[0, 2, 1], 78 | [1, 2, 1], 79 | [1, 0, 1]]) 80 | 81 | pre = np.array([[0, 1, 1], 82 | [2, 0, 1], 83 | [1, 1, 1]]) 84 | 85 | eval = Evaluator(num_class=3) 86 | eval.add_batch(gt, pre) 87 | print(eval.confusion_matrix) 88 | print(eval.get_tp_fp_tn_fn()) 89 | print(eval.Precision()) 90 | print(eval.Recall()) 91 | print(eval.Intersection_over_Union()) 92 | print(eval.OA()) 93 | print(eval.F1()) 94 | print(eval.Frequency_Weighted_Intersection_over_Union()) 95 | -------------------------------------------------------------------------------- /tools/tsne_feature_map/space_tsne.py: -------------------------------------------------------------------------------- 1 | # 标准库 2 | import os 3 | import math 4 | import warnings 5 | from glob import glob 6 | import argparse 7 | from typing import Any, List, Optional, Tuple, Type 8 | 9 | # 第三方库 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | import albumentations as albu 13 | from PIL import Image 14 | from tqdm import tqdm 15 | from sklearn.manifold import TSNE 16 | import torch 17 | import torch.nn as nn 18 | import torch.nn.functional as F 19 | import torchvision.models as models 20 | from torch import Tensor 21 | from torchvision.models import ( 22 | convnext_base, 23 | convnext_small, 24 | convnext_tiny, 25 | swin_b, 26 | swin_v2_b, 27 | swin_v2_s, 28 | swin_v2_t, 29 | mobilenet_v3_large, 30 | efficientnet_v2_m, 31 | ) 32 | 33 | # 警告过滤 34 | warnings.filterwarnings("ignore") 35 | 36 | from scipy.spatial.distance import pdist, cdist 37 | 38 | 39 | def plot_tsne( 40 | data, 41 | labels=None, 42 | perplexity=30, 43 | learning_rate=200, 44 | n_iter=2000, 45 | random_state=42, 46 | title="t-SNE Visualization", 47 | filename="tsne.png", 48 | ): 49 | """ 50 | 使用 t-SNE 对高维数据进行降维并可视化。 51 | 52 | 参数: 53 | - data: np.array 或者 pd.DataFrame, 需要降维的数据,形状为 (N, D) 54 | - labels: 可选,类别标签,若提供则颜色区分 55 | - perplexity: t-SNE 的困惑度,影响点之间的分布关系 56 | - learning_rate: t-SNE 的学习率 57 | - n_iter: t-SNE 的迭代次数 58 | - random_state: 随机种子,保证结果可复现 59 | """ 60 | dim = data.shape[-1] 61 | data = data.reshape(-1, dim) 62 | bs = data.shape[0] 63 | labels = np.array([i for i in range(5)]) 64 | labels = np.tile(labels, (bs + len(labels) - 1) // len(labels))[:bs] 65 | 66 | 67 | tsne = TSNE( 68 | n_components=2, 69 | perplexity=perplexity, 70 | learning_rate=learning_rate, 71 | n_iter=n_iter, 72 | random_state=random_state, 73 | ) 74 | 75 | reduced_data = tsne.fit_transform(data) 76 | 77 | plt.figure(figsize=(8, 6)) 78 | plt.subplots_adjust(left=0, right=1, bottom=0, top=1) 79 | 80 | scatter = plt.scatter( 81 | reduced_data[:, 0], reduced_data[:, 1], c=labels, cmap="jet", alpha=0.7, s=2 82 | ) 83 | # plt.colorbar(scatter) 84 | # plt.title(title) 85 | # plt.xlabel("t-SNE Component 1") 86 | # plt.ylabel("t-SNE Component 2") 87 | # plt.grid(True) 88 | plt.axis("off") 89 | filename = os.path.join(filename) 90 | plt.savefig(filename,bbox_inches='tight',pad_inches=0) 91 | plt.close() 92 | 93 | 94 | # 计算类内距离和类间距离 95 | unique_labels = np.unique(labels) 96 | n_classes = len(unique_labels) 97 | 98 | # 类内距离:每个类别内部样本的平均距离 99 | intra_distances = [] 100 | for label in unique_labels: 101 | class_data = reduced_data[labels == label] 102 | if len(class_data) < 2: 103 | continue # 单个样本无法计算距离 104 | distances = pdist(class_data, "euclidean") 105 | intra_distances.append(np.mean(distances)) 106 | intra_distance = np.mean(intra_distances) if intra_distances else 0.0 107 | 108 | # 类间距离:基于类中心计算 109 | if n_classes >= 2: 110 | centroids = [ 111 | np.mean(reduced_data[labels == label], axis=0) for label in unique_labels 112 | ] 113 | centroid_dists = pdist(centroids, "euclidean") 114 | inter_distance = np.mean(centroid_dists) 115 | else: 116 | inter_distance = 0.0 # 仅一个类别 117 | 118 | print(f"类内平均距离: {intra_distance:.2f}", end=" ") 119 | print(f"类间平均距离 (基于类中心): {inter_distance:.2f}") 120 | 121 | data = [] 122 | for _ in range(1151): 123 | data.append(nn.Embedding(7,512).weight.detach().numpy()) 124 | 125 | data = np.array(data) 126 | plot_tsne(data) 127 | -------------------------------------------------------------------------------- /network/losses/jaccard.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | from .dice import to_tensor 6 | from torch import Tensor 7 | from torch.nn.modules.loss import _Loss 8 | 9 | from .functional import soft_jaccard_score 10 | 11 | __all__ = ["JaccardLoss", "BINARY_MODE", "MULTICLASS_MODE", "MULTILABEL_MODE"] 12 | 13 | BINARY_MODE = "binary" 14 | MULTICLASS_MODE = "multiclass" 15 | MULTILABEL_MODE = "multilabel" 16 | 17 | 18 | class JaccardLoss(_Loss): 19 | """ 20 | Implementation of Jaccard loss for image segmentation task. 21 | It supports binary, multi-class and multi-label cases. 22 | """ 23 | 24 | def __init__(self, mode: str = 'multiclass', classes: List[int] = None, log_loss=False, from_logits=True, smooth=0, eps=1e-7): 25 | """ 26 | 27 | :param mode: Metric mode {'binary', 'multiclass', 'multilabel'} 28 | :param classes: Optional list of classes that contribute in loss computation; 29 | By default, all channels are included. 30 | :param log_loss: If True, loss computed as `-log(jaccard)`; otherwise `1 - jaccard` 31 | :param from_logits: If True assumes input is raw logits 32 | :param smooth: 33 | :param eps: Small epsilon for numerical stability 34 | """ 35 | assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE} 36 | super(JaccardLoss, self).__init__() 37 | self.mode = mode 38 | if classes is not None: 39 | assert mode != BINARY_MODE, "Masking classes is not supported with mode=binary" 40 | classes = to_tensor(classes, dtype=torch.long) 41 | 42 | self.classes = classes 43 | self.from_logits = from_logits 44 | self.smooth = smooth 45 | self.eps = eps 46 | self.log_loss = log_loss 47 | 48 | def forward(self, y_pred: Tensor, y_true: Tensor) -> Tensor: 49 | """ 50 | 51 | :param y_pred: NxCxHxW 52 | :param y_true: NxHxW 53 | :return: scalar 54 | """ 55 | assert y_true.size(0) == y_pred.size(0) 56 | 57 | if self.from_logits: 58 | # Apply activations to get [0..1] class probabilities 59 | # Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on 60 | # extreme values 0 and 1 61 | if self.mode == MULTICLASS_MODE: 62 | y_pred = y_pred.log_softmax(dim=1).exp() 63 | else: 64 | y_pred = F.logsigmoid(y_pred).exp() 65 | 66 | bs = y_true.size(0) 67 | num_classes = y_pred.size(1) 68 | dims = (0, 2) 69 | 70 | if self.mode == BINARY_MODE: 71 | y_true = y_true.view(bs, 1, -1) 72 | y_pred = y_pred.view(bs, 1, -1) 73 | 74 | if self.mode == MULTICLASS_MODE: 75 | y_true = y_true.view(bs, -1) 76 | y_pred = y_pred.view(bs, num_classes, -1) 77 | 78 | y_true = F.one_hot(y_true, num_classes) # N,H*W -> N,H*W, C 79 | y_true = y_true.permute(0, 2, 1) # H, C, H*W 80 | 81 | if self.mode == MULTILABEL_MODE: 82 | y_true = y_true.view(bs, num_classes, -1) 83 | y_pred = y_pred.view(bs, num_classes, -1) 84 | 85 | scores = soft_jaccard_score(y_pred, y_true.type(y_pred.dtype), smooth=self.smooth, eps=self.eps, dims=dims) 86 | 87 | if self.log_loss: 88 | loss = -torch.log(scores.clamp_min(self.eps)) 89 | else: 90 | loss = 1.0 - scores 91 | 92 | # IoU loss is defined for non-empty classes 93 | # So we zero contribution of channel that does not have true pixels 94 | # NOTE: A better workaround would be to use loss term `mean(y_pred)` 95 | # for this case, however it will be a modified jaccard loss 96 | 97 | mask = y_true.sum(dims) > 0 98 | loss *= mask.float() 99 | 100 | if self.classes is not None: 101 | loss = loss[self.classes] 102 | 103 | return loss.mean() 104 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # PyPI configuration file 171 | .pypirc 172 | envs/ 173 | data/ 174 | logs/ 175 | checkpoints/ 176 | fig_results/ 177 | *.tar.gz -------------------------------------------------------------------------------- /network/losses/soft_f1.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn, Tensor 3 | from typing import Optional 4 | 5 | __all__ = ["soft_micro_f1", "BinarySoftF1Loss", "SoftF1Loss"] 6 | 7 | 8 | def soft_micro_f1(preds: Tensor, targets: Tensor, eps=1e-6) -> Tensor: 9 | """Compute the macro soft F1-score as a cost. 10 | Average (1 - soft-F1) across all labels. 11 | Use probability values instead of binary predictions. 12 | 13 | Args: 14 | targets (Tensor): targets array of shape (Num Samples, Num Classes) 15 | preds (Tensor): probability matrix of shape (Num Samples, Num Classes) 16 | 17 | Returns: 18 | cost (scalar Tensor): value of the cost function for the batch 19 | 20 | References: 21 | https://towardsdatascience.com/the-unknown-benefits-of-using-a-soft-f1-loss-in-classification-systems-753902c0105d 22 | """ 23 | tp = torch.sum(preds * targets, dim=0) 24 | fp = torch.sum(preds * (1 - targets), dim=0) 25 | fn = torch.sum((1 - preds) * targets, dim=0) 26 | soft_f1 = 2 * tp / (2 * tp + fn + fp + eps) 27 | loss = 1 - soft_f1 # reduce 1 - soft-f1 in order to increase soft-f1 28 | return loss.mean() 29 | 30 | 31 | # TODO: Test 32 | # def macro_double_soft_f1(y, y_hat): 33 | # """Compute the macro soft F1-score as a cost (average 1 - soft-F1 across all labels). 34 | # Use probability values instead of binary predictions. 35 | # This version uses the computation of soft-F1 for both positive and negative class for each label. 36 | # 37 | # Args: 38 | # y (int32 Tensor): targets array of shape (BATCH_SIZE, N_LABELS) 39 | # y_hat (float32 Tensor): probability matrix from forward propagation of shape (BATCH_SIZE, N_LABELS) 40 | # 41 | # Returns: 42 | # cost (scalar Tensor): value of the cost function for the batch 43 | # """ 44 | # tp = tf.reduce_sum(y_hat * y, axis=0) 45 | # fp = tf.reduce_sum(y_hat * (1 - y), axis=0) 46 | # fn = tf.reduce_sum((1 - y_hat) * y, axis=0) 47 | # tn = tf.reduce_sum((1 - y_hat) * (1 - y), axis=0) 48 | # soft_f1_class1 = 2 * tp / (2 * tp + fn + fp + 1e-16) 49 | # soft_f1_class0 = 2 * tn / (2 * tn + fn + fp + 1e-16) 50 | # cost_class1 = 1 - soft_f1_class1 # reduce 1 - soft-f1_class1 in order to increase soft-f1 on class 1 51 | # cost_class0 = 1 - soft_f1_class0 # reduce 1 - soft-f1_class0 in order to increase soft-f1 on class 0 52 | # cost = 0.5 * (cost_class1 + cost_class0) # take into account both class 1 and class 0 53 | # macro_cost = tf.reduce_mean(cost) # average on all labels 54 | # return macro_cost 55 | 56 | 57 | class BinarySoftF1Loss(nn.Module): 58 | def __init__(self, ignore_index: Optional[int] = None, eps=1e-6): 59 | super().__init__() 60 | self.ignore_index = ignore_index 61 | self.eps = eps 62 | 63 | def forward(self, preds: Tensor, targets: Tensor) -> Tensor: 64 | targets = targets.view(-1) 65 | preds = preds.view(-1) 66 | 67 | if self.ignore_index is not None: 68 | # Filter predictions with ignore label from loss computation 69 | not_ignored = targets != self.ignore_index 70 | preds = preds[not_ignored] 71 | targets = targets[not_ignored] 72 | 73 | if targets.numel() == 0: 74 | return torch.tensor(0, dtype=preds.dtype, device=preds.device) 75 | 76 | preds = preds.sigmoid().clamp(self.eps, 1 - self.eps) 77 | return soft_micro_f1(preds.view(-1, 1), targets.view(-1, 1)) 78 | 79 | 80 | class SoftF1Loss(nn.Module): 81 | def __init__(self, ignore_index: Optional[int] = None, eps=1e-6): 82 | super().__init__() 83 | self.ignore_index = ignore_index 84 | self.eps = eps 85 | 86 | def forward(self, preds: Tensor, targets: Tensor) -> Tensor: 87 | preds = preds.softmax(dim=1).clamp(self.eps, 1 - self.eps) 88 | targets = torch.nn.functional.one_hot(targets, preds.size(1)) 89 | 90 | if self.ignore_index is not None: 91 | # Filter predictions with ignore label from loss computation 92 | not_ignored = targets != self.ignore_index 93 | preds = preds[not_ignored] 94 | targets = targets[not_ignored] 95 | 96 | if targets.numel() == 0: 97 | return torch.tensor(0, dtype=preds.dtype, device=preds.device) 98 | 99 | return soft_micro_f1(preds, targets) 100 | -------------------------------------------------------------------------------- /network/losses/useful_loss.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn.functional as F 4 | import torch.nn as nn 5 | from torch import Tensor 6 | from .soft_ce import SoftCrossEntropyLoss 7 | from .joint_loss import JointLoss 8 | from .dice import DiceLoss 9 | 10 | from .focal import FocalLoss 11 | 12 | 13 | class EdgeLoss(nn.Module): 14 | def __init__(self, ignore_index=255, edge_factor=1.0): 15 | super(EdgeLoss, self).__init__() 16 | self.main_loss = JointLoss(SoftCrossEntropyLoss(smooth_factor=0.05, ignore_index=ignore_index), 17 | DiceLoss(smooth=0.05, ignore_index=ignore_index), 1.0, 1.0) 18 | self.edge_factor = edge_factor 19 | 20 | def get_boundary(self, x): 21 | laplacian_kernel_target = torch.tensor( 22 | [-1, -1, -1, -1, 8, -1, -1, -1, -1], 23 | dtype=torch.float32).reshape(1, 1, 3, 3).requires_grad_(False).cuda(device=x.device) 24 | x = x.unsqueeze(1).float() 25 | x = F.conv2d(x, laplacian_kernel_target, padding=1) 26 | x = x.clamp(min=0) 27 | x[x >= 0.1] = 1 28 | x[x < 0.1] = 0 29 | 30 | return x 31 | 32 | def compute_edge_loss(self, logits, targets): 33 | bs = logits.size()[0] 34 | boundary_targets = self.get_boundary(targets) 35 | boundary_targets = boundary_targets.view(bs, 1, -1) 36 | # print(boundary_targets.shape) 37 | logits = F.softmax(logits, dim=1).argmax(dim=1).squeeze(dim=1) 38 | boundary_pre = self.get_boundary(logits) 39 | boundary_pre = boundary_pre / (boundary_pre + 0.01) 40 | # print(boundary_pre) 41 | boundary_pre = boundary_pre.view(bs, 1, -1) 42 | # print(boundary_pre) 43 | # dice_loss = 1 - ((2. * (boundary_pre * boundary_targets).sum(1) + 1.0) / 44 | # (boundary_pre.sum(1) + boundary_targets.sum(1) + 1.0)) 45 | # dice_loss = dice_loss.mean() 46 | edge_loss = F.binary_cross_entropy_with_logits(boundary_pre, boundary_targets) 47 | 48 | return edge_loss 49 | 50 | def forward(self, logits, targets): 51 | loss = (self.main_loss(logits, targets) + self.compute_edge_loss(logits, targets) * self.edge_factor) / (self.edge_factor+1) 52 | return loss 53 | 54 | 55 | class OHEM_CELoss(nn.Module): 56 | 57 | def __init__(self, thresh=0.7, ignore_index=255): 58 | super(OHEM_CELoss, self).__init__() 59 | self.thresh = -torch.log(torch.tensor(thresh, requires_grad=False, dtype=torch.float)).cuda() 60 | self.ignore_index = ignore_index 61 | self.criteria = nn.CrossEntropyLoss(ignore_index=ignore_index, reduction='none') 62 | 63 | def forward(self, logits, labels): 64 | n_min = labels[labels != self.ignore_index].numel() // 16 65 | loss = self.criteria(logits, labels).view(-1) 66 | loss_hard = loss[loss > self.thresh] 67 | if loss_hard.numel() < n_min: 68 | loss_hard, _ = loss.topk(n_min) 69 | return torch.mean(loss_hard) 70 | 71 | 72 | class UnetFormerLoss(nn.Module): 73 | 74 | def __init__(self, ignore_index=255): 75 | super().__init__() 76 | self.main_loss = JointLoss(SoftCrossEntropyLoss(smooth_factor=0.05, ignore_index=ignore_index), 77 | DiceLoss(smooth=0.05, ignore_index=ignore_index), 1.0, 1.0) 78 | self.aux_loss = SoftCrossEntropyLoss(smooth_factor=0.05, ignore_index=ignore_index) 79 | 80 | def forward(self, logits, labels): 81 | if self.training and len(logits) == 2: 82 | logit_main, logit_aux = logits 83 | loss = self.main_loss(logit_main, labels) + 0.4 * self.aux_loss(logit_aux, labels) 84 | else: 85 | loss = self.main_loss(logits, labels) 86 | 87 | return loss 88 | 89 | 90 | 91 | from .dice import WeightedBoundaryDiceLoss 92 | 93 | class DeltaLoss(nn.Module): 94 | 95 | def __init__(self, ignore_index=255): 96 | super().__init__() 97 | self.main_loss = JointLoss(SoftCrossEntropyLoss(smooth_factor=0.05, ignore_index=ignore_index), 98 | WeightedBoundaryDiceLoss(smooth=0.05, ignore_index=ignore_index), 1.0, 1.0) 99 | self.aux_loss = SoftCrossEntropyLoss(smooth_factor=0.05, ignore_index=ignore_index) 100 | 101 | def forward(self, logits, labels): 102 | if self.training and len(logits) == 2: 103 | logit_main, logit_aux = logits 104 | loss = self.main_loss(logit_main, labels) + 0.4 * self.aux_loss(logit_aux, labels) 105 | else: 106 | loss = self.main_loss(logits, labels) 107 | 108 | return loss 109 | 110 | 111 | 112 | if __name__ == '__main__': 113 | targets = torch.randint(low=0, high=2, size=(2, 16, 16)) 114 | logits = torch.randn((2, 2, 16, 16)) 115 | # print(targets) 116 | model = EdgeLoss() 117 | loss = model.compute_edge_loss(logits, targets) 118 | 119 | print(loss) -------------------------------------------------------------------------------- /test_vaihingen.py: -------------------------------------------------------------------------------- 1 | import ttach as tta 2 | import multiprocessing.pool as mpp 3 | import multiprocessing as mp 4 | import time 5 | from train import * 6 | import argparse 7 | from pathlib import Path 8 | import cv2 9 | import numpy as np 10 | import torch 11 | 12 | from torch import nn 13 | from torch.utils.data import DataLoader 14 | from tqdm import tqdm 15 | 16 | 17 | def seed_everything(seed): 18 | random.seed(seed) 19 | os.environ['PYTHONHASHSEED'] = str(seed) 20 | np.random.seed(seed) 21 | torch.manual_seed(seed) 22 | torch.cuda.manual_seed(seed) 23 | torch.backends.cudnn.deterministic = True 24 | torch.backends.cudnn.benchmark = True 25 | 26 | 27 | def label2rgb(mask): 28 | h, w = mask.shape[0], mask.shape[1] 29 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 30 | mask_convert = mask[np.newaxis, :, :] 31 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [0, 255, 0] 32 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 33 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 34 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [255, 255, 0] 35 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [0, 204, 255] 36 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [0, 0, 255] 37 | return mask_rgb 38 | 39 | 40 | def img_writer(inp): 41 | (mask, mask_id, rgb) = inp 42 | if rgb: 43 | mask_name_tif = mask_id + '.png' 44 | mask_tif = label2rgb(mask) 45 | cv2.imwrite(mask_name_tif, mask_tif) 46 | else: 47 | mask_png = mask.astype(np.uint8) 48 | mask_name_png = mask_id + '.png' 49 | cv2.imwrite(mask_name_png, mask_png) 50 | 51 | 52 | def get_args(): 53 | parser = argparse.ArgumentParser() 54 | arg = parser.add_argument 55 | arg("-c", "--config_path", type=Path, required=True, help="Path to config") 56 | arg("-o", "--output_path", type=Path, help="Path where to save resulting masks.", required=True) 57 | arg("-t", "--tta", help="Test time augmentation.", default=None, choices=[None, "d4", "lr"]) 58 | arg("--rgb", help="whether output rgb images", action='store_true') 59 | return parser.parse_args() 60 | 61 | 62 | def main(): 63 | seed_everything(42) 64 | args = get_args() 65 | config = py2cfg(args.config_path) 66 | args.output_path.mkdir(exist_ok=True, parents=True) 67 | model = Supervision_Train.load_from_checkpoint(os.path.join(config.weights_path, config.test_weights_name+'.ckpt'), config=config) 68 | model.cuda() 69 | model.eval() 70 | evaluator = Evaluator(num_class=config.num_classes) 71 | evaluator.reset() 72 | if args.tta == "lr": 73 | transforms = tta.Compose( 74 | [ 75 | tta.HorizontalFlip(), 76 | tta.VerticalFlip() 77 | ] 78 | ) 79 | model = tta.SegmentationTTAWrapper(model, transforms) 80 | elif args.tta == "d4": 81 | transforms = tta.Compose( 82 | [ 83 | tta.HorizontalFlip(), 84 | tta.VerticalFlip(), 85 | tta.Rotate90(angles=[90]), 86 | tta.Scale(scales=[0.5, 0.75, 1.0, 1.25, 1.5], interpolation='bicubic', align_corners=False) 87 | ] 88 | ) 89 | model = tta.SegmentationTTAWrapper(model, transforms) 90 | 91 | test_dataset = config.test_dataset 92 | 93 | with torch.no_grad(): 94 | test_loader = DataLoader( 95 | test_dataset, 96 | batch_size=2, 97 | num_workers=4, 98 | pin_memory=True, 99 | drop_last=False, 100 | ) 101 | results = [] 102 | for input in tqdm(test_loader): 103 | # raw_prediction NxCxHxW 104 | raw_predictions = model(input['img'].cuda()) 105 | 106 | image_ids = input["img_id"] 107 | masks_true = input['gt_semantic_seg'] 108 | 109 | raw_predictions = nn.Softmax(dim=1)(raw_predictions) 110 | predictions = raw_predictions.argmax(dim=1) 111 | 112 | for i in range(raw_predictions.shape[0]): 113 | mask = predictions[i].cpu().numpy() 114 | evaluator.add_batch(pre_image=mask, gt_image=masks_true[i].cpu().numpy()) 115 | mask_name = image_ids[i] 116 | results.append((mask, str(args.output_path / mask_name), args.rgb)) 117 | 118 | iou_per_class = evaluator.Intersection_over_Union() 119 | f1_per_class = evaluator.F1() 120 | OA = evaluator.OA() 121 | for class_name, class_iou, class_f1 in zip(config.classes, iou_per_class, f1_per_class): 122 | print('F1_{}:{}, IOU_{}:{}'.format(class_name, class_f1, class_name, class_iou)) 123 | print('F1:{}, mIOU:{}, OA:{}'.format(np.nanmean(f1_per_class[:-1]), np.nanmean(iou_per_class[:-1]), OA)) 124 | t0 = time.time() 125 | mpp.Pool(processes=mp.cpu_count()).map(img_writer, results) 126 | t1 = time.time() 127 | img_write_time = t1 - t0 128 | print('images writing spends: {} s'.format(img_write_time)) 129 | 130 | 131 | if __name__ == "__main__": 132 | main() 133 | -------------------------------------------------------------------------------- /test_potsdam.py: -------------------------------------------------------------------------------- 1 | import ttach as tta 2 | import ttach as tta 3 | import multiprocessing.pool as mpp 4 | import multiprocessing as mp 5 | import time 6 | from train import * 7 | import argparse 8 | from pathlib import Path 9 | import cv2 10 | import numpy as np 11 | import torch 12 | 13 | from torch import nn 14 | from torch.utils.data import DataLoader 15 | from tqdm import tqdm 16 | 17 | 18 | def seed_everything(seed): 19 | random.seed(seed) 20 | os.environ['PYTHONHASHSEED'] = str(seed) 21 | np.random.seed(seed) 22 | torch.manual_seed(seed) 23 | torch.cuda.manual_seed(seed) 24 | torch.backends.cudnn.deterministic = True 25 | torch.backends.cudnn.benchmark = True 26 | 27 | 28 | def label2rgb(mask): 29 | h, w = mask.shape[0], mask.shape[1] 30 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 31 | mask_convert = mask[np.newaxis, :, :] 32 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [0, 255, 0] 33 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 34 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 35 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [255, 255, 0] 36 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [0, 204, 255] 37 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [0, 0, 255] 38 | return mask_rgb 39 | 40 | 41 | def img_writer(inp): 42 | (mask, mask_id, rgb) = inp 43 | if rgb: 44 | mask_name_tif = mask_id + '.png' 45 | mask_tif = label2rgb(mask) 46 | cv2.imwrite(mask_name_tif, mask_tif) 47 | else: 48 | mask_png = mask.astype(np.uint8) 49 | mask_name_png = mask_id + '.png' 50 | cv2.imwrite(mask_name_png, mask_png) 51 | 52 | 53 | def get_args(): 54 | parser = argparse.ArgumentParser() 55 | arg = parser.add_argument 56 | arg("-c", "--config_path", type=Path, required=True, help="Path to config") 57 | arg("-o", "--output_path", type=Path, help="Path where to save resulting masks.", required=True) 58 | arg("-t", "--tta", help="Test time augmentation.", default=None, choices=[None, "d4", "lr"]) 59 | arg("--rgb", help="whether output rgb images", action='store_true') 60 | return parser.parse_args() 61 | 62 | 63 | def main(): 64 | args = get_args() 65 | seed_everything(42) 66 | 67 | config = py2cfg(args.config_path) 68 | args.output_path.mkdir(exist_ok=True, parents=True) 69 | 70 | model = Supervision_Train.load_from_checkpoint( 71 | os.path.join(config.weights_path, config.test_weights_name + '.ckpt'), config=config) 72 | model.cuda() 73 | model.eval() 74 | evaluator = Evaluator(num_class=config.num_classes) 75 | evaluator.reset() 76 | if args.tta == "lr": 77 | transforms = tta.Compose( 78 | [ 79 | tta.HorizontalFlip(), 80 | tta.VerticalFlip() 81 | ] 82 | ) 83 | model = tta.SegmentationTTAWrapper(model, transforms) 84 | elif args.tta == "d4": 85 | transforms = tta.Compose( 86 | [ 87 | tta.HorizontalFlip(), 88 | tta.VerticalFlip(), 89 | # tta.Rotate90(angles=[90]), 90 | tta.Scale(scales=[0.75, 1.0, 1.25, 1.5], interpolation='bicubic', align_corners=False) 91 | ] 92 | ) 93 | model = tta.SegmentationTTAWrapper(model, transforms) 94 | 95 | test_dataset = config.test_dataset 96 | 97 | with torch.no_grad(): 98 | test_loader = DataLoader( 99 | test_dataset, 100 | batch_size=2, 101 | num_workers=4, 102 | pin_memory=True, 103 | drop_last=False, 104 | ) 105 | results = [] 106 | for input in tqdm(test_loader): 107 | # raw_prediction NxCxHxW 108 | raw_predictions = model(input['img'].cuda()) 109 | 110 | image_ids = input["img_id"] 111 | masks_true = input['gt_semantic_seg'] 112 | 113 | raw_predictions = nn.Softmax(dim=1)(raw_predictions) 114 | predictions = raw_predictions.argmax(dim=1) 115 | 116 | for i in range(raw_predictions.shape[0]): 117 | mask = predictions[i].cpu().numpy() 118 | evaluator.add_batch(pre_image=mask, gt_image=masks_true[i].cpu().numpy()) 119 | mask_name = image_ids[i] 120 | results.append((mask, str(args.output_path / mask_name), args.rgb)) 121 | iou_per_class = evaluator.Intersection_over_Union() 122 | f1_per_class = evaluator.F1() 123 | OA = evaluator.OA() 124 | for class_name, class_iou, class_f1 in zip(config.classes, iou_per_class, f1_per_class): 125 | print('F1_{}:{}, IOU_{}:{}'.format(class_name, class_f1, class_name, class_iou)) 126 | print('F1:{}, mIOU:{}, OA:{}'.format(np.nanmean(f1_per_class[:-1]), np.nanmean(iou_per_class[:-1]), OA)) 127 | t0 = time.time() 128 | mpp.Pool(processes=mp.cpu_count()).map(img_writer, results) 129 | t1 = time.time() 130 | img_write_time = t1 - t0 131 | print('images writing spends: {} s'.format(img_write_time)) 132 | 133 | 134 | if __name__ == "__main__": 135 | main() 136 | -------------------------------------------------------------------------------- /test_loveda.py: -------------------------------------------------------------------------------- 1 | import ttach as tta 2 | import multiprocessing.pool as mpp 3 | import multiprocessing as mp 4 | import time 5 | from train import * 6 | import argparse 7 | from pathlib import Path 8 | import cv2 9 | import numpy as np 10 | import torch 11 | 12 | from torch import nn 13 | from torch.utils.data import DataLoader 14 | from tqdm import tqdm 15 | 16 | 17 | def label2rgb(mask): 18 | h, w = mask.shape[0], mask.shape[1] 19 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 20 | mask_convert = mask[np.newaxis, :, :] 21 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 22 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 23 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [255, 255, 0] 24 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [0, 0, 255] 25 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [159, 129, 183] 26 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [0, 255, 0] 27 | mask_rgb[np.all(mask_convert == 6, axis=0)] = [255, 195, 128] 28 | return mask_rgb 29 | 30 | 31 | def img_writer(inp): 32 | (mask, mask_id, rgb) = inp 33 | if rgb: 34 | mask_name_tif = mask_id + '.png' 35 | mask_tif = label2rgb(mask) 36 | mask_tif = cv2.cvtColor(mask_tif, cv2.COLOR_RGB2BGR) 37 | cv2.imwrite(mask_name_tif, mask_tif) 38 | else: 39 | mask_png = mask.astype(np.uint8) 40 | mask_name_png = mask_id + '.png' 41 | cv2.imwrite(mask_name_png, mask_png) 42 | 43 | 44 | def get_args(): 45 | parser = argparse.ArgumentParser() 46 | arg = parser.add_argument 47 | arg("-c", "--config_path", type=Path, required=True, help="Path to config") 48 | arg("-o", "--output_path", type=Path, help="Path where to save resulting masks.", required=True) 49 | arg("-t", "--tta", help="Test time augmentation.", default=None, choices=[None, "d4", "lr"]) ## lr is flip TTA, d4 is multi-scale TTA 50 | arg("--rgb", help="whether output rgb masks", action='store_true') 51 | arg("--val", help="whether eval validation set", action='store_true') 52 | return parser.parse_args() 53 | 54 | 55 | def main(): 56 | args = get_args() 57 | config = py2cfg(args.config_path) 58 | args.output_path.mkdir(exist_ok=True, parents=True) 59 | 60 | model = Supervision_Train.load_from_checkpoint(os.path.join(config.weights_path, config.test_weights_name+'.ckpt'), config=config, map_location=f"cuda:{config.gpus[0]}") 61 | model = model.to(f'cuda:{config.gpus[0]}') 62 | model.eval() 63 | if args.tta == "lr": 64 | transforms = tta.Compose( 65 | [ 66 | tta.HorizontalFlip(), 67 | tta.VerticalFlip() 68 | ] 69 | ) 70 | model = tta.SegmentationTTAWrapper(model, transforms) 71 | elif args.tta == "d4": 72 | transforms = tta.Compose( 73 | [ 74 | tta.HorizontalFlip(), 75 | # tta.VerticalFlip(), 76 | # tta.Rotate90(angles=[0, 90, 180, 270]), 77 | tta.Scale(scales=[0.75, 1.0, 1.25, 1.5], interpolation='bicubic', align_corners=False), 78 | # tta.Multiply(factors=[0.8, 1, 1.2]) 79 | ] 80 | ) 81 | model = tta.SegmentationTTAWrapper(model, transforms) 82 | 83 | test_dataset = config.test_dataset 84 | if args.val: 85 | evaluator = Evaluator(num_class=config.num_classes) 86 | evaluator.reset() 87 | test_dataset = config.val_dataset 88 | 89 | with torch.no_grad(): 90 | test_loader = DataLoader( 91 | test_dataset, 92 | batch_size=4, 93 | num_workers=4, 94 | pin_memory=True, 95 | drop_last=False, 96 | ) 97 | results = [] 98 | for input in tqdm(test_loader): 99 | # raw_prediction NxCxHxW 100 | raw_predictions = model(input['img'].to(f'cuda:{config.gpus[0]}')) 101 | 102 | image_ids = input["img_id"] 103 | if args.val: 104 | masks_true = input['gt_semantic_seg'] 105 | 106 | img_type = input['img_type'] 107 | 108 | raw_predictions = nn.Softmax(dim=1)(raw_predictions) 109 | predictions = raw_predictions.argmax(dim=1) 110 | 111 | for i in range(raw_predictions.shape[0]): 112 | mask = predictions[i].cpu().numpy() 113 | mask_name = image_ids[i] 114 | mask_type = img_type[i] 115 | if args.val: 116 | if not os.path.exists(os.path.join(args.output_path, mask_type)): 117 | os.mkdir(os.path.join(args.output_path, mask_type)) 118 | evaluator.add_batch(pre_image=mask, gt_image=masks_true[i].cpu().numpy()) 119 | results.append((mask, str(args.output_path / mask_type / mask_name), args.rgb)) 120 | else: 121 | results.append((mask, str(args.output_path / mask_name), args.rgb)) 122 | if args.val: 123 | iou_per_class = evaluator.Intersection_over_Union() 124 | f1_per_class = evaluator.F1() 125 | OA = evaluator.OA() 126 | for class_name, class_iou, class_f1 in zip(config.classes, iou_per_class, f1_per_class): 127 | print('F1_{}:{}, IOU_{}:{}'.format(class_name, class_f1, class_name, class_iou)) 128 | print('F1:{}, mIOU:{}, OA:{}'.format(np.nanmean(f1_per_class), np.nanmean(iou_per_class), OA)) 129 | 130 | t0 = time.time() 131 | mpp.Pool(processes=mp.cpu_count()).map(img_writer, results) 132 | t1 = time.time() 133 | img_write_time = t1 - t0 134 | print('images writing spends: {} s'.format(img_write_time)) 135 | 136 | 137 | if __name__ == "__main__": 138 | main() 139 | -------------------------------------------------------------------------------- /network/losses/cel1.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import logging 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from typing import Optional 6 | 7 | BINARY_MODE: str = "binary" 8 | 9 | MULTICLASS_MODE: str = "multiclass" 10 | 11 | MULTILABEL_MODE: str = "multilabel" 12 | 13 | 14 | EPS = 1e-10 15 | 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | def expand_onehot_labels(labels, target_shape, ignore_index): 21 | """Expand onehot labels to match the size of prediction.""" 22 | bin_labels = labels.new_zeros(target_shape) 23 | valid_mask = (labels >= 0) & (labels != ignore_index) 24 | inds = torch.nonzero(valid_mask, as_tuple=True) 25 | 26 | if inds[0].numel() > 0: 27 | if labels.dim() == 3: 28 | bin_labels[inds[0], labels[valid_mask], inds[1], inds[2]] = 1 29 | else: 30 | bin_labels[inds[0], labels[valid_mask]] = 1 31 | 32 | return bin_labels, valid_mask 33 | 34 | 35 | def get_region_proportion(x: torch.Tensor, valid_mask: torch.Tensor = None) -> torch.Tensor: 36 | """Get region proportion 37 | Args: 38 | x : one-hot label map/mask 39 | valid_mask : indicate the considered elements 40 | """ 41 | if valid_mask is not None: 42 | if valid_mask.dim() == 4: 43 | x = torch.einsum("bcwh, bcwh->bcwh", x, valid_mask) 44 | cardinality = torch.einsum("bcwh->bc", valid_mask) 45 | else: 46 | x = torch.einsum("bcwh,bwh->bcwh", x, valid_mask) 47 | cardinality = torch.einsum("bwh->b", valid_mask).unsqueeze(dim=1).repeat(1, x.shape[1]) 48 | else: 49 | cardinality = x.shape[2] * x.shape[3] 50 | 51 | region_proportion = (torch.einsum("bcwh->bc", x) + EPS) / (cardinality + EPS) 52 | 53 | return region_proportion 54 | 55 | 56 | class CompoundLoss(nn.Module): 57 | """ 58 | The base class for implementing a compound loss: 59 | l = l_1 + alpha * l_2 60 | """ 61 | def __init__(self, mode: str = MULTICLASS_MODE, 62 | alpha: float = 0.1, 63 | factor: float = 5., 64 | step_size: int = 0, 65 | max_alpha: float = 100., 66 | temp: float = 1., 67 | ignore_index: int = 255, 68 | background_index: int = -1, 69 | weight: Optional[torch.Tensor] = None) -> None: 70 | assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE} 71 | super().__init__() 72 | self.mode = mode 73 | self.alpha = alpha 74 | self.max_alpha = max_alpha 75 | self.factor = factor 76 | self.step_size = step_size 77 | self.temp = temp 78 | self.ignore_index = ignore_index 79 | self.background_index = background_index 80 | self.weight = weight 81 | 82 | def cross_entropy(self, inputs: torch.Tensor, labels: torch.Tensor): 83 | if self.mode == MULTICLASS_MODE: 84 | loss = F.cross_entropy( 85 | inputs, labels, weight=self.weight, ignore_index=self.ignore_index) 86 | else: 87 | if labels.dim() == 3: 88 | labels = labels.unsqueeze(dim=1) 89 | loss = F.binary_cross_entropy_with_logits(inputs, labels.type(torch.float32)) 90 | return loss 91 | 92 | def adjust_alpha(self, epoch: int) -> None: 93 | if self.step_size == 0: 94 | return 95 | if (epoch + 1) % self.step_size == 0: 96 | curr_alpha = self.alpha 97 | self.alpha = min(self.alpha * self.factor, self.max_alpha) 98 | logger.info( 99 | "CompoundLoss : Adjust the tradoff param alpha : {:.3g} -> {:.3g}".format(curr_alpha, self.alpha) 100 | ) 101 | 102 | def get_gt_proportion(self, mode: str, 103 | labels: torch.Tensor, 104 | target_shape, 105 | ignore_index: int = 255): 106 | if mode == MULTICLASS_MODE: 107 | bin_labels, valid_mask = expand_onehot_labels(labels, target_shape, ignore_index) 108 | else: 109 | valid_mask = (labels >= 0) & (labels != ignore_index) 110 | if labels.dim() == 3: 111 | labels = labels.unsqueeze(dim=1) 112 | bin_labels = labels 113 | gt_proportion = get_region_proportion(bin_labels, valid_mask) 114 | return gt_proportion, valid_mask 115 | 116 | def get_pred_proportion(self, mode: str, 117 | logits: torch.Tensor, 118 | temp: float = 1.0, 119 | valid_mask=None): 120 | if mode == MULTICLASS_MODE: 121 | preds = F.log_softmax(temp * logits, dim=1).exp() 122 | else: 123 | preds = F.logsigmoid(temp * logits).exp() 124 | pred_proportion = get_region_proportion(preds, valid_mask) 125 | return pred_proportion 126 | 127 | 128 | class CrossEntropyWithL1(CompoundLoss): 129 | """ 130 | Cross entropy loss with region size priors measured by l1. 131 | The loss can be described as: 132 | l = CE(X, Y) + alpha * |gt_region - prob_region| 133 | """ 134 | def forward(self, inputs: torch.Tensor, labels: torch.Tensor): 135 | # ce term 136 | loss_ce = self.cross_entropy(inputs, labels) 137 | # regularization 138 | gt_proportion, valid_mask = self.get_gt_proportion(self.mode, labels, inputs.shape) 139 | pred_proportion = self.get_pred_proportion(self.mode, inputs, temp=self.temp, valid_mask=valid_mask) 140 | loss_reg = (pred_proportion - gt_proportion).abs().mean() 141 | 142 | loss = loss_ce + self.alpha * loss_reg 143 | 144 | return loss 145 | 146 | 147 | class CrossEntropyWithKL(CompoundLoss): 148 | """ 149 | Cross entropy loss with region size priors measured by l1. 150 | The loss can be described as: 151 | l = CE(X, Y) + alpha * KL(gt_region || prob_region) 152 | """ 153 | def kl_div(self, p : torch.Tensor, q : torch.Tensor) -> torch.Tensor: 154 | x = p * torch.log(p / q) 155 | x = torch.einsum("ij->i", x) 156 | return x 157 | 158 | def forward(self, inputs: torch.Tensor, labels: torch.Tensor): 159 | # ce term 160 | loss_ce = self.cross_entropy(inputs, labels) 161 | # regularization 162 | gt_proportion, valid_mask = self.get_gt_proportion(self.mode, labels, inputs.shape) 163 | pred_proportion = self.get_pred_proportion(self.mode, inputs, temp=self.temp, valid_mask=valid_mask) 164 | 165 | if self.mode == BINARY_MODE: 166 | regularizer = ( 167 | self.kl_div(gt_proportion, pred_proportion) 168 | + self.kl_div(1 - gt_proportion, 1 - pred_proportion) 169 | ).mean() 170 | else: 171 | regularizer = self.kl_div(gt_proportion, pred_proportion).mean() 172 | 173 | loss = loss_ce + self.alpha * regularizer 174 | 175 | return loss -------------------------------------------------------------------------------- /network/datasets/potsdam_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | import torch 5 | from torch.utils.data import Dataset 6 | import cv2 7 | import matplotlib.pyplot as plt 8 | import albumentations as albu 9 | from .transform import * 10 | import matplotlib.patches as mpatches 11 | from PIL import Image 12 | import random 13 | 14 | 15 | CLASSES = ('ImSurf', 'Building', 'LowVeg', 'Tree', 'Car', 'Clutter') 16 | PALETTE = [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], [255, 204, 0], [255, 0, 0]] 17 | 18 | ORIGIN_IMG_SIZE = (1024, 1024) 19 | INPUT_IMG_SIZE = (1024, 1024) 20 | TEST_IMG_SIZE = (1024, 1024) 21 | 22 | def get_training_transform(): 23 | train_transform = [ 24 | albu.RandomRotate90(p=0.25), 25 | albu.HorizontalFlip(p=0.5), 26 | albu.VerticalFlip(p=0.5), 27 | albu.Normalize() 28 | ] 29 | return albu.Compose(train_transform) 30 | 31 | 32 | def train_aug(img, mask): 33 | crop_aug = Compose([RandomScale(scale_list=[0.75, 1.0, 1.25, 1.5], mode='value'), 34 | SmartCropV1(crop_size=768, max_ratio=0.75, ignore_index=len(CLASSES), nopad=False)]) 35 | img, mask = crop_aug(img, mask) 36 | img, mask = np.array(img), np.array(mask) 37 | aug = get_training_transform()(image=img.copy(), mask=mask.copy()) 38 | img, mask = aug['image'], aug['mask'] 39 | return img, mask 40 | 41 | 42 | def get_val_transform(): 43 | val_transform = [ 44 | albu.Normalize() 45 | ] 46 | return albu.Compose(val_transform) 47 | 48 | 49 | def val_aug(img, mask): 50 | img, mask = np.array(img), np.array(mask) 51 | aug = get_val_transform()(image=img.copy(), mask=mask.copy()) 52 | img, mask = aug['image'], aug['mask'] 53 | return img, mask 54 | 55 | 56 | def get_test_transform(): 57 | test_transform = [ 58 | albu.Normalize() 59 | ] 60 | return albu.Compose(test_transform) 61 | 62 | 63 | def test_aug(img, mask): 64 | img, mask = np.array(img), np.array(mask) 65 | aug = get_test_transform()(image=img.copy(), mask=mask.copy()) 66 | img, mask = aug['image'], aug['mask'] 67 | return img, mask 68 | 69 | 70 | class PotsdamDataset(Dataset): 71 | def __init__(self, data_root='data/potsdam/test', mode='val', img_dir='images_1024', mask_dir='masks_1024', 72 | img_suffix='.tif', mask_suffix='.png', transform=test_aug, mosaic_ratio=0.0, 73 | img_size=ORIGIN_IMG_SIZE): 74 | self.data_root = data_root 75 | self.img_dir = img_dir 76 | self.mask_dir = mask_dir 77 | self.img_suffix = img_suffix 78 | self.mask_suffix = mask_suffix 79 | self.transform = transform 80 | self.mode = mode 81 | self.mosaic_ratio = mosaic_ratio 82 | self.img_size = img_size 83 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 84 | 85 | def __getitem__(self, index): 86 | p_ratio = random.random() 87 | if p_ratio > self.mosaic_ratio or self.mode == 'val' or self.mode == 'test': 88 | img, mask = self.load_img_and_mask(index) 89 | if self.transform: 90 | img, mask = self.transform(img, mask) 91 | else: 92 | img, mask = self.load_mosaic_img_and_mask(index) 93 | if self.transform: 94 | img, mask = self.transform(img, mask) 95 | 96 | img = torch.from_numpy(img).permute(2, 0, 1).float() 97 | mask = torch.from_numpy(mask).long() 98 | img_id = self.img_ids[index] 99 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 100 | return results 101 | 102 | def __len__(self): 103 | return len(self.img_ids) 104 | 105 | def get_img_ids(self, data_root, img_dir, mask_dir): 106 | img_filename_list = os.listdir(osp.join(data_root, img_dir)) 107 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir)) 108 | assert len(img_filename_list) == len(mask_filename_list) 109 | img_ids = [str(id.split('.')[0]) for id in mask_filename_list] 110 | return img_ids 111 | 112 | def load_img_and_mask(self, index): 113 | img_id = self.img_ids[index] 114 | img_name = osp.join(self.data_root, self.img_dir, img_id + self.img_suffix) 115 | mask_name = osp.join(self.data_root, self.mask_dir, img_id + self.mask_suffix) 116 | img = Image.open(img_name).convert('RGB') 117 | mask = Image.open(mask_name).convert('L') 118 | return img, mask 119 | 120 | def load_mosaic_img_and_mask(self, index): 121 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 122 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 123 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 124 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 125 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 126 | 127 | img_a, mask_a = np.array(img_a), np.array(mask_a) 128 | img_b, mask_b = np.array(img_b), np.array(mask_b) 129 | img_c, mask_c = np.array(img_c), np.array(mask_c) 130 | img_d, mask_d = np.array(img_d), np.array(mask_d) 131 | 132 | w = self.img_size[1] 133 | h = self.img_size[0] 134 | 135 | start_x = w // 4 136 | strat_y = h // 4 137 | # The coordinates of the splice center 138 | offset_x = random.randint(start_x, (w - start_x)) 139 | offset_y = random.randint(strat_y, (h - strat_y)) 140 | 141 | crop_size_a = (offset_x, offset_y) 142 | crop_size_b = (w - offset_x, offset_y) 143 | crop_size_c = (offset_x, h - offset_y) 144 | crop_size_d = (w - offset_x, h - offset_y) 145 | 146 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 147 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 148 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 149 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 150 | 151 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 152 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 153 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 154 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 155 | 156 | img_crop_a, mask_crop_a = croped_a['image'], croped_a['mask'] 157 | img_crop_b, mask_crop_b = croped_b['image'], croped_b['mask'] 158 | img_crop_c, mask_crop_c = croped_c['image'], croped_c['mask'] 159 | img_crop_d, mask_crop_d = croped_d['image'], croped_d['mask'] 160 | 161 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 162 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 163 | img = np.concatenate((top, bottom), axis=0) 164 | 165 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 166 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 167 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 168 | mask = np.ascontiguousarray(mask) 169 | img = np.ascontiguousarray(img) 170 | 171 | img = Image.fromarray(img) 172 | mask = Image.fromarray(mask) 173 | 174 | return img, mask 175 | -------------------------------------------------------------------------------- /network/datasets/cloud_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | import torch 5 | from torch.utils.data import Dataset 6 | import albumentations as albu 7 | from .transform import * 8 | from PIL import Image 9 | import random 10 | 11 | 12 | CLASSES = ("Clear", "Cloud Shadow", "Thin Cloud", "Cloud") 13 | PALETTE = [ 14 | [79, 253, 199], 15 | [221, 53, 223], 16 | [251, 255, 41], 17 | [77, 2, 115], 18 | ] 19 | 20 | ORIGIN_IMG_SIZE = (512, 512) 21 | INPUT_IMG_SIZE = (512, 512) 22 | TEST_IMG_SIZE = (512, 512) 23 | 24 | 25 | def get_training_transform(): 26 | train_transform = [ 27 | albu.HorizontalFlip(p=0.5), 28 | albu.VerticalFlip(p=0.5), 29 | albu.RandomBrightnessContrast( 30 | brightness_limit=0.25, contrast_limit=0.25, p=0.25 31 | ), 32 | albu.Sharpen(), 33 | albu.Normalize(), 34 | ] 35 | return albu.Compose(train_transform) 36 | 37 | 38 | def train_aug(img, mask): 39 | # crop_aug = SmartCropV1(crop_size=768, max_ratio=0.75, ignore_index=255, nopad=False) 40 | # label, mask = crop_aug(label, mask) 41 | img, mask = np.array(img), np.array(mask) 42 | aug = get_training_transform()(image=img.copy(), mask=mask.copy()) 43 | img, mask = aug["image"], aug["mask"] 44 | return img, mask 45 | 46 | 47 | def get_val_transform(): 48 | val_transform = [albu.Normalize()] 49 | return albu.Compose(val_transform) 50 | 51 | 52 | def val_aug(img, mask): 53 | img, mask = np.array(img), np.array(mask) 54 | aug = get_val_transform()(image=img.copy(), mask=mask.copy()) 55 | img, mask = aug["image"], aug["mask"] 56 | return img, mask 57 | 58 | 59 | def get_test_transform(): 60 | test_transform = [albu.Normalize()] 61 | return albu.Compose(test_transform) 62 | 63 | 64 | def test_aug(img, mask): 65 | img, mask = np.array(img), np.array(mask) 66 | aug = get_test_transform()(image=img.copy(), mask=mask.copy()) 67 | img, mask = aug["image"], aug["mask"] 68 | return img, mask 69 | 70 | 71 | class CloudDataset(Dataset): 72 | def __init__( 73 | self, 74 | data_root="data/grass", 75 | mode="train", 76 | img_dir="img_dir", 77 | mask_dir="ann_dir", 78 | img_suffix=".png", 79 | mask_suffix=".png", 80 | transform=test_aug, 81 | mosaic_ratio=0.0, 82 | img_size=ORIGIN_IMG_SIZE, 83 | ): 84 | self.data_root = data_root 85 | self.img_dir = img_dir 86 | self.mask_dir = mask_dir 87 | self.img_suffix = img_suffix 88 | self.mask_suffix = mask_suffix 89 | self.transform = transform 90 | self.mode = mode 91 | self.mosaic_ratio = mosaic_ratio 92 | self.img_size = img_size 93 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 94 | 95 | def __getitem__(self, index): 96 | p_ratio = random.random() 97 | if p_ratio > self.mosaic_ratio or self.mode == "val": 98 | img, mask = self.load_img_and_mask(index) 99 | if self.transform: 100 | img, mask = self.transform(img, mask) 101 | else: 102 | img, mask = self.load_mosaic_img_and_mask(index) 103 | if self.transform: 104 | img, mask = self.transform(img, mask) 105 | 106 | img = torch.from_numpy(img).permute(2, 0, 1).float() 107 | mask = torch.from_numpy(mask).long() 108 | img_id = self.img_ids[index] 109 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 110 | return results 111 | 112 | def __len__(self): 113 | return len(self.img_ids) 114 | 115 | def get_img_ids(self, data_root, img_dir, mask_dir): 116 | img_filename_list = os.listdir(osp.join(data_root, img_dir, self.mode)) 117 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir, self.mode)) 118 | assert len(img_filename_list) == len(mask_filename_list) 119 | img_ids = [str(id.split(".")[0]) for id in mask_filename_list] 120 | return img_ids 121 | 122 | def load_img_and_mask(self, index): 123 | img_id = self.img_ids[index] 124 | img_name = osp.join( 125 | self.data_root, self.img_dir, self.mode, img_id + self.img_suffix 126 | ) 127 | mask_name = osp.join( 128 | self.data_root, self.mask_dir, self.mode, img_id + self.mask_suffix 129 | ) 130 | img = Image.open(img_name).convert("RGB") 131 | mask = Image.open(mask_name) 132 | return img, mask 133 | 134 | def load_mosaic_img_and_mask(self, index): 135 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 136 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 137 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 138 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 139 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 140 | 141 | img_a, mask_a = np.array(img_a), np.array(mask_a) 142 | img_b, mask_b = np.array(img_b), np.array(mask_b) 143 | img_c, mask_c = np.array(img_c), np.array(mask_c) 144 | img_d, mask_d = np.array(img_d), np.array(mask_d) 145 | 146 | w = self.img_size[1] 147 | h = self.img_size[0] 148 | 149 | start_x = w // 4 150 | strat_y = h // 4 151 | # The coordinates of the splice center 152 | offset_x = random.randint(start_x, (w - start_x)) 153 | offset_y = random.randint(strat_y, (h - strat_y)) 154 | 155 | crop_size_a = (offset_x, offset_y) 156 | crop_size_b = (w - offset_x, offset_y) 157 | crop_size_c = (offset_x, h - offset_y) 158 | crop_size_d = (w - offset_x, h - offset_y) 159 | 160 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 161 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 162 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 163 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 164 | 165 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 166 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 167 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 168 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 169 | 170 | img_crop_a, mask_crop_a = croped_a["image"], croped_a["mask"] 171 | img_crop_b, mask_crop_b = croped_b["image"], croped_b["mask"] 172 | img_crop_c, mask_crop_c = croped_c["image"], croped_c["mask"] 173 | img_crop_d, mask_crop_d = croped_d["image"], croped_d["mask"] 174 | 175 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 176 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 177 | img = np.concatenate((top, bottom), axis=0) 178 | 179 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 180 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 181 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 182 | mask = np.ascontiguousarray(mask) 183 | img = np.ascontiguousarray(img) 184 | 185 | img = Image.fromarray(img) 186 | mask = Image.fromarray(mask) 187 | 188 | return img, mask 189 | -------------------------------------------------------------------------------- /network/datasets/grass_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | import torch 5 | from torch.utils.data import Dataset 6 | import albumentations as albu 7 | from .transform import * 8 | from PIL import Image 9 | import random 10 | 11 | 12 | CLASSES = ("low", "middle-low", "middle", "middle-high", "high") 13 | PALETTE = [ 14 | [185, 101, 71], 15 | [248, 202, 155], 16 | [211, 232, 158], 17 | [138, 191, 104], 18 | [92, 144, 77], 19 | ] 20 | 21 | ORIGIN_IMG_SIZE = (256, 256) 22 | INPUT_IMG_SIZE = (256, 256) 23 | TEST_IMG_SIZE = (256, 256) 24 | 25 | 26 | def get_training_transform(): 27 | train_transform = [ 28 | albu.HorizontalFlip(p=0.5), 29 | albu.VerticalFlip(p=0.5), 30 | albu.RandomBrightnessContrast(brightness_limit=0.25, contrast_limit=0.25, p=0.25), 31 | albu.Sharpen(), 32 | albu.Normalize() 33 | ] 34 | return albu.Compose(train_transform) 35 | 36 | 37 | def train_aug(img, mask): 38 | # crop_aug = SmartCropV1(crop_size=768, max_ratio=0.75, ignore_index=255, nopad=False) 39 | # label, mask = crop_aug(label, mask) 40 | img, mask = np.array(img), np.array(mask) 41 | aug = get_training_transform()(image=img.copy(), mask=mask.copy()) 42 | img, mask = aug['image'], aug['mask'] 43 | return img, mask 44 | 45 | 46 | def get_val_transform(): 47 | val_transform = [ 48 | albu.Normalize() 49 | ] 50 | return albu.Compose(val_transform) 51 | 52 | 53 | def val_aug(img, mask): 54 | img, mask = np.array(img), np.array(mask) 55 | aug = get_val_transform()(image=img.copy(), mask=mask.copy()) 56 | img, mask = aug['image'], aug['mask'] 57 | return img, mask 58 | 59 | 60 | def get_test_transform(): 61 | test_transform = [ 62 | albu.Normalize() 63 | ] 64 | return albu.Compose(test_transform) 65 | 66 | 67 | def test_aug(img, mask): 68 | img, mask = np.array(img), np.array(mask) 69 | aug = get_test_transform()(image=img.copy(), mask=mask.copy()) 70 | img, mask = aug['image'], aug['mask'] 71 | return img, mask 72 | 73 | 74 | class GrassDataset(Dataset): 75 | def __init__( 76 | self, 77 | data_root="data/grass", 78 | mode="train", 79 | img_dir="img_dir", 80 | mask_dir="ann_dir", 81 | img_suffix=".tif", 82 | mask_suffix=".png", 83 | transform=test_aug, 84 | mosaic_ratio=0.0, 85 | img_size=ORIGIN_IMG_SIZE, 86 | ): 87 | self.data_root = data_root 88 | self.img_dir = img_dir 89 | self.mask_dir = mask_dir 90 | self.img_suffix = img_suffix 91 | self.mask_suffix = mask_suffix 92 | self.transform = transform 93 | self.mode = mode 94 | self.mosaic_ratio = mosaic_ratio 95 | self.img_size = img_size 96 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 97 | 98 | def __getitem__(self, index): 99 | p_ratio = random.random() 100 | if p_ratio > self.mosaic_ratio or self.mode == "val": 101 | img, mask = self.load_img_and_mask(index) 102 | if self.transform: 103 | img, mask = self.transform(img, mask) 104 | else: 105 | img, mask = self.load_mosaic_img_and_mask(index) 106 | if self.transform: 107 | img, mask = self.transform(img, mask) 108 | 109 | img = torch.from_numpy(img).permute(2, 0, 1).float() 110 | mask = torch.from_numpy(mask).long() 111 | img_id = self.img_ids[index] 112 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 113 | return results 114 | 115 | def __len__(self): 116 | return len(self.img_ids) 117 | 118 | def get_img_ids(self, data_root, img_dir, mask_dir): 119 | img_filename_list = os.listdir(osp.join(data_root, img_dir, self.mode)) 120 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir, self.mode)) 121 | assert len(img_filename_list) == len(mask_filename_list) 122 | img_ids = [str(id.split(".")[0]) for id in mask_filename_list] 123 | return img_ids 124 | 125 | def load_img_and_mask(self, index): 126 | img_id = self.img_ids[index] 127 | img_name = osp.join( 128 | self.data_root, self.img_dir, self.mode, img_id + self.img_suffix 129 | ) 130 | mask_name = osp.join( 131 | self.data_root, self.mask_dir, self.mode, img_id + self.mask_suffix 132 | ) 133 | img = Image.open(img_name).convert("RGB") 134 | mask = Image.open(mask_name) 135 | return img, mask 136 | 137 | def load_mosaic_img_and_mask(self, index): 138 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 139 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 140 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 141 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 142 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 143 | 144 | img_a, mask_a = np.array(img_a), np.array(mask_a) 145 | img_b, mask_b = np.array(img_b), np.array(mask_b) 146 | img_c, mask_c = np.array(img_c), np.array(mask_c) 147 | img_d, mask_d = np.array(img_d), np.array(mask_d) 148 | 149 | w = self.img_size[1] 150 | h = self.img_size[0] 151 | 152 | start_x = w // 4 153 | strat_y = h // 4 154 | # The coordinates of the splice center 155 | offset_x = random.randint(start_x, (w - start_x)) 156 | offset_y = random.randint(strat_y, (h - strat_y)) 157 | 158 | crop_size_a = (offset_x, offset_y) 159 | crop_size_b = (w - offset_x, offset_y) 160 | crop_size_c = (offset_x, h - offset_y) 161 | crop_size_d = (w - offset_x, h - offset_y) 162 | 163 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 164 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 165 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 166 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 167 | 168 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 169 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 170 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 171 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 172 | 173 | img_crop_a, mask_crop_a = croped_a["image"], croped_a["mask"] 174 | img_crop_b, mask_crop_b = croped_b["image"], croped_b["mask"] 175 | img_crop_c, mask_crop_c = croped_c["image"], croped_c["mask"] 176 | img_crop_d, mask_crop_d = croped_d["image"], croped_d["mask"] 177 | 178 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 179 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 180 | img = np.concatenate((top, bottom), axis=0) 181 | 182 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 183 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 184 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 185 | mask = np.ascontiguousarray(mask) 186 | img = np.ascontiguousarray(img) 187 | 188 | img = Image.fromarray(img) 189 | mask = Image.fromarray(mask) 190 | 191 | return img, mask 192 | -------------------------------------------------------------------------------- /network/losses/lovasz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Lovasz-Softmax and Jaccard hinge loss in PyTorch 3 | Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License) 4 | """ 5 | 6 | from __future__ import print_function, division 7 | 8 | from typing import Optional, Union 9 | 10 | import torch 11 | import torch.nn.functional as F 12 | from torch.autograd import Variable 13 | from torch.nn.modules.loss import _Loss 14 | 15 | try: 16 | from itertools import ifilterfalse 17 | except ImportError: # py3k 18 | from itertools import filterfalse as ifilterfalse 19 | 20 | __all__ = ["BinaryLovaszLoss", "LovaszLoss"] 21 | 22 | 23 | def _lovasz_grad(gt_sorted): 24 | """Compute gradient of the Lovasz extension w.r.t sorted errors 25 | See Alg. 1 in paper 26 | """ 27 | p = len(gt_sorted) 28 | gts = gt_sorted.sum() 29 | intersection = gts - gt_sorted.float().cumsum(0) 30 | union = gts + (1 - gt_sorted).float().cumsum(0) 31 | jaccard = 1.0 - intersection / union 32 | if p > 1: # cover 1-pixel case 33 | jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] 34 | return jaccard 35 | 36 | 37 | def _lovasz_hinge(logits, labels, per_image=True, ignore_index=None): 38 | """ 39 | Binary Lovasz hinge loss 40 | logits: [B, H, W] Variable, logits at each pixel (between -infinity and +infinity) 41 | labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) 42 | per_image: compute the loss per image instead of per batch 43 | ignore: void class id 44 | """ 45 | if per_image: 46 | loss = mean( 47 | _lovasz_hinge_flat(*_flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore_index)) 48 | for log, lab in zip(logits, labels) 49 | ) 50 | else: 51 | loss = _lovasz_hinge_flat(*_flatten_binary_scores(logits, labels, ignore_index)) 52 | return loss 53 | 54 | 55 | def _lovasz_hinge_flat(logits, labels): 56 | """Binary Lovasz hinge loss 57 | Args: 58 | logits: [P] Variable, logits at each prediction (between -iinfinity and +iinfinity) 59 | labels: [P] Tensor, binary ground truth labels (0 or 1) 60 | ignore: label to ignore 61 | """ 62 | if len(labels) == 0: 63 | # only void pixels, the gradients should be 0 64 | return logits.sum() * 0.0 65 | signs = 2.0 * labels.float() - 1.0 66 | errors = 1.0 - logits * Variable(signs) 67 | errors_sorted, perm = torch.sort(errors, dim=0, descending=True) 68 | perm = perm.data 69 | gt_sorted = labels[perm] 70 | grad = _lovasz_grad(gt_sorted) 71 | loss = torch.dot(F.relu(errors_sorted), Variable(grad)) 72 | return loss 73 | 74 | 75 | def _flatten_binary_scores(scores, labels, ignore_index=None): 76 | """Flattens predictions in the batch (binary case) 77 | Remove labels equal to 'ignore' 78 | """ 79 | scores = scores.view(-1) 80 | labels = labels.view(-1) 81 | if ignore_index is None: 82 | return scores, labels 83 | valid = labels != ignore_index 84 | vscores = scores[valid] 85 | vlabels = labels[valid] 86 | return vscores, vlabels 87 | 88 | 89 | # --------------------------- MULTICLASS LOSSES --------------------------- 90 | 91 | 92 | def _lovasz_softmax(probas, labels, classes="present", per_image=False, ignore_index=None): 93 | """Multi-class Lovasz-Softmax loss 94 | Args: 95 | @param probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1). 96 | Interpreted as binary (sigmoid) output with outputs of size [B, H, W]. 97 | @param labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1) 98 | @param classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average. 99 | @param per_image: compute the loss per image instead of per batch 100 | @param ignore_index: void class labels 101 | """ 102 | if per_image: 103 | loss = mean( 104 | _lovasz_softmax_flat(*_flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore_index), classes=classes) 105 | for prob, lab in zip(probas, labels) 106 | ) 107 | else: 108 | loss = _lovasz_softmax_flat(*_flatten_probas(probas, labels, ignore_index), classes=classes) 109 | return loss 110 | 111 | 112 | def _lovasz_softmax_flat(probas, labels, classes="present"): 113 | """Multi-class Lovasz-Softmax loss 114 | Args: 115 | @param probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) 116 | @param labels: [P] Tensor, ground truth labels (between 0 and C - 1) 117 | @param classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average. 118 | """ 119 | if probas.numel() == 0: 120 | # only void pixels, the gradients should be 0 121 | return probas * 0.0 122 | C = probas.size(1) 123 | losses = [] 124 | class_to_sum = list(range(C)) if classes in ["all", "present"] else classes 125 | for c in class_to_sum: 126 | fg = (labels == c).type_as(probas) # foreground for class c 127 | if classes == "present" and fg.sum() == 0: 128 | continue 129 | if C == 1: 130 | if len(classes) > 1: 131 | raise ValueError("Sigmoid output possible only with 1 class") 132 | class_pred = probas[:, 0] 133 | else: 134 | class_pred = probas[:, c] 135 | errors = (fg - class_pred).abs() 136 | errors_sorted, perm = torch.sort(errors, 0, descending=True) 137 | perm = perm.data 138 | fg_sorted = fg[perm] 139 | losses.append(torch.dot(errors_sorted, _lovasz_grad(fg_sorted))) 140 | return mean(losses) 141 | 142 | 143 | def _flatten_probas(probas, labels, ignore=None): 144 | """Flattens predictions in the batch""" 145 | if probas.dim() == 3: 146 | # assumes output of a sigmoid layer 147 | B, H, W = probas.size() 148 | probas = probas.view(B, 1, H, W) 149 | 150 | C = probas.size(1) 151 | probas = torch.movedim(probas, 1, -1) # [B, C, Di, Dj, ...] -> [B, Di, Dj, ..., C] 152 | probas = probas.contiguous().view(-1, C) # [P, C] 153 | 154 | labels = labels.view(-1) 155 | if ignore is None: 156 | return probas, labels 157 | valid = labels != ignore 158 | vprobas = probas[valid] 159 | vlabels = labels[valid] 160 | return vprobas, vlabels 161 | 162 | 163 | # --------------------------- HELPER FUNCTIONS --------------------------- 164 | def isnan(x): 165 | return x != x 166 | 167 | 168 | def mean(values, ignore_nan=False, empty=0): 169 | """Nanmean compatible with generators.""" 170 | values = iter(values) 171 | if ignore_nan: 172 | values = ifilterfalse(isnan, values) 173 | try: 174 | n = 1 175 | acc = next(values) 176 | except StopIteration: 177 | if empty == "raise": 178 | raise ValueError("Empty mean") 179 | return empty 180 | for n, v in enumerate(values, 2): 181 | acc += v 182 | if n == 1: 183 | return acc 184 | return acc / n 185 | 186 | 187 | class BinaryLovaszLoss(_Loss): 188 | def __init__(self, per_image: bool = False, ignore_index: Optional[Union[int, float]] = None): 189 | super().__init__() 190 | self.ignore_index = ignore_index 191 | self.per_image = per_image 192 | 193 | def forward(self, logits, target): 194 | return _lovasz_hinge(logits, target, per_image=self.per_image, ignore_index=self.ignore_index) 195 | 196 | 197 | class LovaszLoss(_Loss): 198 | def __init__(self, per_image=False, ignore=None): 199 | super().__init__() 200 | self.ignore = ignore 201 | self.per_image = per_image 202 | 203 | def forward(self, logits, target): 204 | return _lovasz_softmax(logits, target, per_image=self.per_image, ignore_index=self.ignore) 205 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import pytorch_lightning as pl 2 | from pytorch_lightning.callbacks import ModelCheckpoint 3 | from tools.cfg import py2cfg 4 | import os 5 | import torch 6 | from torch import nn 7 | import cv2 8 | import numpy as np 9 | import argparse 10 | from pathlib import Path 11 | from tools.metric import Evaluator 12 | from pytorch_lightning.loggers import CSVLogger,WandbLogger 13 | import random 14 | 15 | 16 | 17 | 18 | def seed_everything(seed): 19 | random.seed(seed) 20 | os.environ['PYTHONHASHSEED'] = str(seed) 21 | np.random.seed(seed) 22 | torch.manual_seed(seed) 23 | torch.cuda.manual_seed(seed) 24 | torch.backends.cudnn.deterministic = True 25 | torch.backends.cudnn.benchmark = True 26 | 27 | 28 | def get_args(): 29 | parser = argparse.ArgumentParser() 30 | arg = parser.add_argument 31 | arg("-c", "--config_path", type=Path, help="Path to the config.", required=True) 32 | return parser.parse_args() 33 | 34 | import pytorch_model_summary 35 | from torchinfo import summary 36 | import torchsummary 37 | 38 | class Supervision_Train(pl.LightningModule): 39 | def __init__(self, config): 40 | super().__init__() 41 | self.config = config 42 | self.net = config.net 43 | 44 | self.loss = config.loss 45 | 46 | self.metrics_train = Evaluator(num_class=config.num_classes) 47 | self.metrics_val = Evaluator(num_class=config.num_classes) 48 | 49 | def forward(self, x): 50 | # only net is used in the prediction/inference 51 | #summary(self.net, input_size=(3, 1024, 1024)) 52 | #print(pytorch_model_summary.summary(self.net(x), torch.zeros(8, 3, 1024, 1024), max_depth=None, show_parent_layers=True, show_input=True)) 53 | #summary(self.net, (8,3,1024,1024)) 54 | #torchsummary.summary(self.net, (3, 1024, 1024)) 55 | 56 | 57 | seg_pre = self.net(x) 58 | return seg_pre 59 | 60 | def training_step(self, batch, batch_idx): 61 | img, mask = batch['img'], batch['gt_semantic_seg'] 62 | loss = 0 63 | prediction = self.net(img) 64 | if self.config.get("has_contrastive_loss",False): 65 | loss += prediction[-1] 66 | prediction = prediction[:-1] 67 | loss += self.loss(prediction, mask) 68 | 69 | if self.config.use_aux_loss: 70 | pre_mask = nn.Softmax(dim=1)(prediction[0]) 71 | else: 72 | pre_mask = nn.Softmax(dim=1)(prediction) 73 | 74 | pre_mask = pre_mask.argmax(dim=1) 75 | 76 | for i in range(mask.shape[0]): 77 | self.metrics_train.add_batch(mask[i].cpu().numpy(), pre_mask[i].cpu().numpy()) 78 | 79 | return {"loss": loss} 80 | 81 | def on_train_epoch_end(self): 82 | if 'vaihingen' in self.config.log_name: 83 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 84 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 85 | elif 'potsdam' in self.config.log_name: 86 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 87 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 88 | elif 'whubuilding' in self.config.log_name: 89 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 90 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 91 | elif 'massbuilding' in self.config.log_name: 92 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 93 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 94 | elif 'cropland' in self.config.log_name: 95 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 96 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 97 | else: 98 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()) 99 | F1 = np.nanmean(self.metrics_train.F1()) 100 | 101 | OA = np.nanmean(self.metrics_train.OA()) 102 | iou_per_class = self.metrics_train.Intersection_over_Union() 103 | eval_value = {'train_mIoU': mIoU, 104 | 'train_F1': F1, 105 | 'train_OA': OA} 106 | print('train:', eval_value) 107 | 108 | iou_value = {} 109 | for class_name, iou in zip(self.config.classes, iou_per_class): 110 | iou_value[class_name] = iou 111 | print(iou_value) 112 | self.metrics_train.reset() 113 | log_dict = {'train_mIoU': mIoU, 'train_F1': F1, 'train_OA': OA} 114 | self.log_dict(log_dict, prog_bar=True) 115 | 116 | def validation_step(self, batch, batch_idx): 117 | img, mask = batch['img'], batch['gt_semantic_seg'] 118 | prediction = self.forward(img) 119 | pre_mask = nn.Softmax(dim=1)(prediction) 120 | pre_mask = pre_mask.argmax(dim=1) 121 | for i in range(mask.shape[0]): 122 | self.metrics_val.add_batch(mask[i].cpu().numpy(), pre_mask[i].cpu().numpy()) 123 | 124 | loss_val = self.loss(prediction, mask) 125 | return {"loss_val": loss_val} 126 | 127 | def on_validation_epoch_end(self): 128 | if 'vaihingen' in self.config.log_name: 129 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 130 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 131 | elif 'potsdam' in self.config.log_name: 132 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 133 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 134 | elif 'whubuilding' in self.config.log_name: 135 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 136 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 137 | elif 'massbuilding' in self.config.log_name: 138 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 139 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 140 | elif 'cropland' in self.config.log_name: 141 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 142 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 143 | else: 144 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()) 145 | F1 = np.nanmean(self.metrics_val.F1()) 146 | 147 | OA = np.nanmean(self.metrics_val.OA()) 148 | iou_per_class = self.metrics_val.Intersection_over_Union() 149 | 150 | eval_value = {'val_mIoU': mIoU, 151 | 'val_F1': F1, 152 | 'val_OA': OA} 153 | print('val:', eval_value) 154 | iou_value = {} 155 | for class_name, iou in zip(self.config.classes, iou_per_class): 156 | iou_value[class_name] = iou 157 | print(iou_value) 158 | 159 | self.metrics_val.reset() 160 | log_dict = {'val_mIoU': mIoU, 'val_F1': F1, 'val_OA': OA} 161 | self.log_dict(log_dict, prog_bar=True) 162 | 163 | def configure_optimizers(self): 164 | optimizer = self.config.optimizer 165 | lr_scheduler = self.config.lr_scheduler 166 | 167 | return [optimizer], [lr_scheduler] 168 | 169 | def train_dataloader(self): 170 | 171 | return self.config.train_loader 172 | 173 | def val_dataloader(self): 174 | 175 | return self.config.val_loader 176 | 177 | 178 | # training 179 | def main(): 180 | args = get_args() 181 | config = py2cfg(args.config_path) 182 | seed_everything(42) 183 | 184 | checkpoint_callback = ModelCheckpoint(save_top_k=config.save_top_k, monitor=config.monitor, 185 | save_last=config.save_last, mode=config.monitor_mode, 186 | dirpath=config.weights_path, 187 | filename=config.weights_name) 188 | # logger = [CSVLogger('logs', name=config.log_name),WandbLogger(name=config.wandb_name,save_dir=config.wand_dir,project=config.wandb_project)] 189 | 190 | logger = CSVLogger('logs', name=config.log_name) 191 | 192 | model = Supervision_Train(config) 193 | if config.pretrained_ckpt_path: 194 | model = Supervision_Train.load_from_checkpoint(config.pretrained_ckpt_path, config=config) 195 | 196 | trainer = pl.Trainer(devices=config.gpus, max_epochs=config.max_epoch, accelerator='gpu', 197 | check_val_every_n_epoch=config.check_val_every_n_epoch, 198 | callbacks=[checkpoint_callback], 199 | logger=logger) 200 | trainer.fit(model=model, ckpt_path=config.resume_ckpt_path) 201 | 202 | 203 | if __name__ == "__main__": 204 | main() 205 | -------------------------------------------------------------------------------- /tools/uavid_patch_split.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import numpy as np 4 | import cv2 5 | import multiprocessing.pool as mpp 6 | import multiprocessing as mp 7 | import time 8 | import argparse 9 | import torch 10 | import albumentations as albu 11 | 12 | import random 13 | 14 | def seed_everything(seed): 15 | random.seed(seed) 16 | os.environ['PYTHONHASHSEED'] = str(seed) 17 | np.random.seed(seed) 18 | torch.manual_seed(seed) 19 | torch.cuda.manual_seed(seed) 20 | torch.backends.cudnn.deterministic = True 21 | torch.backends.cudnn.benchmark = True 22 | 23 | 24 | Building = np.array([128, 0, 0]) # label 0 25 | Road = np.array([128, 64, 128]) # label 1 26 | Tree = np.array([0, 128, 0]) # label 2 27 | LowVeg = np.array([128, 128, 0]) # label 3 28 | Moving_Car = np.array([64, 0, 128]) # label 4 29 | Static_Car = np.array([192, 0, 192]) # label 5 30 | Human = np.array([64, 64, 0]) # label 6 31 | Clutter = np.array([0, 0, 0]) # label 7 32 | Boundary = np.array([255, 255, 255]) # label 255 33 | 34 | num_classes = 8 35 | 36 | 37 | # split huge RS image to small patches 38 | def parse_args(): 39 | parser = argparse.ArgumentParser() 40 | parser.add_argument("--input-dir", default="data/uavid/uavid_train_val") 41 | parser.add_argument("--output-img-dir", default="data/uavid/train_val/images") 42 | parser.add_argument("--output-mask-dir", default="data/uavid/train_val/masks") 43 | parser.add_argument("--mode", type=str, default='train') 44 | parser.add_argument("--split-size-h", type=int, default=1024) 45 | parser.add_argument("--split-size-w", type=int, default=1024) 46 | parser.add_argument("--stride-h", type=int, default=1024) 47 | parser.add_argument("--stride-w", type=int, default=1024) 48 | return parser.parse_args() 49 | 50 | 51 | def label2rgb(mask): 52 | h, w = mask.shape[0], mask.shape[1] 53 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 54 | mask_convert = mask[np.newaxis, :, :] 55 | mask_rgb[np.all(mask_convert == 0, axis=0)] = Building 56 | mask_rgb[np.all(mask_convert == 1, axis=0)] = Road 57 | mask_rgb[np.all(mask_convert == 2, axis=0)] = Tree 58 | mask_rgb[np.all(mask_convert == 3, axis=0)] = LowVeg 59 | mask_rgb[np.all(mask_convert == 4, axis=0)] = Moving_Car 60 | mask_rgb[np.all(mask_convert == 5, axis=0)] = Static_Car 61 | mask_rgb[np.all(mask_convert == 6, axis=0)] = Human 62 | mask_rgb[np.all(mask_convert == 7, axis=0)] = Clutter 63 | mask_rgb[np.all(mask_convert == 255, axis=0)] = Boundary 64 | return mask_rgb 65 | 66 | 67 | def rgb2label(label): 68 | label_seg = np.zeros(label.shape[:2], dtype=np.uint8) 69 | label_seg[np.all(label == Building, axis=-1)] = 0 70 | label_seg[np.all(label == Road, axis=-1)] = 1 71 | label_seg[np.all(label == Tree, axis=-1)] = 2 72 | label_seg[np.all(label == LowVeg, axis=-1)] = 3 73 | label_seg[np.all(label == Moving_Car, axis=-1)] = 4 74 | label_seg[np.all(label == Static_Car, axis=-1)] = 5 75 | label_seg[np.all(label == Human, axis=-1)] = 6 76 | label_seg[np.all(label == Clutter, axis=-1)] = 7 77 | label_seg[np.all(label == Boundary, axis=-1)] = 255 78 | return label_seg 79 | 80 | 81 | def image_augment(image, mask, mode='train'): 82 | image_list = [] 83 | mask_list = [] 84 | image_width, image_height = image.shape[1], image.shape[0] 85 | mask_width, mask_height = mask.shape[1], mask.shape[0] 86 | assert image_height == mask_height and image_width == mask_width 87 | if mode == 'train': 88 | image_list_train = [image] 89 | mask_list_train = [mask] 90 | for i in range(len(image_list_train)): 91 | mask_tmp = rgb2label(mask_list_train[i]) 92 | image_list.append(image_list_train[i]) 93 | mask_list.append(mask_tmp) 94 | else: 95 | mask = rgb2label(mask.copy()) 96 | image_list.append(image) 97 | mask_list.append(mask) 98 | return image_list, mask_list 99 | 100 | 101 | def padifneeded(image, mask): 102 | # pad = albu.PadIfNeeded(min_height=2160, min_width=4096, position='bottom_right', 103 | # border_mode=0, value=[0, 0, 0], mask_value=[255, 255, 255])(image=image, mask=mask) # val 104 | 105 | pad = albu.PadIfNeeded(min_height=3072, min_width=4096, border_mode=0, 106 | position='bottom_right', value=[0, 0, 0], mask_value=[255, 255, 255])(image=image, mask=mask) # test 107 | 108 | 109 | # pad = albu.PadIfNeeded(min_height=h, min_width=w)(image=image, mask=mask) 110 | img_pad, mask_pad = pad['image'], pad['mask'] 111 | assert img_pad.shape[0] == 2048 or img_pad.shape[1] == 4096, print(img_pad.shape) 112 | # print(img_pad.shape) 113 | return img_pad, mask_pad 114 | 115 | 116 | def patch_format(inp): 117 | (input_dir, seq, imgs_output_dir, masks_output_dir, mode, split_size, stride) = inp 118 | img_paths = glob.glob(os.path.join(input_dir, str(seq), 'Images', "*.png")) 119 | mask_paths = glob.glob(os.path.join(input_dir, str(seq), 'Labels', "*.png")) 120 | for img_path, mask_path in zip(img_paths, mask_paths): 121 | img = cv2.imread(img_path, cv2.IMREAD_COLOR) 122 | mask = cv2.imread(mask_path, cv2.IMREAD_COLOR) 123 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 124 | mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) 125 | id = os.path.splitext(os.path.basename(img_path))[0] 126 | assert img.shape == mask.shape and img.shape[0] == 2160, print(img.shape) 127 | assert img.shape[1] == 3840 or img.shape[1] == 4096, print(img.shape) 128 | img, mask = padifneeded(img.copy(), mask.copy()) 129 | 130 | # print(img_path) 131 | # print(label.size, mask.size) 132 | # label and mask shape: WxHxC 133 | image_list, mask_list = image_augment(image=img.copy(), mask=mask.copy(), mode=mode) 134 | assert len(image_list) == len(mask_list) 135 | for m in range(len(image_list)): 136 | k = 0 137 | img = image_list[m] 138 | mask = mask_list[m] 139 | img, mask = img[-2048:, -4096:, :], mask[-2048:, -4096:] 140 | assert img.shape[0] == mask.shape[0] and img.shape[1] == mask.shape[1] 141 | for y in range(0, img.shape[0], stride[0]): 142 | for x in range(0, img.shape[1], stride[1]): 143 | img_tile_cut = img[y:y + split_size[0], x:x + split_size[1]] 144 | mask_tile_cut = mask[y:y + split_size[0], x:x + split_size[1]] 145 | img_tile, mask_tile = img_tile_cut, mask_tile_cut 146 | 147 | if img_tile.shape[0] == split_size[0] and img_tile.shape[1] == split_size[1] \ 148 | and mask_tile.shape[0] == split_size[0] and mask_tile.shape[1] == split_size[1]: 149 | if mode == 'train': 150 | out_img_path = os.path.join(imgs_output_dir, "{}_{}_{}_{}.png".format(seq, id, m, k)) 151 | img_tile = cv2.cvtColor(img_tile, cv2.COLOR_RGB2BGR) 152 | cv2.imwrite(out_img_path, img_tile) 153 | # print(img_tile.shape) 154 | 155 | out_mask_path = os.path.join(masks_output_dir, 156 | "{}_{}_{}_{}.png".format(seq, id, m, k)) 157 | cv2.imwrite(out_mask_path, mask_tile) 158 | else: 159 | img_tile = cv2.cvtColor(img_tile, cv2.COLOR_RGB2BGR) 160 | out_img_path = os.path.join(imgs_output_dir, "{}_{}_{}_{}.png".format(seq, id, m, k)) 161 | cv2.imwrite(out_img_path, img_tile) 162 | 163 | out_mask_path = os.path.join(masks_output_dir, "{}_{}_{}_{}.png".format(seq, id, m, k)) 164 | cv2.imwrite(out_mask_path, mask_tile) 165 | 166 | k += 1 167 | 168 | 169 | if __name__ == "__main__": 170 | seed_everything(42) 171 | args = parse_args() 172 | input_dir = args.input_dir 173 | imgs_output_dir = args.output_img_dir 174 | masks_output_dir = args.output_mask_dir 175 | mode = args.mode 176 | split_size_h = args.split_size_h 177 | split_size_w = args.split_size_w 178 | split_size = (split_size_h, split_size_w) 179 | stride_h = args.stride_h 180 | stride_w = args.stride_w 181 | stride = (stride_h, stride_w) 182 | seqs = os.listdir(input_dir) 183 | # print(seqs) 184 | 185 | if not os.path.exists(imgs_output_dir): 186 | os.makedirs(imgs_output_dir) 187 | if not os.path.exists(masks_output_dir): 188 | os.makedirs(masks_output_dir) 189 | 190 | inp = [(input_dir, seq, imgs_output_dir, masks_output_dir, mode, split_size, stride) 191 | for seq in seqs] 192 | 193 | t0 = time.time() 194 | mpp.Pool(processes=mp.cpu_count()).map(patch_format, inp) 195 | t1 = time.time() 196 | split_time = t1 - t0 197 | print('images spliting spends: {} s'.format(split_time)) 198 | 199 | 200 | -------------------------------------------------------------------------------- /network/datasets/transform.py: -------------------------------------------------------------------------------- 1 | import math 2 | import numbers 3 | from PIL import Image, ImageOps, ImageEnhance 4 | import numpy as np 5 | import random 6 | from scipy.ndimage.morphology import generate_binary_structure, binary_erosion 7 | from scipy.ndimage import maximum_filter 8 | 9 | 10 | class Compose(object): 11 | def __init__(self, transforms): 12 | self.transforms = transforms 13 | 14 | def __call__(self, img, mask): 15 | assert img.size == mask.size 16 | for t in self.transforms: 17 | img, mask = t(img, mask) 18 | return img, mask 19 | 20 | 21 | class RandomCrop(object): 22 | """ 23 | Take a random crop from the image. 24 | First the image or crop size may need to be adjusted if the incoming image 25 | is too small... 26 | If the image is smaller than the crop, then: 27 | the image is padded up to the size of the crop 28 | unless 'nopad', in which case the crop size is shrunk to fit the image 29 | A random crop is taken such that the crop fits within the image. 30 | If a centroid is passed in, the crop must intersect the centroid. 31 | """ 32 | def __init__(self, size=512, ignore_index=12, nopad=True): 33 | 34 | if isinstance(size, numbers.Number): 35 | self.size = (int(size), int(size)) 36 | else: 37 | self.size = size 38 | self.ignore_index = ignore_index 39 | self.nopad = nopad 40 | self.pad_color = (0, 0, 0) 41 | 42 | def __call__(self, img, mask, centroid=None): 43 | assert img.size == mask.size 44 | w, h = img.size 45 | # ASSUME H, W 46 | th, tw = self.size 47 | if w == tw and h == th: 48 | return img, mask 49 | 50 | if self.nopad: 51 | if th > h or tw > w: 52 | # Instead of padding, adjust crop size to the shorter edge of image. 53 | shorter_side = min(w, h) 54 | th, tw = shorter_side, shorter_side 55 | else: 56 | # Check if we need to pad label to fit for crop_size. 57 | if th > h: 58 | pad_h = (th - h) // 2 + 1 59 | else: 60 | pad_h = 0 61 | if tw > w: 62 | pad_w = (tw - w) // 2 + 1 63 | else: 64 | pad_w = 0 65 | border = (pad_w, pad_h, pad_w, pad_h) 66 | if pad_h or pad_w: 67 | img = ImageOps.expand(img, border=border, fill=self.pad_color) 68 | mask = ImageOps.expand(mask, border=border, fill=self.ignore_index) 69 | w, h = img.size 70 | 71 | if centroid is not None: 72 | # Need to insure that centroid is covered by crop and that crop 73 | # sits fully within the image 74 | c_x, c_y = centroid 75 | max_x = w - tw 76 | max_y = h - th 77 | x1 = random.randint(c_x - tw, c_x) 78 | x1 = min(max_x, max(0, x1)) 79 | y1 = random.randint(c_y - th, c_y) 80 | y1 = min(max_y, max(0, y1)) 81 | else: 82 | if w == tw: 83 | x1 = 0 84 | else: 85 | x1 = random.randint(0, w - tw) 86 | if h == th: 87 | y1 = 0 88 | else: 89 | y1 = random.randint(0, h - th) 90 | return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th)) 91 | 92 | 93 | class PadImage(object): 94 | def __init__(self, size=(512, 512), ignore_index=0): 95 | self.size = size 96 | self.ignore_index = ignore_index 97 | 98 | def __call__(self, img, mask): 99 | assert img.size == mask.size 100 | th, tw = self.size, self.size 101 | 102 | w, h = img.size 103 | 104 | if w > tw or h > th: 105 | wpercent = (tw / float(w)) 106 | target_h = int((float(img.size[1]) * float(wpercent))) 107 | img, mask = img.resize((tw, target_h), Image.BICUBIC), mask.resize((tw, target_h), Image.NEAREST) 108 | 109 | w, h = img.size 110 | img = ImageOps.expand(img, border=(0, 0, tw - w, th - h), fill=0) 111 | mask = ImageOps.expand(mask, border=(0, 0, tw - w, th - h), fill=self.ignore_index) 112 | 113 | return img, mask 114 | 115 | 116 | class RandomHorizontalFlip(object): 117 | 118 | def __init__(self, prob: float = 0.5): 119 | self.prob = prob 120 | 121 | def __call__(self, img, mask=None): 122 | if mask is not None: 123 | if random.random() < self.prob: 124 | return img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose( 125 | Image.FLIP_LEFT_RIGHT) 126 | else: 127 | return img, mask 128 | else: 129 | if random.random() < self.prob: 130 | return img.transpose(Image.FLIP_LEFT_RIGHT) 131 | else: 132 | return img 133 | 134 | 135 | class RandomVerticalFlip(object): 136 | def __init__(self, prob: float = 0.5): 137 | self.prob = prob 138 | 139 | def __call__(self, img, mask=None): 140 | if mask is not None: 141 | if random.random() < self.prob: 142 | return img.transpose(Image.FLIP_TOP_BOTTOM), mask.transpose( 143 | Image.FLIP_TOP_BOTTOM) 144 | else: 145 | return img, mask 146 | else: 147 | if random.random() < self.prob: 148 | return img.transpose(Image.FLIP_TOP_BOTTOM) 149 | else: 150 | return img 151 | 152 | 153 | class Resize(object): 154 | def __init__(self, size: tuple = (512, 512)): 155 | self.size = size # size: (h, w) 156 | 157 | def __call__(self, img, mask): 158 | assert img.size == mask.size 159 | return img.resize(self.size, Image.BICUBIC), mask.resize(self.size, Image.NEAREST) 160 | 161 | 162 | class RandomScale(object): 163 | def __init__(self, scale_list=[0.75, 1.0, 1.25], mode='value'): 164 | self.scale_list = scale_list 165 | self.mode = mode 166 | 167 | def __call__(self, img, mask): 168 | oh, ow = img.size 169 | scale_amt = 1.0 170 | if self.mode == 'value': 171 | scale_amt = np.random.choice(self.scale_list, 1) 172 | elif self.mode == 'range': 173 | scale_amt = random.uniform(self.scale_list[0], self.scale_list[-1]) 174 | h = int(scale_amt * oh) 175 | w = int(scale_amt * ow) 176 | return img.resize((w, h), Image.BICUBIC), mask.resize((w, h), Image.NEAREST) 177 | 178 | 179 | class ColorJitter(object): 180 | def __init__(self, brightness=0.5, contrast=0.5, saturation=0.5): 181 | if not brightness is None and brightness>0: 182 | self.brightness = [max(1-brightness, 0), 1+brightness] 183 | if not contrast is None and contrast>0: 184 | self.contrast = [max(1-contrast, 0), 1+contrast] 185 | if not saturation is None and saturation>0: 186 | self.saturation = [max(1-saturation, 0), 1+saturation] 187 | 188 | def __call__(self, img, mask=None): 189 | r_brightness = random.uniform(self.brightness[0], self.brightness[1]) 190 | r_contrast = random.uniform(self.contrast[0], self.contrast[1]) 191 | r_saturation = random.uniform(self.saturation[0], self.saturation[1]) 192 | img = ImageEnhance.Brightness(img).enhance(r_brightness) 193 | img = ImageEnhance.Contrast(img).enhance(r_contrast) 194 | img = ImageEnhance.Color(img).enhance(r_saturation) 195 | if mask is None: 196 | return img 197 | else: 198 | return img, mask 199 | 200 | 201 | class SmartCropV1(object): 202 | def __init__(self, crop_size=512, 203 | max_ratio=0.75, 204 | ignore_index=12, nopad=False): 205 | self.crop_size = crop_size 206 | self.max_ratio = max_ratio 207 | self.ignore_index = ignore_index 208 | self.crop = RandomCrop(crop_size, ignore_index=ignore_index, nopad=nopad) 209 | 210 | def __call__(self, img, mask): 211 | assert img.size == mask.size 212 | count = 0 213 | while True: 214 | img_crop, mask_crop = self.crop(img.copy(), mask.copy()) 215 | count += 1 216 | labels, cnt = np.unique(np.array(mask_crop), return_counts=True) 217 | cnt = cnt[labels != self.ignore_index] 218 | if len(cnt) > 1 and np.max(cnt) / np.sum(cnt) < self.max_ratio: 219 | break 220 | if count > 10: 221 | break 222 | 223 | return img_crop, mask_crop 224 | 225 | 226 | class SmartCropV2(object): 227 | def __init__(self, crop_size=512, num_classes=13, 228 | class_interest=[2, 3], 229 | class_ratio=[0.1, 0.25], 230 | max_ratio=0.75, 231 | ignore_index=12, nopad=True): 232 | self.crop_size = crop_size 233 | self.num_classes = num_classes 234 | self.class_interest = class_interest 235 | self.class_ratio = class_ratio 236 | self.max_ratio = max_ratio 237 | self.ignore_index = ignore_index 238 | self.crop = RandomCrop(crop_size, ignore_index=ignore_index, nopad=nopad) 239 | 240 | def __call__(self, img, mask): 241 | assert img.size == mask.size 242 | count = 0 243 | while True: 244 | img_crop, mask_crop = self.crop(img.copy(), mask.copy()) 245 | count += 1 246 | bins = np.array(range(self.num_classes + 1)) 247 | class_pixel_counts, _ = np.histogram(np.array(mask_crop), bins=bins) 248 | cf = class_pixel_counts / (self.crop_size * self.crop_size) 249 | cf = np.array(cf) 250 | for c, f in zip(self.class_interest, self.class_ratio): 251 | if cf[c] > f: 252 | break 253 | if np.max(cf) < 0.75 and np.argmax(cf) != self.ignore_index: 254 | break 255 | if count > 10: 256 | break 257 | 258 | return img_crop, mask_crop -------------------------------------------------------------------------------- /network/losses/functional.py: -------------------------------------------------------------------------------- 1 | import math 2 | from typing import Optional 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | 7 | __all__ = [ 8 | "focal_loss_with_logits", 9 | "softmax_focal_loss_with_logits", 10 | "soft_jaccard_score", 11 | "soft_dice_score", 12 | "wing_loss", 13 | ] 14 | 15 | 16 | def focal_loss_with_logits( 17 | output: torch.Tensor, 18 | target: torch.Tensor, 19 | gamma: float = 2.0, 20 | alpha: Optional[float] = 0.25, 21 | reduction: str = "mean", 22 | normalized: bool = False, 23 | reduced_threshold: Optional[float] = None, 24 | eps: float = 1e-6, 25 | ignore_index=None, 26 | ) -> torch.Tensor: 27 | """Compute binary focal loss between target and output logits. 28 | 29 | See :class:`~pytorch_toolbelt.losses.FocalLoss` for details. 30 | 31 | Args: 32 | output: Tensor of arbitrary shape (predictions of the models) 33 | target: Tensor of the same shape as input 34 | gamma: Focal loss power factor 35 | alpha: Weight factor to balance positive and negative samples. Alpha must be in [0...1] range, 36 | high values will give more weight to positive class. 37 | reduction (string, optional): Specifies the reduction to apply to the output: 38 | 'none' | 'mean' | 'sum' | 'batchwise_mean'. 'none': no reduction will be applied, 39 | 'mean': the sum of the output will be divided by the number of 40 | elements in the output, 'sum': the output will be summed. Note: :attr:`size_average` 41 | and :attr:`reduce` are in the process of being deprecated, and in the meantime, 42 | specifying either of those two args will override :attr:`reduction`. 43 | 'batchwise_mean' computes mean loss per sample in batch. Default: 'mean' 44 | normalized (bool): Compute normalized focal loss (https://arxiv.org/pdf/1909.07829.pdf). 45 | reduced_threshold (float, optional): Compute reduced focal loss (https://arxiv.org/abs/1903.01347). 46 | 47 | References: 48 | https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/loss/losses.py 49 | """ 50 | target = target.type_as(output) 51 | 52 | p = torch.sigmoid(output) 53 | ce_loss = F.binary_cross_entropy_with_logits(output, target, reduction="none") 54 | pt = p * target + (1 - p) * (1 - target) 55 | 56 | # compute the loss 57 | if reduced_threshold is None: 58 | focal_term = (1.0 - pt).pow(gamma) 59 | else: 60 | focal_term = ((1.0 - pt) / reduced_threshold).pow(gamma) 61 | focal_term = torch.masked_fill(focal_term, pt < reduced_threshold, 1) 62 | 63 | loss = focal_term * ce_loss 64 | 65 | if alpha is not None: 66 | loss *= alpha * target + (1 - alpha) * (1 - target) 67 | 68 | if ignore_index is not None: 69 | ignore_mask = target.eq(ignore_index) 70 | loss = torch.masked_fill(loss, ignore_mask, 0) 71 | if normalized: 72 | focal_term = torch.masked_fill(focal_term, ignore_mask, 0) 73 | 74 | if normalized: 75 | norm_factor = focal_term.sum(dtype=torch.float32).clamp_min(eps) 76 | loss /= norm_factor 77 | 78 | if reduction == "mean": 79 | loss = loss.mean() 80 | if reduction == "sum": 81 | loss = loss.sum(dtype=torch.float32) 82 | if reduction == "batchwise_mean": 83 | loss = loss.sum(dim=0, dtype=torch.float32) 84 | 85 | return loss 86 | 87 | 88 | def softmax_focal_loss_with_logits( 89 | output: torch.Tensor, 90 | target: torch.Tensor, 91 | gamma: float = 2.0, 92 | reduction="mean", 93 | normalized=False, 94 | reduced_threshold: Optional[float] = None, 95 | eps: float = 1e-6, 96 | ) -> torch.Tensor: 97 | """ 98 | Softmax version of focal loss between target and output logits. 99 | See :class:`~pytorch_toolbelt.losses.FocalLoss` for details. 100 | 101 | Args: 102 | output: Tensor of shape [B, C, *] (Similar to nn.CrossEntropyLoss) 103 | target: Tensor of shape [B, *] (Similar to nn.CrossEntropyLoss) 104 | reduction (string, optional): Specifies the reduction to apply to the output: 105 | 'none' | 'mean' | 'sum' | 'batchwise_mean'. 'none': no reduction will be applied, 106 | 'mean': the sum of the output will be divided by the number of 107 | elements in the output, 'sum': the output will be summed. Note: :attr:`size_average` 108 | and :attr:`reduce` are in the process of being deprecated, and in the meantime, 109 | specifying either of those two args will override :attr:`reduction`. 110 | 'batchwise_mean' computes mean loss per sample in batch. Default: 'mean' 111 | normalized (bool): Compute normalized focal loss (https://arxiv.org/pdf/1909.07829.pdf). 112 | reduced_threshold (float, optional): Compute reduced focal loss (https://arxiv.org/abs/1903.01347). 113 | """ 114 | log_softmax = F.log_softmax(output, dim=1) 115 | 116 | loss = F.nll_loss(log_softmax, target, reduction="none") 117 | pt = torch.exp(-loss) 118 | 119 | # compute the loss 120 | if reduced_threshold is None: 121 | focal_term = (1.0 - pt).pow(gamma) 122 | else: 123 | focal_term = ((1.0 - pt) / reduced_threshold).pow(gamma) 124 | focal_term[pt < reduced_threshold] = 1 125 | 126 | loss = focal_term * loss 127 | 128 | if normalized: 129 | norm_factor = focal_term.sum().clamp_min(eps) 130 | loss = loss / norm_factor 131 | 132 | if reduction == "mean": 133 | loss = loss.mean() 134 | if reduction == "sum": 135 | loss = loss.sum() 136 | if reduction == "batchwise_mean": 137 | loss = loss.sum(0) 138 | 139 | return loss 140 | 141 | 142 | def soft_jaccard_score( 143 | output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None 144 | ) -> torch.Tensor: 145 | """ 146 | 147 | :param output: 148 | :param target: 149 | :param smooth: 150 | :param eps: 151 | :param dims: 152 | :return: 153 | 154 | Shape: 155 | - Input: :math:`(N, NC, *)` where :math:`*` means 156 | any number of additional dimensions 157 | - Target: :math:`(N, NC, *)`, same shape as the input 158 | - Output: scalar. 159 | 160 | """ 161 | assert output.size() == target.size() 162 | 163 | if dims is not None: 164 | intersection = torch.sum(output * target, dim=dims) 165 | cardinality = torch.sum(output + target, dim=dims) 166 | else: 167 | intersection = torch.sum(output * target) 168 | cardinality = torch.sum(output + target) 169 | 170 | union = cardinality - intersection 171 | jaccard_score = (intersection + smooth) / (union + smooth).clamp_min(eps) 172 | return jaccard_score 173 | 174 | 175 | def soft_dice_score( 176 | output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None 177 | ) -> torch.Tensor: 178 | """ 179 | 180 | :param output: 181 | :param target: 182 | :param smooth: 183 | :param eps: 184 | :return: 185 | 186 | Shape: 187 | - Input: :math:`(N, NC, *)` where :math:`*` means any number 188 | of additional dimensions 189 | - Target: :math:`(N, NC, *)`, same shape as the input 190 | - Output: scalar. 191 | 192 | """ 193 | assert output.size() == target.size() 194 | if dims is not None: 195 | intersection = torch.sum(output * target, dim=dims) 196 | cardinality = torch.sum(output + target, dim=dims) 197 | else: 198 | intersection = torch.sum(output * target) 199 | cardinality = torch.sum(output + target) 200 | dice_score = (2.0 * intersection + smooth) / (cardinality + smooth).clamp_min(eps) 201 | return dice_score 202 | 203 | 204 | def wing_loss(output: torch.Tensor, target: torch.Tensor, width=5, curvature=0.5, reduction="mean"): 205 | """ 206 | https://arxiv.org/pdf/1711.06753.pdf 207 | :param output: 208 | :param target: 209 | :param width: 210 | :param curvature: 211 | :param reduction: 212 | :return: 213 | """ 214 | diff_abs = (target - output).abs() 215 | loss = diff_abs.clone() 216 | 217 | idx_smaller = diff_abs < width 218 | idx_bigger = diff_abs >= width 219 | 220 | loss[idx_smaller] = width * torch.log(1 + diff_abs[idx_smaller] / curvature) 221 | 222 | C = width - width * math.log(1 + width / curvature) 223 | loss[idx_bigger] = loss[idx_bigger] - C 224 | 225 | if reduction == "sum": 226 | loss = loss.sum() 227 | 228 | if reduction == "mean": 229 | loss = loss.mean() 230 | 231 | return loss 232 | 233 | 234 | def label_smoothed_nll_loss( 235 | lprobs: torch.Tensor, target: torch.Tensor, epsilon: float, ignore_index=None, reduction="mean", dim=-1 236 | ) -> torch.Tensor: 237 | """ 238 | 239 | Source: https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/label_smoothed_cross_entropy.py 240 | 241 | :param lprobs: Log-probabilities of predictions (e.g after log_softmax) 242 | :param target: 243 | :param epsilon: 244 | :param ignore_index: 245 | :param reduction: 246 | :return: 247 | """ 248 | if target.dim() == lprobs.dim() - 1: 249 | target = target.unsqueeze(dim) 250 | 251 | if ignore_index is not None: 252 | pad_mask = target.eq(ignore_index) 253 | target = target.masked_fill(pad_mask, 0) 254 | nll_loss = -lprobs.gather(dim=dim, index=target) 255 | smooth_loss = -lprobs.sum(dim=dim, keepdim=True) 256 | 257 | # nll_loss.masked_fill_(pad_mask, 0.0) 258 | # smooth_loss.masked_fill_(pad_mask, 0.0) 259 | nll_loss = nll_loss.masked_fill(pad_mask, 0.0) 260 | smooth_loss = smooth_loss.masked_fill(pad_mask, 0.0) 261 | else: 262 | nll_loss = -lprobs.gather(dim=dim, index=target) 263 | smooth_loss = -lprobs.sum(dim=dim, keepdim=True) 264 | 265 | nll_loss = nll_loss.squeeze(dim) 266 | smooth_loss = smooth_loss.squeeze(dim) 267 | 268 | if reduction == "sum": 269 | nll_loss = nll_loss.sum() 270 | smooth_loss = smooth_loss.sum() 271 | if reduction == "mean": 272 | nll_loss = nll_loss.mean() 273 | smooth_loss = smooth_loss.mean() 274 | 275 | eps_i = epsilon / lprobs.size(dim) 276 | loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss 277 | return loss 278 | -------------------------------------------------------------------------------- /test_uavid.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | import glob 4 | from PIL import Image 5 | import ttach as tta 6 | import cv2 7 | import numpy as np 8 | import torch 9 | import albumentations as albu 10 | from catalyst.dl import SupervisedRunner 11 | from skimage.morphology import remove_small_holes, remove_small_objects 12 | from tools.cfg import py2cfg 13 | from torch import nn 14 | from torch.utils.data import Dataset, DataLoader 15 | from tqdm import tqdm 16 | from train import * 17 | import random 18 | import os 19 | 20 | 21 | def seed_everything(seed): 22 | random.seed(seed) 23 | os.environ['PYTHONHASHSEED'] = str(seed) 24 | np.random.seed(seed) 25 | torch.manual_seed(seed) 26 | torch.cuda.manual_seed(seed) 27 | torch.backends.cudnn.deterministic = True 28 | torch.backends.cudnn.benchmark = True 29 | 30 | 31 | def pv2rgb(mask): 32 | h, w = mask.shape[0], mask.shape[1] 33 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 34 | mask_convert = mask[np.newaxis, :, :] 35 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [0, 255, 0] 36 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 37 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 38 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [255, 255, 0] 39 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [0, 204, 255] 40 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [0, 0, 255] 41 | mask_rgb = cv2.cvtColor(mask_rgb, cv2.COLOR_RGB2BGR) 42 | return mask_rgb 43 | 44 | 45 | def landcoverai_to_rgb(mask): 46 | w, h = mask.shape[0], mask.shape[1] 47 | mask_rgb = np.zeros(shape=(w, h, 3), dtype=np.uint8) 48 | mask_convert = mask[np.newaxis, :, :] 49 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [255, 255, 255] 50 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [233, 193, 133] 51 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [255, 0, 0] 52 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [0, 255, 0] 53 | mask_rgb = cv2.cvtColor(mask_rgb, cv2.COLOR_RGB2BGR) 54 | return mask_rgb 55 | 56 | 57 | def uavid2rgb(mask): 58 | h, w = mask.shape[0], mask.shape[1] 59 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 60 | mask_convert = mask[np.newaxis, :, :] 61 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [128, 0, 0] 62 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [128, 64, 128] 63 | mask_rgb[np.all(mask_convert == 2, axis=0)] = [0, 128, 0] 64 | mask_rgb[np.all(mask_convert == 3, axis=0)] = [128, 128, 0] 65 | mask_rgb[np.all(mask_convert == 4, axis=0)] = [64, 0, 128] 66 | mask_rgb[np.all(mask_convert == 5, axis=0)] = [192, 0, 192] 67 | mask_rgb[np.all(mask_convert == 6, axis=0)] = [64, 64, 0] 68 | mask_rgb[np.all(mask_convert == 7, axis=0)] = [0, 0, 0] 69 | mask_rgb = cv2.cvtColor(mask_rgb, cv2.COLOR_RGB2BGR) 70 | return mask_rgb 71 | 72 | 73 | def get_args(): 74 | parser = argparse.ArgumentParser() 75 | arg = parser.add_argument 76 | arg("-i", "--image_path", type=str, default='data/uavid/uavid_test', help="Path to huge image") 77 | arg("-c", "--config_path", type=Path, required=True, help="Path to config") 78 | arg("-o", "--output_path", type=Path, help="Path to save resulting masks.", required=True) 79 | arg("-t", "--tta", help="Test time augmentation.", default="lr", choices=[None, "d4", "lr"]) 80 | arg("-ph", "--patch-height", help="height of patch size", type=int, default=1152) 81 | arg("-pw", "--patch-width", help="width of patch size", type=int, default=1024) 82 | arg("-b", "--batch-size", help="batch size", type=int, default=2) 83 | arg("-d", "--dataset", help="dataset", default="uavid", choices=["pv", "landcoverai", "uavid"]) 84 | return parser.parse_args() 85 | 86 | 87 | def load_checkpoint(checkpoint_path, model): 88 | pretrained_dict = torch.load(checkpoint_path)['model_state_dict'] 89 | model_dict = model.state_dict() 90 | pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} 91 | model_dict.update(pretrained_dict) 92 | model.load_state_dict(model_dict) 93 | 94 | return model 95 | 96 | 97 | def get_img_padded(image, patch_size): 98 | oh, ow = image.shape[0], image.shape[1] # 3840, 2160 99 | rh, rw = oh % patch_size[0], ow % patch_size[1] # 100 | 101 | width_pad = 0 if rw == 0 else patch_size[1] - rw 102 | height_pad = 0 if rh == 0 else patch_size[0] - rh 103 | # print(oh, ow, rh, rw, height_pad, width_pad) 104 | h, w = oh + height_pad, ow + width_pad # 3840+ 105 | 106 | pad = albu.PadIfNeeded(min_height=h, min_width=w, border_mode=0, 107 | position='bottom_right', value=[0, 0, 0])(image=image) 108 | img_pad = pad['image'] 109 | return img_pad, height_pad, width_pad 110 | 111 | 112 | class InferenceDataset(Dataset): 113 | def __init__(self, tile_list=None, transform=albu.Normalize()): 114 | self.tile_list = tile_list 115 | self.transform = transform 116 | 117 | def __getitem__(self, index): 118 | img = self.tile_list[index] 119 | img_id = index 120 | aug = self.transform(image=img) 121 | img = aug['image'] 122 | img = torch.from_numpy(img).permute(2, 0, 1).float() 123 | results = dict(img_id=img_id, img=img) 124 | return results 125 | 126 | def __len__(self): 127 | return len(self.tile_list) 128 | 129 | 130 | def make_dataset_for_one_huge_image(img_path, patch_size): 131 | img = cv2.imread(img_path, cv2.IMREAD_COLOR) # 4k (3840*2160) 132 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 133 | tile_list = [] 134 | image_pad, height_pad, width_pad = get_img_padded(img.copy(), patch_size) 135 | 136 | output_height, output_width = image_pad.shape[0], image_pad.shape[1] 137 | 138 | for x in range(0, output_height, patch_size[0]): 139 | for y in range(0, output_width, patch_size[1]): 140 | image_tile = image_pad[x:x+patch_size[0], y:y+patch_size[1]] 141 | tile_list.append(image_tile) 142 | 143 | dataset = InferenceDataset(tile_list=tile_list) 144 | return dataset, width_pad, height_pad, output_width, output_height, image_pad, img.shape 145 | 146 | 147 | def main(): 148 | args = get_args() 149 | seed_everything(42) 150 | seqs = os.listdir(args.image_path) 151 | 152 | # print(img_paths) 153 | patch_size = (args.patch_height, args.patch_width) 154 | config = py2cfg(args.config_path) 155 | model = Supervision_Train.load_from_checkpoint(os.path.join(config.weights_path, config.test_weights_name+'.ckpt'), config=config,map_location="cpu") 156 | 157 | model.cuda(config.gpus[0]) 158 | model.eval() 159 | 160 | if args.tta == "lr": 161 | transforms = tta.Compose( 162 | [ 163 | tta.HorizontalFlip(), 164 | tta.VerticalFlip() 165 | ] 166 | ) 167 | model = tta.SegmentationTTAWrapper(model, transforms) 168 | elif args.tta == "d4": 169 | transforms = tta.Compose( 170 | [ 171 | tta.HorizontalFlip(), 172 | # tta.VerticalFlip(), 173 | # tta.Rotate90(angles=[0, 90, 180, 270]), 174 | tta.Scale(scales=[0.75, 1, 1.25, 1.5, 1.75]), 175 | # tta.Multiply(factors=[0.8, 1, 1.2]) 176 | ] 177 | ) 178 | model = tta.SegmentationTTAWrapper(model, transforms) 179 | 180 | for seq in seqs: 181 | img_paths = [] 182 | output_path = os.path.join(args.output_path, str(seq), 'Labels') 183 | if not os.path.exists(output_path): 184 | os.makedirs(output_path) 185 | for ext in ('*.tif', '*.png', '*.jpg'): 186 | img_paths.extend(glob.glob(os.path.join(args.image_path, str(seq), 'Images', ext))) 187 | img_paths.sort() 188 | # print(img_paths) 189 | for img_path in img_paths: 190 | img_name = img_path.split('/')[-1] 191 | # print('origin mask', original_mask.shape) 192 | dataset, width_pad, height_pad, output_width, output_height, img_pad, img_shape = \ 193 | make_dataset_for_one_huge_image(img_path, patch_size) 194 | # print('img_padded', img_pad.shape) 195 | output_mask = np.zeros(shape=(output_height, output_width), dtype=np.uint8) 196 | output_tiles = [] 197 | k = 0 198 | with torch.no_grad(): 199 | dataloader = DataLoader(dataset=dataset, batch_size=args.batch_size, 200 | drop_last=False, shuffle=False) 201 | for input in tqdm(dataloader): 202 | # raw_prediction NxCxHxW 203 | # img:torch.Tensor = input["img"] 204 | # img = img[0].permute(1,2,0).detach().cpu().numpy() 205 | # img = img * 255 206 | # img = img.astype(np.uint8) 207 | # print(input["img_id"]) 208 | # Image.fromarray(img).save("1.png") 209 | # exit() 210 | raw_predictions = model(input['img'].cuda(config.gpus[0])) 211 | # print('raw_pred shape:', raw_predictions.shape) 212 | raw_predictions = nn.Softmax(dim=1)(raw_predictions) 213 | # input_images['features'] NxCxHxW C=3 214 | predictions = raw_predictions.argmax(dim=1) 215 | image_ids = input['img_id'] 216 | # print('prediction', predictions.shape) 217 | # print(np.unique(predictions)) 218 | 219 | for i in range(predictions.shape[0]): 220 | raw_mask = predictions[i].cpu().numpy() 221 | mask = raw_mask 222 | output_tiles.append((mask, image_ids[i].cpu().numpy())) 223 | 224 | for m in range(0, output_height, patch_size[0]): 225 | for n in range(0, output_width, patch_size[1]): 226 | output_mask[m:m + patch_size[0], n:n + patch_size[1]] = output_tiles[k][0] 227 | k = k + 1 228 | 229 | output_mask = output_mask[-img_shape[0]:, -img_shape[1]:] 230 | 231 | # print('mask', output_mask.shape) 232 | if args.dataset == 'landcoverai': 233 | output_mask = landcoverai_to_rgb(output_mask) 234 | elif args.dataset == 'pv': 235 | output_mask = pv2rgb(output_mask) 236 | elif args.dataset == 'uavid': 237 | output_mask = uavid2rgb(output_mask) 238 | else: 239 | output_mask = output_mask 240 | assert img_shape == output_mask.shape 241 | cv2.imwrite(os.path.join(output_path, img_name), output_mask) 242 | 243 | 244 | if __name__ == "__main__": 245 | main() 246 | -------------------------------------------------------------------------------- /network/losses/bitempered_loss.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import torch 4 | from torch import nn, Tensor 5 | 6 | __all__ = ["BiTemperedLogisticLoss", "BinaryBiTemperedLogisticLoss"] 7 | 8 | 9 | def log_t(u, t): 10 | """Compute log_t for `u'.""" 11 | if t == 1.0: 12 | return u.log() 13 | else: 14 | return (u.pow(1.0 - t) - 1.0) / (1.0 - t) 15 | 16 | 17 | def exp_t(u, t): 18 | """Compute exp_t for `u'.""" 19 | if t == 1: 20 | return u.exp() 21 | else: 22 | return (1.0 + (1.0 - t) * u).relu().pow(1.0 / (1.0 - t)) 23 | 24 | 25 | def compute_normalization_fixed_point(activations: Tensor, t: float, num_iters: int) -> Tensor: 26 | """Return the normalization value for each example (t > 1.0). 27 | Args: 28 | activations: A multi-dimensional tensor with last dimension `num_classes`. 29 | t: Temperature 2 (> 1.0 for tail heaviness). 30 | num_iters: Number of iterations to run the method. 31 | Return: A tensor of same shape as activation with the last dimension being 1. 32 | """ 33 | mu, _ = torch.max(activations, -1, keepdim=True) 34 | normalized_activations_step_0 = activations - mu 35 | 36 | normalized_activations = normalized_activations_step_0 37 | 38 | for _ in range(num_iters): 39 | logt_partition = torch.sum(exp_t(normalized_activations, t), -1, keepdim=True) 40 | normalized_activations = normalized_activations_step_0 * logt_partition.pow(1.0 - t) 41 | 42 | logt_partition = torch.sum(exp_t(normalized_activations, t), -1, keepdim=True) 43 | normalization_constants = -log_t(1.0 / logt_partition, t) + mu 44 | 45 | return normalization_constants 46 | 47 | 48 | def compute_normalization_binary_search(activations: Tensor, t: float, num_iters: int) -> Tensor: 49 | """Compute normalization value for each example (t < 1.0). 50 | Args: 51 | activations: A multi-dimensional tensor with last dimension `num_classes`. 52 | t: Temperature 2 (< 1.0 for finite support). 53 | num_iters: Number of iterations to run the method. 54 | Return: A tensor of same rank as activation with the last dimension being 1. 55 | """ 56 | mu, _ = torch.max(activations, -1, keepdim=True) 57 | normalized_activations = activations - mu 58 | 59 | effective_dim = torch.sum((normalized_activations > -1.0 / (1.0 - t)).to(torch.int32), dim=-1, keepdim=True).to( 60 | activations.dtype 61 | ) 62 | 63 | shape_partition = activations.shape[:-1] + (1,) 64 | lower = torch.zeros(shape_partition, dtype=activations.dtype, device=activations.device) 65 | upper = -log_t(1.0 / effective_dim, t) * torch.ones_like(lower) 66 | 67 | for _ in range(num_iters): 68 | logt_partition = (upper + lower) / 2.0 69 | sum_probs = torch.sum(exp_t(normalized_activations - logt_partition, t), dim=-1, keepdim=True) 70 | update = (sum_probs < 1.0).to(activations.dtype) 71 | lower = torch.reshape(lower * update + (1.0 - update) * logt_partition, shape_partition) 72 | upper = torch.reshape(upper * (1.0 - update) + update * logt_partition, shape_partition) 73 | 74 | logt_partition = (upper + lower) / 2.0 75 | return logt_partition + mu 76 | 77 | 78 | class ComputeNormalization(torch.autograd.Function): 79 | """ 80 | Class implementing custom backward pass for compute_normalization. See compute_normalization. 81 | """ 82 | 83 | @staticmethod 84 | def forward(ctx, activations, t, num_iters): 85 | if t < 1.0: 86 | normalization_constants = compute_normalization_binary_search(activations, t, num_iters) 87 | else: 88 | normalization_constants = compute_normalization_fixed_point(activations, t, num_iters) 89 | 90 | ctx.save_for_backward(activations, normalization_constants) 91 | ctx.t = t 92 | return normalization_constants 93 | 94 | @staticmethod 95 | def backward(ctx, grad_output): 96 | activations, normalization_constants = ctx.saved_tensors 97 | t = ctx.t 98 | normalized_activations = activations - normalization_constants 99 | probabilities = exp_t(normalized_activations, t) 100 | escorts = probabilities.pow(t) 101 | escorts = escorts / escorts.sum(dim=-1, keepdim=True) 102 | grad_input = escorts * grad_output 103 | 104 | return grad_input, None, None 105 | 106 | 107 | def compute_normalization(activations, t, num_iters=5): 108 | """Compute normalization value for each example. 109 | Backward pass is implemented. 110 | Args: 111 | activations: A multi-dimensional tensor with last dimension `num_classes`. 112 | t: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). 113 | num_iters: Number of iterations to run the method. 114 | Return: A tensor of same rank as activation with the last dimension being 1. 115 | """ 116 | return ComputeNormalization.apply(activations, t, num_iters) 117 | 118 | 119 | def tempered_softmax(activations, t, num_iters=5): 120 | """Tempered softmax function. 121 | Args: 122 | activations: A multi-dimensional tensor with last dimension `num_classes`. 123 | t: Temperature > 1.0. 124 | num_iters: Number of iterations to run the method. 125 | Returns: 126 | A probabilities tensor. 127 | """ 128 | if t == 1.0: 129 | return activations.softmax(dim=-1) 130 | 131 | normalization_constants = compute_normalization(activations, t, num_iters) 132 | return exp_t(activations - normalization_constants, t) 133 | 134 | 135 | def bi_tempered_logistic_loss(activations, labels, t1, t2, label_smoothing=0.0, num_iters=5, reduction="mean"): 136 | """Bi-Tempered Logistic Loss. 137 | Args: 138 | activations: A multi-dimensional tensor with last dimension `num_classes`. 139 | labels: A tensor with shape and dtype as activations (onehot), 140 | or a long tensor of one dimension less than activations (pytorch standard) 141 | t1: Temperature 1 (< 1.0 for boundedness). 142 | t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). 143 | label_smoothing: Label smoothing parameter between [0, 1). Default 0.0. 144 | num_iters: Number of iterations to run the method. Default 5. 145 | reduction: ``'none'`` | ``'mean'`` | ``'sum'``. Default ``'mean'``. 146 | ``'none'``: No reduction is applied, return shape is shape of 147 | activations without the last dimension. 148 | ``'mean'``: Loss is averaged over minibatch. Return shape (1,) 149 | ``'sum'``: Loss is summed over minibatch. Return shape (1,) 150 | Returns: 151 | A loss tensor. 152 | """ 153 | if len(labels.shape) < len(activations.shape): # not one-hot 154 | labels_onehot = torch.zeros_like(activations) 155 | labels_onehot.scatter_(1, labels[..., None], 1) 156 | else: 157 | labels_onehot = labels 158 | 159 | if label_smoothing > 0: 160 | num_classes = labels_onehot.shape[-1] 161 | labels_onehot = (1 - label_smoothing * num_classes / (num_classes - 1)) * labels_onehot + label_smoothing / ( 162 | num_classes - 1 163 | ) 164 | 165 | probabilities = tempered_softmax(activations, t2, num_iters) 166 | 167 | loss_values = ( 168 | labels_onehot * log_t(labels_onehot + 1e-10, t1) 169 | - labels_onehot * log_t(probabilities, t1) 170 | - labels_onehot.pow(2.0 - t1) / (2.0 - t1) 171 | + probabilities.pow(2.0 - t1) / (2.0 - t1) 172 | ) 173 | loss_values = loss_values.sum(dim=-1) # sum over classes 174 | 175 | if reduction == "none": 176 | return loss_values 177 | if reduction == "sum": 178 | return loss_values.sum() 179 | if reduction == "mean": 180 | return loss_values.mean() 181 | 182 | 183 | class BiTemperedLogisticLoss(nn.Module): 184 | """ 185 | 186 | https://ai.googleblog.com/2019/08/bi-tempered-logistic-loss-for-training.html 187 | https://arxiv.org/abs/1906.03361 188 | """ 189 | 190 | def __init__(self, t1: float, t2: float, smoothing=0.0, ignore_index=None, reduction: str = "mean"): 191 | """ 192 | 193 | Args: 194 | t1: 195 | t2: 196 | smoothing: 197 | ignore_index: 198 | reduction: 199 | """ 200 | super(BiTemperedLogisticLoss, self).__init__() 201 | self.t1 = t1 202 | self.t2 = t2 203 | self.smoothing = smoothing 204 | self.reduction = reduction 205 | self.ignore_index = ignore_index 206 | 207 | def forward(self, predictions: Tensor, targets: Tensor) -> Tensor: 208 | loss = bi_tempered_logistic_loss( 209 | predictions, targets, t1=self.t1, t2=self.t2, label_smoothing=self.smoothing, reduction="none" 210 | ) 211 | 212 | if self.ignore_index is not None: 213 | mask = ~targets.eq(self.ignore_index) 214 | loss *= mask 215 | 216 | if self.reduction == "mean": 217 | loss = loss.mean() 218 | elif self.reduction == "sum": 219 | loss = loss.sum() 220 | return loss 221 | 222 | 223 | class BinaryBiTemperedLogisticLoss(nn.Module): 224 | """ 225 | Modification of BiTemperedLogisticLoss for binary classification case. 226 | It's signature matches nn.BCEWithLogitsLoss: Predictions and target tensors must have shape [B,1,...] 227 | 228 | References: 229 | https://ai.googleblog.com/2019/08/bi-tempered-logistic-loss-for-training.html 230 | https://arxiv.org/abs/1906.03361 231 | """ 232 | 233 | def __init__( 234 | self, t1: float, t2: float, smoothing: float = 0.0, ignore_index: Optional[int] = None, reduction: str = "mean" 235 | ): 236 | """ 237 | 238 | Args: 239 | t1: 240 | t2: 241 | smoothing: 242 | ignore_index: 243 | reduction: 244 | """ 245 | super().__init__() 246 | self.t1 = t1 247 | self.t2 = t2 248 | self.smoothing = smoothing 249 | self.reduction = reduction 250 | self.ignore_index = ignore_index 251 | 252 | def forward(self, predictions: Tensor, targets: Tensor) -> Tensor: 253 | """ 254 | Forward method of the loss function 255 | 256 | Args: 257 | predictions: [B,1,...] 258 | targets: [B,1,...] 259 | 260 | Returns: 261 | Zero-sized tensor with reduced loss if self.reduction is `sum` or `mean`; Otherwise returns loss of the 262 | shape of `predictions` tensor. 263 | """ 264 | if predictions.size(1) != 1 or targets.size(1) != 1: 265 | raise ValueError("Channel dimension for predictions and targets must be equal to 1") 266 | 267 | loss = bi_tempered_logistic_loss( 268 | torch.cat([-predictions, predictions], dim=1).moveaxis(1, -1), 269 | torch.cat([1 - targets, targets], dim=1).moveaxis(1, -1), 270 | t1=self.t1, 271 | t2=self.t2, 272 | label_smoothing=self.smoothing, 273 | reduction="none", 274 | ).unsqueeze(dim=1) 275 | 276 | if self.ignore_index is not None: 277 | mask = targets.eq(self.ignore_index) 278 | loss = torch.masked_fill(loss, mask, 0) 279 | 280 | if self.reduction == "mean": 281 | loss = loss.mean() 282 | elif self.reduction == "sum": 283 | loss = loss.sum() 284 | return loss 285 | -------------------------------------------------------------------------------- /network/datasets/vaihingen_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | # os.environ['CUDA_LAUNCH_BLOCKING'] = "1" 3 | # os.environ["CUDA_VISIBLE_DEVICES"] = "0" 4 | import os.path as osp 5 | import numpy as np 6 | import torch 7 | from torch.utils.data import Dataset 8 | import cv2 9 | import matplotlib.pyplot as plt 10 | import albumentations as albu 11 | 12 | import matplotlib.patches as mpatches 13 | from PIL import Image 14 | import random 15 | from .transform import * 16 | 17 | CLASSES = ('ImSurf', 'Building', 'LowVeg', 'Tree', 'Car', 'Clutter') 18 | PALETTE = [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], [255, 204, 0], [255, 0, 0]] 19 | 20 | ORIGIN_IMG_SIZE = (1024, 1024) 21 | INPUT_IMG_SIZE = (1024, 1024) 22 | TEST_IMG_SIZE = (1024, 1024) 23 | 24 | 25 | def get_training_transform(): 26 | train_transform = [ 27 | # albu.RandomBrightnessContrast(brightness_limit=0.25, contrast_limit=0.5, p=0.15), 28 | # albu.RandomBrightnessContrast(p=0.5), 29 | # albu.RandomCrop(height=256, width=256, always_apply=False, p=1.0), 30 | albu.RandomRotate90(p=0.5), 31 | albu.HorizontalFlip(p=0.5), 32 | albu.VerticalFlip(p=0.5), 33 | albu.Normalize() 34 | ] 35 | return albu.Compose(train_transform) 36 | 37 | 38 | def train_aug(img, mask): 39 | crop_aug = Compose([RandomScale(scale_list=[0.5, 0.75, 1.0, 1.25, 1.5], mode='value'), 40 | SmartCropV1(crop_size=512, max_ratio=0.5, 41 | ignore_index=len(CLASSES), nopad=False)]) 42 | img, mask = crop_aug(img, mask) 43 | img, mask = np.array(img), np.array(mask) 44 | aug = get_training_transform()(image=img.copy(), mask=mask.copy()) 45 | img, mask = aug['image'], aug['mask'] 46 | return img, mask 47 | 48 | # def train_aug(label, mask): 49 | # label, mask = np.array(label), np.array(mask) 50 | # aug = get_training_transform()(image=label.copy(), mask=mask.copy()) 51 | # label, mask = aug['image'], aug['mask'] 52 | # return label, mask 53 | 54 | 55 | def get_val_transform(): 56 | val_transform = [ 57 | albu.Normalize() 58 | ] 59 | return albu.Compose(val_transform) 60 | 61 | 62 | def val_aug(img, mask): 63 | img, mask = np.array(img), np.array(mask) 64 | aug = get_val_transform()(image=img.copy(), mask=mask.copy()) 65 | img, mask = aug['image'], aug['mask'] 66 | return img, mask 67 | 68 | 69 | def get_test_transform(): 70 | test_transform = [ 71 | albu.Normalize() 72 | ] 73 | return albu.Compose(test_transform) 74 | 75 | 76 | def test_aug(img, mask): 77 | img, mask = np.array(img), np.array(mask) 78 | aug = get_test_transform()(image=img.copy(), mask=mask.copy()) 79 | img, mask = aug['image'], aug['mask'] 80 | return img, mask 81 | 82 | 83 | class VaihingenDataset(Dataset): 84 | def __init__(self, data_root='data/vaihingen/test', mode='val', img_dir='images_1024', mask_dir='masks_1024', 85 | img_suffix='.tif', mask_suffix='.png', transform=val_aug, mosaic_ratio=0.0, 86 | img_size=ORIGIN_IMG_SIZE): 87 | self.data_root = data_root 88 | self.img_dir = img_dir 89 | self.mask_dir = mask_dir 90 | self.img_suffix = img_suffix 91 | self.mask_suffix = mask_suffix 92 | self.transform = transform 93 | self.mode = mode 94 | self.mosaic_ratio = mosaic_ratio 95 | self.img_size = img_size 96 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 97 | 98 | def __getitem__(self, index): 99 | p_ratio = random.random() 100 | if p_ratio > self.mosaic_ratio or self.mode == 'val' or self.mode == 'test': 101 | img, mask = self.load_img_and_mask(index) 102 | if self.transform: 103 | img, mask = self.transform(img, mask) 104 | else: 105 | img, mask = self.load_mosaic_img_and_mask(index) 106 | if self.transform: 107 | img, mask = self.transform(img, mask) 108 | 109 | img = torch.from_numpy(img).permute(2, 0, 1).float() 110 | mask = torch.from_numpy(mask).long() 111 | img_id = self.img_ids[index] 112 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 113 | return results 114 | 115 | def __len__(self): 116 | return len(self.img_ids) 117 | 118 | def get_img_ids(self, data_root, img_dir, mask_dir): 119 | img_filename_list = os.listdir(osp.join(data_root, img_dir)) 120 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir)) 121 | assert len(img_filename_list) == len(mask_filename_list) 122 | img_ids = [str(id.split('.')[0]) for id in mask_filename_list] 123 | return img_ids 124 | 125 | def load_img_and_mask(self, index): 126 | img_id = self.img_ids[index] 127 | img_name = osp.join(self.data_root, self.img_dir, img_id + self.img_suffix) 128 | mask_name = osp.join(self.data_root, self.mask_dir, img_id + self.mask_suffix) 129 | img = Image.open(img_name).convert('RGB') 130 | mask = Image.open(mask_name).convert('L') 131 | return img, mask 132 | 133 | def load_mosaic_img_and_mask(self, index): 134 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 135 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 136 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 137 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 138 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 139 | 140 | img_a, mask_a = np.array(img_a), np.array(mask_a) 141 | img_b, mask_b = np.array(img_b), np.array(mask_b) 142 | img_c, mask_c = np.array(img_c), np.array(mask_c) 143 | img_d, mask_d = np.array(img_d), np.array(mask_d) 144 | 145 | h = self.img_size[0] 146 | w = self.img_size[1] 147 | 148 | start_x = w // 4 149 | strat_y = h // 4 150 | # The coordinates of the splice center 151 | offset_x = random.randint(start_x, (w - start_x)) 152 | offset_y = random.randint(strat_y, (h - strat_y)) 153 | 154 | crop_size_a = (offset_x, offset_y) 155 | crop_size_b = (w - offset_x, offset_y) 156 | crop_size_c = (offset_x, h - offset_y) 157 | crop_size_d = (w - offset_x, h - offset_y) 158 | 159 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 160 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 161 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 162 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 163 | 164 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 165 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 166 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 167 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 168 | 169 | img_crop_a, mask_crop_a = croped_a['image'], croped_a['mask'] 170 | img_crop_b, mask_crop_b = croped_b['image'], croped_b['mask'] 171 | img_crop_c, mask_crop_c = croped_c['image'], croped_c['mask'] 172 | img_crop_d, mask_crop_d = croped_d['image'], croped_d['mask'] 173 | 174 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 175 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 176 | img = np.concatenate((top, bottom), axis=0) 177 | 178 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 179 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 180 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 181 | mask = np.ascontiguousarray(mask) 182 | img = np.ascontiguousarray(img) 183 | img = Image.fromarray(img) 184 | mask = Image.fromarray(mask) 185 | # print(label.shape) 186 | 187 | return img, mask 188 | 189 | 190 | def show_img_mask_seg(seg_path, img_path, mask_path, start_seg_index): 191 | seg_list = os.listdir(seg_path) 192 | seg_list = [f for f in seg_list if f.endswith('.png')] 193 | fig, ax = plt.subplots(2, 3, figsize=(18, 12)) 194 | seg_list = seg_list[start_seg_index:start_seg_index+2] 195 | patches = [mpatches.Patch(color=np.array(PALETTE[i])/255., label=CLASSES[i]) for i in range(len(CLASSES))] 196 | for i in range(len(seg_list)): 197 | seg_id = seg_list[i] 198 | img_seg = cv2.imread(f'{seg_path}/{seg_id}', cv2.IMREAD_UNCHANGED) 199 | img_seg = img_seg.astype(np.uint8) 200 | img_seg = Image.fromarray(img_seg).convert('P') 201 | img_seg.putpalette(np.array(PALETTE, dtype=np.uint8)) 202 | img_seg = np.array(img_seg.convert('RGB')) 203 | mask = cv2.imread(f'{mask_path}/{seg_id}', cv2.IMREAD_UNCHANGED) 204 | mask = mask.astype(np.uint8) 205 | mask = Image.fromarray(mask).convert('P') 206 | mask.putpalette(np.array(PALETTE, dtype=np.uint8)) 207 | mask = np.array(mask.convert('RGB')) 208 | img_id = str(seg_id.split('.')[0])+'.tif' 209 | img = cv2.imread(f'{img_path}/{img_id}', cv2.IMREAD_COLOR) 210 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 211 | ax[i, 0].set_axis_off() 212 | ax[i, 0].imshow(img) 213 | ax[i, 0].set_title('RS IMAGE ' + img_id) 214 | ax[i, 1].set_axis_off() 215 | ax[i, 1].imshow(mask) 216 | ax[i, 1].set_title('Mask True ' + seg_id) 217 | ax[i, 2].set_axis_off() 218 | ax[i, 2].imshow(img_seg) 219 | ax[i, 2].set_title('Mask Predict ' + seg_id) 220 | ax[i, 2].legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize='large') 221 | 222 | 223 | def show_seg(seg_path, img_path, start_seg_index): 224 | seg_list = os.listdir(seg_path) 225 | seg_list = [f for f in seg_list if f.endswith('.png')] 226 | fig, ax = plt.subplots(2, 2, figsize=(12, 12)) 227 | seg_list = seg_list[start_seg_index:start_seg_index+2] 228 | patches = [mpatches.Patch(color=np.array(PALETTE[i])/255., label=CLASSES[i]) for i in range(len(CLASSES))] 229 | for i in range(len(seg_list)): 230 | seg_id = seg_list[i] 231 | img_seg = cv2.imread(f'{seg_path}/{seg_id}', cv2.IMREAD_UNCHANGED) 232 | img_seg = img_seg.astype(np.uint8) 233 | img_seg = Image.fromarray(img_seg).convert('P') 234 | img_seg.putpalette(np.array(PALETTE, dtype=np.uint8)) 235 | img_seg = np.array(img_seg.convert('RGB')) 236 | img_id = str(seg_id.split('.')[0])+'.tif' 237 | img = cv2.imread(f'{img_path}/{img_id}', cv2.IMREAD_COLOR) 238 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 239 | ax[i, 0].set_axis_off() 240 | ax[i, 0].imshow(img) 241 | ax[i, 0].set_title('RS IMAGE '+img_id) 242 | ax[i, 1].set_axis_off() 243 | ax[i, 1].imshow(img_seg) 244 | ax[i, 1].set_title('Seg IMAGE '+seg_id) 245 | ax[i, 1].legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize='large') 246 | 247 | 248 | def show_mask(img, mask, img_id): 249 | fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 12)) 250 | patches = [mpatches.Patch(color=np.array(PALETTE[i])/255., label=CLASSES[i]) for i in range(len(CLASSES))] 251 | mask = mask.astype(np.uint8) 252 | mask = Image.fromarray(mask).convert('P') 253 | mask.putpalette(np.array(PALETTE, dtype=np.uint8)) 254 | mask = np.array(mask.convert('RGB')) 255 | ax1.imshow(img) 256 | ax1.set_title('RS IMAGE ' + str(img_id)+'.tif') 257 | ax2.imshow(mask) 258 | ax2.set_title('Mask ' + str(img_id)+'.png') 259 | ax2.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize='large') 260 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |