synapse_net.training.transform
1import numpy as np 2import torch 3import torch_em 4from bioimage_cpp.distance import distance_transform 5from torch_em.transform.label import labels_to_binary 6from scipy.ndimage import distance_transform_edt 7 8from synapse_net.inference.mitochondria import remove_white_patches 9 10# The voxel size of the cristae training data, in nanometer. 11CRISTAE_VOXEL_SIZE = (1.74, 1.74, 1.74) 12 13 14class AZDistanceLabelTransform: 15 def __init__(self, max_distance: float = 50.0): 16 self.max_distance = max_distance 17 18 def __call__(self, input_): 19 binary_target = labels_to_binary(input_).astype("float32") 20 if binary_target.sum() == 0: 21 distances = np.ones_like(binary_target, dtype="float32") 22 else: 23 distances = distance_transform_edt(binary_target == 0) 24 distances = np.clip(distances, 0.0, self.max_distance) 25 distances /= self.max_distance 26 return np.stack([binary_target, distances]) 27 28 29def standardize_channel(raw: np.ndarray, channel: int = 0) -> np.ndarray: 30 """Standardize one channel of a multi-channel input and leave the other channels unchanged. 31 32 Args: 33 raw: The input data, with the channels in the first axis. 34 channel: The channel to standardize. 35 36 Returns: 37 The input data with the given channel standardized. 38 """ 39 if raw.ndim != 4: 40 raise ValueError(f"Expect input data with 4 dimensions (channels, z, y, x), got {raw.ndim}.") 41 raw = np.float32(raw) 42 raw[channel] = torch_em.transform.raw.standardize(raw[channel]) 43 return raw 44 45 46def _membrane_weight(state, foreground, voxel_size, band_nm, offset_nm, w_pos, w_neg, exclude_state_value): 47 """Weight the loss in a band at the membrane of the annotated mitochondria. 48 49 The membrane is approximated by the surface of the annotated mitochondria. They are padded in 'edge' mode, 50 so that a mitochondrion cut by the patch border continues instead of getting a band through its lumen. 51 """ 52 # Zero in the mitochondria without cristae annotations, one everywhere else (including the background). 53 weight = (np.abs(state - exclude_state_value) >= 0.5).astype(np.float32) 54 mito = state == 1 55 if (w_pos == 1.0 and w_neg == 1.0) or not mito.any(): 56 return weight 57 58 upper = offset_nm + band_nm 59 pad = int(np.ceil(upper / min(voxel_size))) + 2 60 distances = distance_transform(np.pad(mito, pad, mode="edge"), sampling=list(voxel_size), number_of_threads=1) 61 distances = distances[tuple(slice(pad, -pad) for _ in range(mito.ndim))] 62 band = mito & (distances > offset_nm) & (distances <= upper) 63 64 foreground = foreground > 0 65 weight[band & foreground] *= np.float32(w_pos) 66 weight[band & ~foreground] *= np.float32(w_neg) 67 return weight 68 69 70class AugmentedMitoStateMaskTransform: 71 """Joint transform that augments the data and appends the loss mask for cristae training to the labels. 72 73 The loss mask is computed from the mitochondria state channel of the augmented raw data. It is zero in the 74 mitochondria without cristae annotations (the state `exclude_state_value`) and one elsewhere. Inside of a band 75 at the membrane of the annotated mitochondria (state 1) it is `w_pos` for cristae and `w_neg` for the rest. 76 The labels are returned with twice their channels, as expected by 77 `synapse_net.training.loss.MaskedDiceLossPerSample`. 78 79 Args: 80 augmentation: The joint augmentation, e.g. `torch_em.transform.get_augmentations(3)`. 81 mito_channel: The channel of the raw data that holds the mitochondria state. 82 exclude_state_value: The state of the mitochondria without cristae annotations. 83 band_nm: The thickness of the membrane band in nanometer. 84 offset_nm: Start the band this far inside the membrane. 85 w_pos: The weight for cristae voxels inside the band. 86 w_neg: The weight for the other voxels inside the band. 87 voxel_size: The voxel size in nanometer, in the order (z, y, x). 88 """ 89 90 def __init__( 91 self, 92 augmentation, 93 mito_channel: int = 1, 94 exclude_state_value: float = 2.0, 95 band_nm: float = 12.0, 96 offset_nm: float = 0.0, 97 w_pos: float = 1.0, 98 w_neg: float = 1.0, 99 voxel_size=CRISTAE_VOXEL_SIZE, 100 ): 101 self.augmentation = augmentation 102 self.mito_channel = mito_channel 103 self.exclude_state_value = float(exclude_state_value) 104 self.band_nm = float(band_nm) 105 self.offset_nm = float(offset_nm) 106 self.w_pos = float(w_pos) 107 self.w_neg = float(w_neg) 108 self.voxel_size = tuple(float(vs) for vs in voxel_size) 109 110 def __call__(self, raw, labels): 111 """Augment the raw data and labels, then append the loss mask to the labels. 112 113 Args: 114 raw: The raw data, with the mitochondria state in `mito_channel`. 115 labels: The labels produced by the label transform, with the binary cristae in the first channel. 116 117 Returns: 118 The augmented raw data. 119 The augmented labels with the loss mask appended to the channel axis. 120 """ 121 # The augmentations return the data with a leading batch axis. 122 raw, labels = self.augmentation(raw, labels) 123 raw, labels = torch.as_tensor(raw), torch.as_tensor(labels) 124 state = raw[:, self.mito_channel].float().numpy() 125 foreground = labels[:, 0].numpy() 126 mask = np.stack([ 127 _membrane_weight(s, f, self.voxel_size, self.band_nm, self.offset_nm, self.w_pos, self.w_neg, 128 self.exclude_state_value) 129 for s, f in zip(state, foreground) 130 ]) 131 mask = torch.as_tensor(mask).to(labels.dtype) 132 masks = mask.unsqueeze(1).repeat(1, labels.shape[1], *([1] * (labels.dim() - 2))) 133 return raw, torch.cat([labels, masks], dim=1) 134 135 136class RemoveWhitePatchesAndNormalize: 137 """Raw transform of the volume EM mitochondria model: `remove_white_patches`, then percentile normalization. 138 139 This is a class so that dataloader workers and checkpoints can pickle it. 140 141 Args: 142 min_size: The minimal size (in voxels) of a filler component that is removed. 143 lower: The lower percentile for the normalization. 144 upper: The upper percentile for the normalization. 145 """ 146 147 def __init__(self, min_size: int = 20, lower: float = 1.0, upper: float = 99.0): 148 self.min_size = min_size 149 self.lower = lower 150 self.upper = upper 151 152 def __call__(self, raw: np.ndarray) -> np.ndarray: 153 raw = remove_white_patches(raw, min_size=self.min_size) 154 return torch_em.transform.raw.normalize_percentile(raw, lower=self.lower, upper=self.upper)
15class AZDistanceLabelTransform: 16 def __init__(self, max_distance: float = 50.0): 17 self.max_distance = max_distance 18 19 def __call__(self, input_): 20 binary_target = labels_to_binary(input_).astype("float32") 21 if binary_target.sum() == 0: 22 distances = np.ones_like(binary_target, dtype="float32") 23 else: 24 distances = distance_transform_edt(binary_target == 0) 25 distances = np.clip(distances, 0.0, self.max_distance) 26 distances /= self.max_distance 27 return np.stack([binary_target, distances])
30def standardize_channel(raw: np.ndarray, channel: int = 0) -> np.ndarray: 31 """Standardize one channel of a multi-channel input and leave the other channels unchanged. 32 33 Args: 34 raw: The input data, with the channels in the first axis. 35 channel: The channel to standardize. 36 37 Returns: 38 The input data with the given channel standardized. 39 """ 40 if raw.ndim != 4: 41 raise ValueError(f"Expect input data with 4 dimensions (channels, z, y, x), got {raw.ndim}.") 42 raw = np.float32(raw) 43 raw[channel] = torch_em.transform.raw.standardize(raw[channel]) 44 return raw
Standardize one channel of a multi-channel input and leave the other channels unchanged.
Arguments:
- raw: The input data, with the channels in the first axis.
- channel: The channel to standardize.
Returns:
The input data with the given channel standardized.
71class AugmentedMitoStateMaskTransform: 72 """Joint transform that augments the data and appends the loss mask for cristae training to the labels. 73 74 The loss mask is computed from the mitochondria state channel of the augmented raw data. It is zero in the 75 mitochondria without cristae annotations (the state `exclude_state_value`) and one elsewhere. Inside of a band 76 at the membrane of the annotated mitochondria (state 1) it is `w_pos` for cristae and `w_neg` for the rest. 77 The labels are returned with twice their channels, as expected by 78 `synapse_net.training.loss.MaskedDiceLossPerSample`. 79 80 Args: 81 augmentation: The joint augmentation, e.g. `torch_em.transform.get_augmentations(3)`. 82 mito_channel: The channel of the raw data that holds the mitochondria state. 83 exclude_state_value: The state of the mitochondria without cristae annotations. 84 band_nm: The thickness of the membrane band in nanometer. 85 offset_nm: Start the band this far inside the membrane. 86 w_pos: The weight for cristae voxels inside the band. 87 w_neg: The weight for the other voxels inside the band. 88 voxel_size: The voxel size in nanometer, in the order (z, y, x). 89 """ 90 91 def __init__( 92 self, 93 augmentation, 94 mito_channel: int = 1, 95 exclude_state_value: float = 2.0, 96 band_nm: float = 12.0, 97 offset_nm: float = 0.0, 98 w_pos: float = 1.0, 99 w_neg: float = 1.0, 100 voxel_size=CRISTAE_VOXEL_SIZE, 101 ): 102 self.augmentation = augmentation 103 self.mito_channel = mito_channel 104 self.exclude_state_value = float(exclude_state_value) 105 self.band_nm = float(band_nm) 106 self.offset_nm = float(offset_nm) 107 self.w_pos = float(w_pos) 108 self.w_neg = float(w_neg) 109 self.voxel_size = tuple(float(vs) for vs in voxel_size) 110 111 def __call__(self, raw, labels): 112 """Augment the raw data and labels, then append the loss mask to the labels. 113 114 Args: 115 raw: The raw data, with the mitochondria state in `mito_channel`. 116 labels: The labels produced by the label transform, with the binary cristae in the first channel. 117 118 Returns: 119 The augmented raw data. 120 The augmented labels with the loss mask appended to the channel axis. 121 """ 122 # The augmentations return the data with a leading batch axis. 123 raw, labels = self.augmentation(raw, labels) 124 raw, labels = torch.as_tensor(raw), torch.as_tensor(labels) 125 state = raw[:, self.mito_channel].float().numpy() 126 foreground = labels[:, 0].numpy() 127 mask = np.stack([ 128 _membrane_weight(s, f, self.voxel_size, self.band_nm, self.offset_nm, self.w_pos, self.w_neg, 129 self.exclude_state_value) 130 for s, f in zip(state, foreground) 131 ]) 132 mask = torch.as_tensor(mask).to(labels.dtype) 133 masks = mask.unsqueeze(1).repeat(1, labels.shape[1], *([1] * (labels.dim() - 2))) 134 return raw, torch.cat([labels, masks], dim=1)
Joint transform that augments the data and appends the loss mask for cristae training to the labels.
The loss mask is computed from the mitochondria state channel of the augmented raw data. It is zero in the
mitochondria without cristae annotations (the state exclude_state_value) and one elsewhere. Inside of a band
at the membrane of the annotated mitochondria (state 1) it is w_pos for cristae and w_neg for the rest.
The labels are returned with twice their channels, as expected by
synapse_net.training.loss.MaskedDiceLossPerSample.
Arguments:
- augmentation: The joint augmentation, e.g.
torch_em.transform.get_augmentations(3). - mito_channel: The channel of the raw data that holds the mitochondria state.
- exclude_state_value: The state of the mitochondria without cristae annotations.
- band_nm: The thickness of the membrane band in nanometer.
- offset_nm: Start the band this far inside the membrane.
- w_pos: The weight for cristae voxels inside the band.
- w_neg: The weight for the other voxels inside the band.
- voxel_size: The voxel size in nanometer, in the order (z, y, x).
91 def __init__( 92 self, 93 augmentation, 94 mito_channel: int = 1, 95 exclude_state_value: float = 2.0, 96 band_nm: float = 12.0, 97 offset_nm: float = 0.0, 98 w_pos: float = 1.0, 99 w_neg: float = 1.0, 100 voxel_size=CRISTAE_VOXEL_SIZE, 101 ): 102 self.augmentation = augmentation 103 self.mito_channel = mito_channel 104 self.exclude_state_value = float(exclude_state_value) 105 self.band_nm = float(band_nm) 106 self.offset_nm = float(offset_nm) 107 self.w_pos = float(w_pos) 108 self.w_neg = float(w_neg) 109 self.voxel_size = tuple(float(vs) for vs in voxel_size)
137class RemoveWhitePatchesAndNormalize: 138 """Raw transform of the volume EM mitochondria model: `remove_white_patches`, then percentile normalization. 139 140 This is a class so that dataloader workers and checkpoints can pickle it. 141 142 Args: 143 min_size: The minimal size (in voxels) of a filler component that is removed. 144 lower: The lower percentile for the normalization. 145 upper: The upper percentile for the normalization. 146 """ 147 148 def __init__(self, min_size: int = 20, lower: float = 1.0, upper: float = 99.0): 149 self.min_size = min_size 150 self.lower = lower 151 self.upper = upper 152 153 def __call__(self, raw: np.ndarray) -> np.ndarray: 154 raw = remove_white_patches(raw, min_size=self.min_size) 155 return torch_em.transform.raw.normalize_percentile(raw, lower=self.lower, upper=self.upper)
Raw transform of the volume EM mitochondria model: remove_white_patches, then percentile normalization.
This is a class so that dataloader workers and checkpoints can pickle it.
Arguments:
- min_size: The minimal size (in voxels) of a filler component that is removed.
- lower: The lower percentile for the normalization.
- upper: The upper percentile for the normalization.