OSCR

Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL.

Code ↔ Paper

6 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 6 matches
  1. [1] § Methods › Custom DNN architectures: 2D HRNetV2 ↔ biapy/data/post_processing/post_processing.py, lines 121–202 · score 0.87 · foreground probability map, binary foreground, controlled watershed, instance seeds, foreground mask, surface
  2. [2] § Methods › Custom DNN architectures: 2D HRNetV2 ↔ biapy/models/blocks.py, lines 1717–1858 · score 0.85 · High Resolution Network, high resolution representations, HRNet, ReLU, convolutional layer, downsampling
  3. [3] § Methods › Custom DNN architectures: 2D HRNetV2 ↔ biapy/models/hrnet.py, lines 42–123 · score 0.79 · lower resolution branches, high resolution branch, parallel branches, HRNet, exchanges, ReLU
  4. [4] § Methods › Custom DNN architectures: 2D HRNetV2 ↔ biapy/config/config.py, lines 309–355 · score 0.79 · topographic surface, controlled watershed, instance seeds, foreground mask, overlapping, instance segmentation
  5. [5] § Methods › Custom DNN architectures: 2D HRNetV2 ↔ biapy/data/generators/pair_base_data_generator.py, lines 39–400 · score 0.69 · vertical flips, elastic transformations, brightness, horizontal, zoom, loss
  6. [6] § Methods › Custom DNN architectures: 2D HRNetV2 ↔ biapy/config/config.py, lines 1387–1446 · score 0.67 · vertical flips, elastic transformations, brightness, horizontal, zoom, augmentation

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 2,662 lines · 195 KB · MIT · 2 matches

  1. """
  2. Configuration management for BiaPy.
  3. This module defines the Config class, which encapsulates all configuration options
  4. for BiaPy workflows using a YACS CfgNode. It provides default values and hierarchical
  5. organization for system, data, augmentation, model, loss, training, inference,
  6. post-processing, and logging parameters. Utility functions are included for updating
  7. dependent configuration variables after merging user-provided configs.
  8. """
  9. import os
  10. from yacs.config import CfgNode as CN
  11. import copy
  12. from typing import (
  13. Dict,
  14. )
  15. class Config:
  16. """
  17. BiaPy configuration handler.
  18. This class manages the hierarchical configuration for BiaPy experiments,
  19. including system resources, problem specification, data loading, augmentation,
  20. model architecture, loss functions, training, inference, post-processing, and
  21. logging. It uses YACS CfgNode for flexible and robust configuration management.
  22. Attributes
  23. ----------
  24. _C : CN
  25. The root YACS configuration node containing all experiment parameters.
  26. """
  27. def __init__(self, job_dir: str, job_identifier: str):
  28. """
  29. Initialize the Config object with default values.
  30. Parameters
  31. ----------
  32. job_dir : str
  33. Directory where job outputs (results, checkpoints, logs) will be stored.
  34. job_identifier : str
  35. Unique identifier for the job (used in output paths).
  36. """
  37. if "/" in job_identifier:
  38. raise ValueError("Job name can not contain / character. Provided: {}".format(job_identifier))
  39. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  40. # Config definition
  41. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  42. _C = CN()
  43. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  44. # 1. System
  45. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  46. _C.SYSTEM = CN()
  47. # Maximum number of CPUs to use. Set it to "-1" to not set a limit.
  48. _C.SYSTEM.NUM_CPUS = -1
  49. # Maximum number of workers to use. You can disable this option by setting 0. With a -1 the workers are calculated automatically.
  50. # They are the processes that prepare the data (reading, cropping and normalizing it) in parallel with the GPU work, one
  51. # set of them per process, i.e. per GPU. In the "by chunks" inference each of them fills one tile of the workflow process
  52. # at a time, so they multiply the RAM the tiles take (see 'TEST.BY_CHUNKS.WORKFLOW_PROCESS.PATCHES_PER_TILE'): lower this
  53. # value, or raise it, to trade reading speed for the memory that bigger tiles need.
  54. _C.SYSTEM.NUM_WORKERS = -1
  55. # Do not set it as its value will be calculated based in --gpu input arg
  56. _C.SYSTEM.NUM_GPUS = 0
  57. # Device to be used when GPU is NOT selected. Most commonly "cpu", but also potentially "mps",
  58. # "xpu", "xla" or "meta".
  59. _C.SYSTEM.DEVICE = "cpu"
  60. # Math seed to generate random numbers. Used to ensure reproducibility in the results.
  61. _C.SYSTEM.SEED = 0
  62. # Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.
  63. _C.SYSTEM.PIN_MEM = True
  64. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  65. # 2. Problem specification
  66. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  67. _C.PROBLEM = CN()
  68. # Whether to check what changed to adapt the given input configuration to the newest. Basically to now what
  69. # biapy.engine.check_configuration file's convert_old_model_cfg_to_current_version() function changes
  70. _C.PROBLEM.PRINT_OLD_KEY_CHANGES = True
  71. # Possible options: 'SEMANTIC_SEG', 'INSTANCE_SEG', 'DETECTION', 'DENOISING', 'SUPER_RESOLUTION',
  72. # 'SELF_SUPERVISED', 'CLASSIFICATION' and 'IMAGE_TO_IMAGE'
  73. _C.PROBLEM.TYPE = "SEMANTIC_SEG"
  74. # Possible options: '2D' and '3D'
  75. _C.PROBLEM.NDIM = "2D"
  76. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  77. # 2.1 Semantic segmentation problem specification
  78. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  79. _C.PROBLEM.SEMANTIC_SEG = CN()
  80. # Class id to ignore when DATA.N_CLASSES > 2
  81. _C.PROBLEM.SEMANTIC_SEG.IGNORE_CLASS_ID = 0
  82. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  83. # 2.2 Instance segmentation problem specification
  84. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  85. _C.PROBLEM.INSTANCE_SEG = CN()
  86. # Type of instances expected. Options are: ["regular", "synapses"]
  87. _C.PROBLEM.INSTANCE_SEG.TYPE = "regular"
  88. #### For "regular" type of instances ####
  89. # This variable defines the channels to be used to represent the instances. The approach follows a bottom-up setting,
  90. # where the intermediate representations of the instances are learned by the model and then fused to create the final
  91. # instances. The variable needs to be a list with the representations to be extracted from the instances.
  92. # These are the options available:
  93. # - 'F' stands for 'Foreground', it is a binary representation of each instance
  94. # - 'B' stands for 'Background', it is a binary representation of the background, i.e. everything that is not an instance.
  95. # - 'P' stands for 'Central part', the extreme case of the F channel, where only the center of mass, or the skeleton is
  96. # represented. It may also be expressed as a heatmap.
  97. # - 'C' stands for 'Contour', it is a binary representation of the countours of each instance.
  98. # - 'H' stands for 'Horizontal distance' (HoVer-Net style). For each instance, the pixel/voxel value is the signed
  99. # horizontal displacement to the centroid. When 'norm' is True (default) values are rescaled to [-1, 1]: leftmost
  100. # pixel of the cell = -1, rightmost = +1, centroid column = 0. Background pixels are always 0.
  101. # - 'V' stands for 'Vertical distance' (HoVer-Net style), same as 'H' along the vertical axis:
  102. # top pixel = -1, bottom pixel = +1, centroid row = 0. Background = 0.
  103. # - 'Z' stands for 'Depth distance' (HoVer-Net style), same as 'H' along the depth (z) axis. Only relevant for 3D data.
  104. # - 'Gh', 'Gv', and 'Gz' stand for the x/y/z components of a flow field derived from a heat-diffusion potential
  105. # (Cellpose strategy) or the per-cell EDT gradient (Omnipose strategy). Each component is a unit vector in [-1, 1];
  106. # background is (0, 0[, 0]). Inspired by "Cellpose: a generalist algorithm for cellular segmentation"
  107. # (https://www.nature.com/articles/s41592-020-01018-x) and "Omnipose" (https://www.nature.com/articles/s41467-022-32267-2).
  108. # - 'Db' stands for 'Distance to the boundary'. For each foreground pixel the value is its Euclidean distance to
  109. # the nearest background pixel (i.e. intra-cell distance from the cell boundary inward). After per-cell normalization
  110. # ('norm'=True), boundary pixels map to 0 and the innermost pixel maps to 1. Background is always 0.
  111. # - 'Dc' stands for 'Distance to the center'. For each foreground pixel the value is its Euclidean distance to
  112. # the centroid (or skeleton) of its cell. The centroid pixel therefore has Dc = 0 (the minimum, most important value).
  113. # Background is also 0. When 'norm' is True, values are rescaled per-cell to [0, 1].
  114. # - 'Dn' stands for 'Distance to the closest neighbor'. For each foreground pixel the value reflects the proximity to
  115. # the nearest other instance; isolated cells (no neighbor) are assigned 0. Background is 0.
  116. # - 'D' stands for 'signed Distance field'. Foreground pixels hold the positive Euclidean distance to the nearest
  117. # background pixel; background pixels hold the negative distance to the nearest foreground pixel. The field spans
  118. # from negative (deep background) through 0 (boundary) to positive (deep interior). When 'norm' is True (default)
  119. # the field is passed through tanh, mapping all values to (-1, 1). Because both foreground (+) and background (-)
  120. # carry meaningful signal, the loss is computed on all pixels without masking.
  121. # - 'R' stands for 'Radial distance', distances to boundaries measure how far each pixel is from its object's edge along fixed
  122. # radial directions, with StarDist being the most prominent approach.
  123. # - 'T' stands for 'Touching area', where touching regions between instances are highlighted.
  124. # - 'A' stands for 'Affinities' and contains the affinity values for each dimension. Affinities represent images as graphs for
  125. # segmentation, where each voxel is a node connected to neighbors by edges indicating shared object membership. In 3D, nodes
  126. # link along x-, y-, and z-axes, yielding multiple affinity channels, commonly used in connectomics.
  127. # - 'E' stands for 'Embeddings' and contains the embedding vectors for each pixel/voxel. Embedding-based approaches map each
  128. # pixel in an input image to a point in an n-dimensional feature space (typically n=24), referred to as the pixel embedding.
  129. # The goal is to ensure that embeddings from the same instance are close together, while embeddings from different instances
  130. # are well separated. We grouped here all the channels involved in this process
  131. #
  132. #### For "synapse" type of instances ####
  133. # Possible options:
  134. # * 'F_pre' and 'F_post': each one is a binary representation of the presynaptic and postsynaptic sites, respectively.
  135. # * 'F_pre', 'H', 'V', 'Z': 'F_pre' is a binary representation of the presynaptic sites, while 'H', 'V' and 'Z' are the horizontal,
  136. # vertical and depth distances to the closest postsynaptic site, respectively. This setting is inspired by the paper
  137. # "Automatic detection of synaptic partners in a whole-brain Drosophila electron microscopy data set"
  138. # (https://www.nature.com/articles/s41592-021-01183-7).
  139. #
  140. _C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS = ["B", "C"]
  141. # Details for each channel. It must be a list with a unique element: a dict of dicts. The details can be only set for the following channels:
  142. # - 'F' channel. Possible options:
  143. # - 'erosion': int or list of ints, specifies the erosion size applied to the channel. Default: 0
  144. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. Default: 0
  145. # - 'B' channel. Possible options:
  146. # - 'erosion': int or list of ints, specifies the erosion size applied to the channel. Default: 0
  147. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. Default: 0
  148. # - 'P' channel. Possible options:
  149. # - 'type': str, specifies the reference used to define the channel. Options are 'centroid' or 'skeleton'. Default: 'centroid'
  150. # - 'skeleton_mode': str, only used when 'type' is 'skeleton'. Controls how much of the skeleton is kept:
  151. # - 'full': keep the whole skeleton, branching into every protrusion of the instance (default).
  152. # - 'main': prune it down to the main body only, i.e. the longest path through the skeleton (its
  153. # two farthest-apart points and the branch connecting them). Side branches coming from small
  154. # protrusions (e.g. dendritic spines) are discarded, so the channel marks just the main shaft.
  155. # Default: 'full'
  156. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. Default: 1
  157. # - 'erosion': int or list of ints, specifies the erosion size applied to the channel. Useful for thinning skeletons,
  158. # which are typically 2 pixels thick. Default: 0
  159. # - 'C' channel. Possible options:
  160. # - 'mode': str, specifies how contours are generated. Corresponds to the 'mode' argument of the
  161. # find_boundaries function from scikit-image.
  162. # More information at: https://scikit-image.org/docs/stable/api/skimage.segmentation.html#skimage.segmentation.find_boundaries.
  163. # Options are 'thick', 'inner', 'outer', 'subpixel', and 'dense'. The 'dense' option labels as contour
  164. # every pixel that is not part of the foreground. Default: 'thick'
  165. # - 'H', 'V' and 'Z' channels. Possible options:
  166. # - 'norm': bool, specifies whether signed displacements are normalized to [-1, 1] (centroid = 0). Default: True
  167. # - 'act': str, specifies the activation function used in the model's final layer when this channel is selected.
  168. # These channels are signed, so the activation must allow negative values: 'linear' (unbounded) or 'tanh'
  169. # (bounded to [-1, 1], only meaningful with 'norm'=True). Options are 'linear' and 'tanh'. Default: 'linear'
  170. # Note: the loss for H/V/Z is computed over all pixels, not masked to the foreground, so the background
  171. # target (0) also trains the model. That keeps the predictions bounded outside the instances, which the
  172. # instance creation relies on (it min-max normalizes these channels over the whole image).
  173. # - 'Gh', 'Gv' and 'Gz' channels. Possible options:
  174. # - 'gradient_type': str, method to compute the gradients. Options are "cellpose" and "omnipose". Default: "cellpose"
  175. # - 'Db' channel. Possible options:
  176. # - 'val_type': str, to determine how to modify the distance values. Default: 'norm'. Options are:
  177. # - 'raw': to leave the distances as they are calculated.
  178. # - 'norm': to normalize the distances per cell to [0, 1] (boundary → 0, innermost pixel → 1).
  179. # - 'discretize': to discretize the distances into bins.
  180. # - 'act': str, activation function to be used in the last layer of the model when this channel is selected.
  181. # Options are: '', 'linear' and 'sigmoid'. Default: ''.
  182. # - 'mask_values': bool, kept for compatibility but superseded: the loss mask prefers a binary foreground channel
  183. # (F/M/B) to avoid excluding boundary pixels (Db=0). Falls back to (Db > 0) if no binary channel is present. Default: True
  184. # - 'Dc' channel. Possible options:
  185. # - 'type': str, specifies the reference used to calculate the distance. Options are 'centroid' or 'skeleton'.
  186. # Default: 'centroid'
  187. # - 'norm': bool, specifies whether distances are normalized per cell to [0, 1]. Default: True
  188. # - 'mask_values': bool, kept for compatibility but superseded: the loss mask prefers a binary foreground channel
  189. # (F/M/B) to correctly include the centroid pixel (Dc=0). Falls back to (Dc > 0) if no binary channel is present,
  190. # which still misses the centroid — prefer pairing Dc with F, M, or B. Default: True
  191. # - 'Dn' channel. Possible options:
  192. # - 'closing_size': int, specifies the size of the closing operation applied to the combined distance map.
  193. # Default: 0
  194. # - 'norm': bool, specifies whether distances are normalized between 0 and 1. Default: True
  195. # - 'mask_values': bool, kept for compatibility but superseded: the loss mask prefers a binary foreground channel
  196. # (F/M/B) to include isolated cells (Dn=0). Falls back to (Dn > 0) if no binary channel is present. Default: True
  197. # - 'decline_power': int, specifies the power applied to distances to control the rate of decline. Default: 3
  198. # - 'D' channel. Per-instance distance in [-1, 1]: each instance's distance to its own boundary,
  199. # normalized per instance (boundary -> 0, innermost voxel -> 1), with the background set to -1.
  200. # Measuring the distance per instance, instead of on the binary foreground, is what keeps
  201. # touching instances apart, so each one keeps its own peak and they can be used as seeds.
  202. # Possible options:
  203. # - 'act': str, specifies the activation function used in the model's final layer when this channel is selected.
  204. # Options are 'tanh' and 'linear'. Default: 'tanh'
  205. # - 'R' channel. Possible options:
  206. # - 'nrays': int, specifies the number of rays used to represent radial distances.
  207. # Default: 32 for 2D data and 96 for 3D data
  208. # - 'norm': bool, specifies whether distances are normalized between 0 and 1. Default: True
  209. # - 'mask_values': bool, kept for compatibility but superseded: the loss mask prefers a binary foreground channel
  210. # (F/M/B) to avoid excluding near-boundary ray pixels (R≈0). Falls back to (R > 0) if no binary channel is present. Default: True
  211. # - 'T' channel. Possible options:
  212. # - 'thickness': int, specifies the thickness (in pixels) of the touching area. Default: 2
  213. # - 'A' channel. Possible options:
  214. # - 'z_affinities': list of int, specifies offsets along the z axis. Default: [1]
  215. # - 'y_affinities': list of int, specifies offsets along the y axis. Default: [1]
  216. # - 'x_affinities': list of int, specifies offsets along the x axis. Default: [1]
  217. # - 'widen_borders': int, specifies the number of pixels used to widen affinity borders. Default: 1
  218. # Note that 'z_affinities', 'y_affinities', and 'x_affinities' must be lists of equal length: they are
  219. # paired by index, so entry k of each describes one set of neighbour offsets. The resulting channels are
  220. # stored as one (z, y, x) triple per offset index, i.e. interleaved (Az_1, Ay_1, Ax_1, Az_2, Ay_2, Ax_2,
  221. # ...) rather than grouped by axis.
  222. # To reproduce the paper "Superhuman Accuracy on the SNEMI3D Connectomics Challenge", use:
  223. # 'z_affinities': [1, 2, 3, 4], 'y_affinities': [1, 3, 9, 27], and 'x_affinities': [1, 3, 9, 27]
  224. # - 'E' channel. Possible options:
  225. # - 'center_mode': str, specifies the center definition used for Gaussian seeds.
  226. # Options are 'centroid' and 'medoid'. Default: 'centroid'
  227. # - 'medoid_max_points': int, specifies the maximum number of points used when computing the medoid.
  228. # Default: 10000
  229. # For synapse type of instances, the options are:
  230. # - 'F_pre' channel. Possible options:
  231. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. Default: [1,3,3]
  232. # - 'F_post' channel. Possible options:
  233. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. Default: [1,3,3]
  234. # - 'F_cleft' channel. Possible options:
  235. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. Default: [1,3,3]
  236. # - 'H', 'V' and 'Z' channels (synapse mode). Possible options:
  237. # - 'norm': bool, if True signed displacements are normalized to [-1, 1]; if False raw physical distances are kept.
  238. # Default: False (raw distances in physical units for synapse partner offsets)
  239. # - 'act': str, specifies the activation function used in the model's final layer when this channel is selected.
  240. # Options are '', 'linear', and 'sigmoid'. Default: ''
  241. # - 'dilation': int or list of ints, specifies the dilation size applied to the channel. In the case of the synapses this
  242. # will represent the area that will define the distance channels. Default: [3,25,25]
  243. # Note: the loss mask for H/V/Z is derived automatically from a binary foreground channel (F_pre/F_post/F_cleft)
  244. # when one is present; otherwise all pixels are included.
  245. #
  246. # For example:
  247. # DATA_CHANNELS = ['F', 'C']
  248. # DATA_CHANNELS_EXTRA_OPTS = [{'F': {'erosion': 2, 'dilation': 0}, 'C': {'mode': 'inner'}}]
  249. _C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS_EXTRA_OPTS = [{}]
  250. # Losses to be applied to each channel. If not provided, the losses will be set automatically depending on the channel.
  251. # The options are:
  252. # - "bce"/"ce": binary cross entropy. Ref: https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html
  253. # - "l1"/"mae": mean absolute error. Ref: https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html
  254. # - "mse": mean squared error. Ref: https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html
  255. # - "triplet": triplet loss. Ref: https://pytorch.org/docs/stable/generated/torch.nn.TripletMarginLoss.html
  256. _C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS_LOSSES = []
  257. # Whether to apply a rebalancing strategy to the loss function to give more importance to underrepresented pixels within the channels.
  258. # The weights are calculated automatically based on the number of pixels of each class per batch and directly in the loss computation.
  259. # For example, in the case of the "C" channel, which represents the contours of the instances, there are usually much less pixels representing
  260. # contours than pixels representing the background. With this option activated, the loss will give more importance to contour pixels to help
  261. # the model learn better to predict them.
  262. _C.PROBLEM.INSTANCE_SEG.CLASS_REBALANCE_WITHIN_CHANNELS = True
  263. # Information on how the channels are distributed in the model's output heads. It must be a list of list of ints, where each
  264. # inner list contains the number of channels that are going to be predicted in the same head. If not provided, it will be set automatically
  265. # with all the channels in one head, i.e. [DATA_CHANNELS]. For example, if "V", "H" and "Z" channels are in the same head, it is likely
  266. # that they are representing distance maps and therefore the model will be able to learn them together. On the other hand, if "C" channel
  267. # is in a different head than "H", "V" and "Z", it is likely that the model will be able to learn better the contours of the instances
  268. # separately from the distance maps.
  269. _C.PROBLEM.INSTANCE_SEG.CHANNELS_PER_HEAD_INFO = []
  270. # Whether to use a different decoder for each head in the model. The heads are defined by 'CHANNELS_PER_HEAD_INFO',
  271. # so at least two entries are required there. Only supported by: ['unet', 'resunet', 'resunet++', 'seunet',
  272. # 'resunet_se', 'attention_unet', 'unext_v1', 'unext_v2'].
  273. _C.PROBLEM.INSTANCE_SEG.SEPARATED_DECODERS_PER_HEAD = False
  274. # Whether to divide 'MODEL.FEATURE_MAPS' by the number of decoders created when 'SEPARATED_DECODERS_PER_HEAD'
  275. # is enabled. This way the model keeps a number of parameters closer to the one built with just one decoder.
  276. # If False each decoder is built with 'MODEL.FEATURE_MAPS' as they are, so the model will be as many times
  277. # bigger (in its decoder part) as decoders are created. Only used when 'SEPARATED_DECODERS_PER_HEAD' is True.
  278. _C.PROBLEM.INSTANCE_SEG.SEPARATED_DECODERS_DIVIDE_FEATURE_MAPS = False
  279. # Weights to be applied to the channels. Notice that these weights are not applied directly to the loss, but to the predicted channels before
  280. # calculating the loss. The length of the list must be equal to the number of channels.
  281. # Notice that this is different from LOSS.WEIGHTS, which are used to apply weights to different losses.
  282. _C.PROBLEM.INSTANCE_SEG.DATA_CHANNEL_WEIGHTS = (1, 1)
  283. # Whether to add an extra weight map to the loss calculation to focus on the borders between instances. Different weighting maps
  284. # can be defined. Options: ["unet-like", ""]
  285. _C.PROBLEM.INSTANCE_SEG.BORDER_EXTRA_WEIGHTS = ""
  286. # Defines how the instances are created. Options:
  287. # - "watershed" to use watershed algorithm
  288. # - "gradient-flow" to use gradient flow algorithm (Cellpose/Omnipose)
  289. # - "stardist" to use stardist algorithm
  290. # - "embeddings" to use embedding-based clustering algorithms
  291. # - "agglomeration" to oversegment predicted affinities and greedily merge fragments by
  292. # affinity (requires 'PROBLEM.INSTANCE_SEG.DATA_CHANNELS' == ['A']). See
  293. # 'PROBLEM.INSTANCE_SEG.AGGLOMERATION' for its options.
  294. _C.PROBLEM.INSTANCE_SEG.INSTANCE_CREATION_PROCESS = ""
  295. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  296. # 2.2.1 Watershed options for instance segmentation
  297. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  298. # Options for marker-controlled watershed
  299. _C.PROBLEM.INSTANCE_SEG.WATERSHED = CN()
  300. # List of the channels to be used for seed creation. If not provided will be automatically set based on
  301. # 'PROBLEM.INSTANCE_SEG.DATA_CHANNELS'.
  302. _C.PROBLEM.INSTANCE_SEG.WATERSHED.SEED_CHANNELS = []
  303. # Thresholds for the seed channels. If not provided will be automatically set with "auto" for each channel.
  304. # If set it must have same length than 'PROBLEM.INSTANCE_SEG.WATERSHED.SEED_CHANNELS'. Options:
  305. # - A float between 0 and 1 to threshold each channel
  306. # - "auto" to automatically define a value by applying an Otsu thresholding
  307. _C.PROBLEM.INSTANCE_SEG.WATERSHED.SEED_CHANNELS_THRESH = []
  308. # Defines the topographic surface to grow the seeds. If not provided will be automatically set based on
  309. # 'PROBLEM.INSTANCE_SEG.DATA_CHANNELS'. If defined it must be a channel name, e.g. "B" or "C".
  310. _C.PROBLEM.INSTANCE_SEG.WATERSHED.TOPOGRAPHIC_SURFACE_CHANNEL = ""
  311. # Channel to be used for growth mask creation. If not provided will be automatically set based on
  312. # 'PROBLEM.INSTANCE_SEG.DATA_CHANNELS'. Options:
  313. # - A list of channel names, e.g. ["B"], ["C"] or ["B", "C"]. The channels must be in 'PROBLEM.INSTANCE_SEG.DATA_CHANNELS'
  314. # - "auto" to automatically create it based on the selected channels ('PROBLEM.INSTANCE_SEG.DATA_CHANNELS')
  315. _C.PROBLEM.INSTANCE_SEG.WATERSHED.GROWTH_MASK_CHANNELS = []
  316. # Thresholds for the growth mask channels. If not provided will be automatically set with "auto" for each channel.
  317. # If set it must have same length than 'PROBLEM.INSTANCE_SEG.WATERSHED.GROWTH_MASK_CHANNELS'. Options:
  318. # - A float between 0 and 1 to threshold each channel
  319. # - "auto" to automatically define a value depending on the channels provided
  320. _C.PROBLEM.INSTANCE_SEG.WATERSHED.GROWTH_MASK_CHANNELS_THRESH = []
  321. # Sequence of string to determine the morphological filters to apply to instance seeds. They will be done in that order.
  322. # Possible options 'dilate' and 'erode'. E.g. ['erode','dilate'] to erode first and dilate later.
  323. _C.PROBLEM.INSTANCE_SEG.WATERSHED.SEED_MORPH_SEQUENCE = []
  324. # Sequence of ints to determine the radius of the erosion or dilation for instance seeds
  325. _C.PROBLEM.INSTANCE_SEG.WATERSHED.SEED_MORPH_RADIUS = []
  326. # To erode and dilate the foreground mask before using marker controlled watershed. The idea is to remove the small holes
  327. # that may be produced so the instances grow without them
  328. _C.PROBLEM.INSTANCE_SEG.WATERSHED.ERODE_AND_DILATE_GROWTH_MASK = False
  329. # Radius to erode the foreground mask
  330. _C.PROBLEM.INSTANCE_SEG.WATERSHED.FORE_EROSION_RADIUS = 5
  331. # Radius to dilate the foreground mask
  332. _C.PROBLEM.INSTANCE_SEG.WATERSHED.FORE_DILATION_RADIUS = 5
  333. # Whether to save watershed check files
  334. _C.PROBLEM.INSTANCE_SEG.WATERSHED.DATA_CHECK_MW = False
  335. # Size of small objects to be removed before doing watershed
  336. _C.PROBLEM.INSTANCE_SEG.WATERSHED.DATA_REMOVE_SMALL_OBJ_BEFORE = 10
  337. # Whether to remove objects before watershed
  338. _C.PROBLEM.INSTANCE_SEG.WATERSHED.DATA_REMOVE_BEFORE_MW = False
  339. # Whether to apply or not the watershed to create instances slice by slice in a 3D problem. This can solve instances invading
  340. # others if the objects in Z axis overlap too much.
  341. _C.PROBLEM.INSTANCE_SEG.WATERSHED.BY_2D_SLICES = False
  342. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  343. # 2.2.1.1 Affinity agglomeration options for instance segmentation
  344. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  345. # Used when 'PROBLEM.INSTANCE_SEG.INSTANCE_CREATION_PROCESS' is 'agglomeration' (requires
  346. # 'PROBLEM.INSTANCE_SEG.DATA_CHANNELS' == ['A']): oversegment the predicted affinities into
  347. # small fragments via watershed, then greedily merge fragment pairs by a quantile of their
  348. # affinity histogram until the merge threshold is reached. Matches waterz's
  349. # (https://github.com/funkey/waterz) canonical behaviour: only the first short-range
  350. # (z, y, x)/(y, x) affinity triple is used, by both the fragment watershed and the merge
  351. # scoring; any further, longer-range offsets are ignored. See
  352. # biapy/data/post_processing/affinity_agglomeration.py.
  353. _C.PROBLEM.INSTANCE_SEG.AGGLOMERATION = CN()
  354. # Seed threshold for the initial oversegmented fragments (high, so fragments never straddle a
  355. # real instance boundary).
  356. _C.PROBLEM.INSTANCE_SEG.AGGLOMERATION.FRAGMENT_SEED_TH = 0.9
  357. # Growth-mask threshold for those fragments (low, so they cover all foreground with no gaps).
  358. _C.PROBLEM.INSTANCE_SEG.AGGLOMERATION.FRAGMENT_GROWTH_TH = 0.1
  359. # Two fragments merge while their MERGE_QUANTILE-th percentile affinity (short-range triple
  360. # only, see above) is >= this value.
  361. _C.PROBLEM.INSTANCE_SEG.AGGLOMERATION.MERGE_TH = 0.5
  362. # Percentile (0-100) of each fragment pair's affinity histogram used as its merge score.
  363. # 50 = median.
  364. _C.PROBLEM.INSTANCE_SEG.AGGLOMERATION.MERGE_QUANTILE = 50.0
  365. # Minimum supporting voxel-pairs an edge needs before it can trigger a merge. 1 effectively
  366. # disables this.
  367. _C.PROBLEM.INSTANCE_SEG.AGGLOMERATION.MIN_EDGE_VOXELS = 5
  368. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  369. # 2.2.2 Stardist-like post-processing options for instance segmentation
  370. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  371. # Options for stardist-kind instance creation
  372. _C.PROBLEM.INSTANCE_SEG.STARDIST = CN()
  373. # Probability threshold to consider a pixel/voxel as a potential instance center
  374. _C.PROBLEM.INSTANCE_SEG.STARDIST.PROB_THRESH = 0.4
  375. # Non-maximum suppression IoU threshold to filter overlapping instance candidates
  376. _C.PROBLEM.INSTANCE_SEG.STARDIST.NMS_IOU_THRESH = 0.3
  377. # Output stride of the StarDist head per axis (StarDist's 'grid'); post-processing scales candidate
  378. # coordinates by it. BiaPy's U-Net predicts at full resolution, so keep it all-ones; only set >1 if
  379. # the model is changed to emit the maps on a coarser lattice. Empty -> all ones for the given ndim.
  380. _C.PROBLEM.INSTANCE_SEG.STARDIST.GRID = []
  381. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  382. # 2.2.3 Cellpose/Omnipose-like post-processing options for instance segmentation
  383. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  384. # Options for flow-field-based instance creation from Gv/Gh/[Gz] channels.
  385. # Inspired by the work:
  386. # References:
  387. # "Cellpose: a generalist algorithm for cellular segmentation"
  388. # [link]: https://www.nature.com/articles/s41592-020-01018-x
  389. # "Omnipose: a high-precision morphology-independent solution for bacterial cell segmentation"
  390. # [link]: https://www.nature.com/articles/s41592-022-01639-4
  391. # Cellpose vs Omnipose post-processing is selected by the flow channels' gradient strategy
  392. # (DATA_CHANNELS_EXTRA_OPTS[0]['Gv']['gradient_type'], 'cellpose' or 'omnipose'); parameters for
  393. # each live in the CELLPOSE and OMNIPOSE nodes below.
  394. #
  395. # Cellpose post-processing: Euler integration followed by histogram peak detection and 3x3
  396. # expansion, with an optional flow-error check that removes instances whose flow (regenerated
  397. # from the mask) disagrees with the network. Suited for Cellpose-style flows.
  398. _C.PROBLEM.INSTANCE_SEG.CELLPOSE = CN()
  399. # Foreground probability threshold. Pixels/voxels with a predicted foreground probability
  400. # above this value are considered foreground and will be traced through the flow field.
  401. # Applies when a dedicated binary channel ('F', 'M', or 'B') is present in DATA_CHANNELS.
  402. # Matches Cellpose default (cellprob_threshold=0.0 in logit space = sigmoid 0.5).
  403. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.FG_THRESH = 0.5
  404. # Flow-error threshold to discard spurious instances: each mask's flow is regenerated by
  405. # diffusion and compared (mean squared error) against the network flow, removing the fragments
  406. # left by over-segmentation. 0 disables the check. Default 0.4.
  407. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.FLOW_THRESHOLD = 0.4
  408. # Number of Euler integration steps (overridden internally by niter = (DIAMETER / DIAM_MEAN) * 200).
  409. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.N_STEPS = 200
  410. # Expected cell diameter (px) in the TEST data (test time only; training always rescales per
  411. # image). The input is rescaled by DIAM_MEAN / DIAMETER, predicted, and resized back, with
  412. # niter = (DIAMETER / DIAM_MEAN) * 200. DIAMETER == 0 estimates it per image
  413. # (TEST_DOUBLE_INFERENCE), else uses the training-set median. Default: 0.0.
  414. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.DIAMETER = 0.0
  415. # Reference cell diameter (px) the flow model is trained at (30 'cyto', 17 'nuclei'). Both
  416. # training and test rescale cells to this size. Default: 30.0.
  417. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.DIAM_MEAN = 30.0
  418. # Amount of random scale jitter applied on top of the per-image diameter rescale during training
  419. # (data augmentation), mirroring Cellpose's 'scale_range'. Each training patch is scaled by a
  420. # factor drawn as (1 - SCALE_RANGE/2) + SCALE_RANGE * U[0, 1), i.e. uniformly in
  421. # [1 - SCALE_RANGE/2, 1 + SCALE_RANGE/2], and this factor multiplies the DIAM_MEAN / diameter
  422. # normalization. Only applied when training with flow channels; validation/test use the plain
  423. # diameter rescale with no jitter. 0.0 disables the jitter. Matches Cellpose's default for the
  424. # rescale training path (cellpose/train.py: scale_range0 = 0.5 when rescale=True), giving the
  425. # range [0.75, 1.25]. Default: 0.5.
  426. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.SCALE_RANGE = 0.5
  427. # When DIAMETER == 0, estimate each test image's diameter with a cheap first inference pass (on
  428. # one central patch) instead of the training-set median, then rescale the input for the real
  429. # pass. Ignored when DIAMETER > 0, for the by-chunks/Zarr path, and for 'torchvision' models.
  430. # Default: True.
  431. _C.PROBLEM.INSTANCE_SEG.CELLPOSE.TEST_DOUBLE_INFERENCE = True
  432. # Omnipose post-processing: divergence-rescaled, suppressed (step-damped) Euler flow-following
  433. # with the step count derived from the predicted distance field, then DBSCAN clustering of the
  434. # convergence points (a faithful port of Omnipose's compute_masks). Requires a predicted distance
  435. # channel ('Db' with val_type 'omnipose'). Omnipose is diameter-agnostic, so the Cellpose
  436. # DIAMETER/DIAM_MEAN/SCALE_RANGE rescaling does not apply.
  437. _C.PROBLEM.INSTANCE_SEG.OMNIPOSE = CN()
  438. # Foreground threshold on the predicted distance field ('Db'): pixels with distance above this
  439. # are traced (Omnipose's mask_threshold, applied via hysteresis at [MASK_THRESHOLD-1,
  440. # MASK_THRESHOLD]). Default: 0.0.
  441. _C.PROBLEM.INSTANCE_SEG.OMNIPOSE.MASK_THRESHOLD = 0.0
  442. # Flow-error threshold to discard masks whose flow (regenerated from the mask) disagrees with the
  443. # network. 0 disables the check. Matches Omnipose default 0.4.
  444. _C.PROBLEM.INSTANCE_SEG.OMNIPOSE.FLOW_THRESHOLD = 0.4
  445. # Number of Euler integration steps. 0 = automatic (Omnipose derives it from the predicted
  446. # distance field: niter = 2*(ndim+1)*mean(distance)). A positive value overrides it, mirroring
  447. # Omnipose's --niter. Default: 0.
  448. _C.PROBLEM.INSTANCE_SEG.OMNIPOSE.NITER = 0
  449. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  450. # 2.2.4 EmbedSeg-like post-processing options for instance segmentation
  451. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  452. # Options for embedding-based clustering instance creation. They are inspired by the work:
  453. # Reference:
  454. # "EmbedSeg: Embedding-based Instance Segmentation for Biomedical Microscopy Data"
  455. # [link]: https://www.sciencedirect.com/science/article/pii/S1361841522001700
  456. # Code adapted from:
  457. # Embedseg: https://github.com/juglab/EmbedSeg
  458. _C.PROBLEM.INSTANCE_SEG.EMBEDSEG = CN()
  459. # Seediness threshold defining the foreground pixels that get clustered into objects.
  460. _C.PROBLEM.INSTANCE_SEG.EMBEDSEG.FG_THRESH = 0.5
  461. # Seediness threshold a pixel must reach to seed a new object; clustering stops once no
  462. # remaining foreground pixel exceeds it.
  463. _C.PROBLEM.INSTANCE_SEG.EMBEDSEG.SEED_THRESH = 0.9
  464. # Minimum number of foreground pixels required to perform clustering.
  465. _C.PROBLEM.INSTANCE_SEG.EMBEDSEG.MIN_MASK_SUM = 0
  466. # Minimum number of unclustered foreground pixels to continue clustering.
  467. _C.PROBLEM.INSTANCE_SEG.EMBEDSEG.MIN_UNCLUSTERED_SUM = 0
  468. # Size (in pixels) of the canonical coordinate grid used to build the spatial-embedding
  469. # coordinate map, i.e. the per-pixel coordinate step is ``1 / (GRID_SIZE - 1)``. This mirrors
  470. # EmbedSeg's ``n_x = n_y`` (the dataset's max image size) and is decoupled from
  471. # ``DATA.PATCH_SIZE`` on purpose: training patches are treated as slices of this grid so the
  472. # coordinate scale (and hence the sigma initialisation ``s = exp(10)``) matches the original
  473. # regardless of the patch size. The SAME value is used by the loss (training) and the clustering
  474. # (inference). Leave it at -1 to compute it automatically from the dataset's max image size
  475. # (cached to a JSON next to the instance-channel folder, like the Cellpose diameter); set a
  476. # positive value to force it.
  477. _C.PROBLEM.INSTANCE_SEG.EMBEDSEG.GRID_SIZE = -1
  478. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  479. # 2.2.5 Synapse-specific options for instance segmentation
  480. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  481. #### For "synapses" type of instances (only available for 3D H5/Zarr data) ####
  482. _C.PROBLEM.INSTANCE_SEG.SYNAPSES = CN()
  483. # Method to create the points from the synapse prediction (in "F_pre" + "F_post" setting). Options are:
  484. # - 'peak_local_max' to use the skimage.feature.peak_local_max function to create the points
  485. # - 'blob_log' to use the skimage.feature.blob_log function to create the points
  486. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.POINT_CREATION_FUNCTION = "peak_local_max"
  487. # The minimal allowed distance separating peaks. To find the maximum number of peaks, use min_distance=1.
  488. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.PEAK_LOCAL_MAX_MIN_DISTANCE = 1
  489. # Whether the threshold are going to be set as automaticaly (with Otsu thresholding) or manually.
  490. # Options available:
  491. # * 'auto' to decide the threshold to be applied by measuring it with Otsu
  492. # * 'manual' to set a fixed threshold defined by 'PROBLEM.INSTANCE_SEG.SYNAPSES.MIN_TH_TO_BE_PEAK'
  493. # * 'relative_by_patch' to use 'PROBLEM.INSTANCE_SEG.SYNAPSES.MIN_TH_TO_BE_PEAK' but relative to the maximum value in the predicted patch
  494. # data. More info in https://scikit-image.org/docs/0.25.x/api/skimage.feature.html#skimage.feature.peak_local_max and
  495. # https://scikit-image.org/docs/0.23.x/api/skimage.feature.html#skimage.feature.blob_log (see 'threshold_rel' argument description)
  496. # * 'relative' to use 'PROBLEM.INSTANCE_SEG.SYNAPSES.MIN_TH_TO_BE_PEAK' but relative to the maximum value in the whole predicted data.
  497. # More info in https://scikit-image.org/docs/0.25.x/api/skimage.feature.html#skimage.feature.peak_local_max and
  498. # https://scikit-image.org/docs/0.23.x/api/skimage.feature.html#skimage.feature.blob_log (see 'threshold_rel' argument description)
  499. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.TH_TYPE = "auto"
  500. # Minimun value to consider a point as a peak. Corresponds to 'threshold_abs' argument of the function
  501. # 'peak_local_max' of skimage.feature
  502. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.MIN_TH_TO_BE_PEAK = 0.2
  503. # Corresponds to 'exclude_border' argument of 'peak_local_max' or 'blob_log' function of skimage. If True it will exclude
  504. # peaks from the border of the image to avoid partial detection.
  505. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.EXCLUDE_BORDER = False
  506. # Corresponds to 'min_sigma' argument of 'blob_log' function. It is the minimum standard deviation for Gaussian kernel.
  507. # Keep this low to detect smaller blobs. The standard deviations of the Gaussian filter are given for each axis as a
  508. # sequence, or as a single number, in which case it is equal for all axes.
  509. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.BLOB_LOG_MIN_SIGMA = 5
  510. # Corresponds to 'max_sigma' argument of 'blob_log' function. It is the maximum standard deviation for Gaussian kernel.
  511. # Keep this high to detect larger blobs. The standard deviations of the Gaussian filter are given for each axis as a
  512. # sequence, or as a single number, in which case it is equal for all axes.
  513. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.BLOB_LOG_MAX_SIGMA = 10
  514. # Corresponds to 'num_sigma' argument of 'blob_log' function. The number of intermediate values of standard deviations
  515. # to consider between min_sigma and max_sigma.
  516. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.BLOB_LOG_NUM_SIGMA = 2
  517. # For removing close points detected during synapse prediction
  518. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.REMOVE_CLOSE_PRE_POINTS_RADIUS = 0
  519. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.REMOVE_CLOSE_POST_POINTS_RADIUS = 0
  520. # If this is activated the post points will be remove not only looking the distance between them but the must lay in the same mask.
  521. # For creating this mask there can be a few options:
  522. # * Implemented: By creating instances binarizing the predictions (using PROBLEM.INSTANCE_SEG.SYNAPSES.MIN_TH_TO_BE_PEAK) and applying
  523. # a connected-components
  524. # * TODO: by looking at external neuron segmentation
  525. _C.PROBLEM.INSTANCE_SEG.SYNAPSES.REMOVE_CLOSE_POINTS_RADIUS_BY_MASK = False
  526. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  527. # 2.3 Detection problem specification
  528. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  529. _C.PROBLEM.DETECTION = CN()
  530. # Shape of the ellipse that will be used to dilate the central point created from the CSV file. 0 to not dilate and only create a 3x3 square.
  531. # The value is the radius of the ellipse in pixels. If an integer is given, the shape will be a ball with the given side length.
  532. # If a list is given, the shape will be a hyperball with the given side lengths. List order is (y,x) or (z,y,x) for 2D and 3D respectively.
  533. # For example [1, 2, 3] will result in an ellipse with a radius of 1 in the first dimension, 2 in the second and 3 in the third.
  534. _C.PROBLEM.DETECTION.CENTRAL_POINT_DILATION = [2]
  535. _C.PROBLEM.DETECTION.CHECK_POINTS_CREATED = True
  536. # Whether to save watershed check files
  537. _C.PROBLEM.DETECTION.DATA_CHECK_MW = False
  538. # Whether to use a different decoder for each head in the model. Only applicable when 'DATA.N_CLASSES' > 2
  539. # (multi-class detection), where the model has two heads: one for the detection points and one for the class
  540. # predictions. Only supported by: ['unet', 'resunet', 'resunet++', 'seunet', 'resunet_se', 'attention_unet',
  541. # 'unext_v1', 'unext_v2'].
  542. _C.PROBLEM.DETECTION.SEPARATED_DECODERS_PER_HEAD = False
  543. # Whether to divide 'MODEL.FEATURE_MAPS' by the number of decoders created when 'SEPARATED_DECODERS_PER_HEAD'
  544. # is enabled. This way the model keeps a number of parameters closer to the one built with just one decoder.
  545. # If False each decoder is built with 'MODEL.FEATURE_MAPS' as they are, so the model will be as many times
  546. # bigger (in its decoder part) as decoders are created. Only used when 'SEPARATED_DECODERS_PER_HEAD' is True.
  547. _C.PROBLEM.DETECTION.SEPARATED_DECODERS_DIVIDE_FEATURE_MAPS = False
  548. # Whether to apply a rebalancing strategy to the loss function to give more importance to underrepresented pixels within the channels.
  549. # The weights are calculated automatically based on the number of pixels of each class per batch and directly in the loss computation.
  550. # In the specific case of detection, where there are usually much less pixels representing the center of the objects to detect than
  551. # background pixels, with this option activated, the loss will give more importance to the pixels representing the center of the objects
  552. # to help the model learn better to predict them.
  553. _C.PROBLEM.DETECTION.CLASS_REBALANCE_WITHIN_CHANNELS = True
  554. # Weights to be applied to the channels when doing detection with classes. Notice that these weights are not applied directly to the loss,
  555. # but to the predicted channels before calculating the loss. The length of the list must be equal to the number of channels.
  556. # Notice that this is different from LOSS.WEIGHTS, which are used to apply weights to different losses.
  557. _C.PROBLEM.DETECTION.DATA_CHANNEL_WEIGHTS = (1, 1)
  558. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  559. # 2.4 Denoising problem specification
  560. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  561. # Based Noise2Void paper: https://arxiv.org/abs/1811.10980
  562. _C.PROBLEM.DENOISING = CN()
  563. # This variable corresponds to n2v_perc_pix from Noise2Void. It explanation is as follows: for faster training multiple
  564. # pixels per input patch can be manipulated. In our experiments we manipulated about 0.198% of the input pixels per
  565. # patch. For a patch size of 64 by 64 pixels this corresponds to about 8 pixels. This fraction can be tuned via this variable
  566. _C.PROBLEM.DENOISING.N2V_PERC_PIX = 0.198
  567. # This variable corresponds to n2v_manipulator from Noise2Void. Most pixel manipulators will compute the replacement value based
  568. # on a neighborhood and this variable controls how to do that
  569. _C.PROBLEM.DENOISING.N2V_MANIPULATOR = "uniform_withCP"
  570. # This variable corresponds to n2v_neighborhood_radius from Noise2Void. Size of the neighborhood to compute the replacement
  571. _C.PROBLEM.DENOISING.N2V_NEIGHBORHOOD_RADIUS = 5
  572. # To apply a structured mask as is proposed in Noise2Void to alleviate the limitation of the method of not removing effectively
  573. # the structured noise (section 4.4 of their paper).
  574. _C.PROBLEM.DENOISING.N2V_STRUCTMASK = False
  575. # Whether to load ground truth data in denoising
  576. _C.PROBLEM.DENOISING.LOAD_GT_DATA = False
  577. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  578. # 2.4 Super-resolution problem specification
  579. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  580. _C.PROBLEM.SUPER_RESOLUTION = CN()
  581. # Upscaling to be done to the input images on every dimension. Examples: (2,2) in 2D or (2,2,2) in 3D.
  582. _C.PROBLEM.SUPER_RESOLUTION.UPSCALING = ()
  583. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  584. # 2.5 Self-supervised problem specification
  585. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  586. _C.PROBLEM.SELF_SUPERVISED = CN()
  587. # Pretext task to do. Options are as follows:
  588. # - 'crappify': crappifies input image by adding Gaussian noise and downsampling and upsampling it so the resolution
  589. # gets worsen. Then, the model is trained to recover the original images.
  590. # - 'masking': mask input image and the model needs to recover the original image. This option can only
  591. # be done with 'mae' transformer. This strategy follows the one proposed in:
  592. # Masked Autoencoders Are Scalable Vision Learners (https://arxiv.org/pdf/2111.06377.pdf)
  593. _C.PROBLEM.SELF_SUPERVISED.PRETEXT_TASK = "crappify"
  594. # Downsizing factor to reshape the image. It will be downsampled and upsampled again by this factor so the
  595. # quality of the image is worsens
  596. _C.PROBLEM.SELF_SUPERVISED.RESIZING_FACTOR = 4
  597. # Number between [0, 1] indicating the std of the Gaussian noise N(0,std).
  598. _C.PROBLEM.SELF_SUPERVISED.NOISE = 0.2
  599. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  600. # 2.6 Image-to-image problem specification
  601. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  602. _C.PROBLEM.IMAGE_TO_IMAGE = CN()
  603. # Information on how the channels are distributed in the model's output heads. It must be a list of list of ints, where each
  604. # inner list contains the number of channels that are going to be predicted in the same head.
  605. _C.PROBLEM.IMAGE_TO_IMAGE.CHANNELS_PER_HEAD_INFO = []
  606. # Whether to use a different decoder for each head in the model. The heads are defined by 'CHANNELS_PER_HEAD_INFO',
  607. # so at least two entries are required there. Only supported by: ['unet', 'resunet', 'resunet++', 'seunet',
  608. # 'resunet_se', 'attention_unet', 'unext_v1', 'unext_v2'].
  609. _C.PROBLEM.IMAGE_TO_IMAGE.SEPARATED_DECODERS_PER_HEAD = False
  610. # Whether to divide 'MODEL.FEATURE_MAPS' by the number of decoders created when 'SEPARATED_DECODERS_PER_HEAD'
  611. # is enabled. This way the model keeps a number of parameters closer to the one built with just one decoder.
  612. # If False each decoder is built with 'MODEL.FEATURE_MAPS' as they are, so the model will be as many times
  613. # bigger (in its decoder part) as decoders are created. Only used when 'SEPARATED_DECODERS_PER_HEAD' is True.
  614. _C.PROBLEM.IMAGE_TO_IMAGE.SEPARATED_DECODERS_DIVIDE_FEATURE_MAPS = False
  615. # Expected output channels to be predicted by the model.
  616. _C.PROBLEM.IMAGE_TO_IMAGE.OUTPUT_CHANNELS = 1
  617. # To use a custom data loader to load a random image from each image sample folder. The data needs to be structured
  618. # in an special way, that is, instead of having images in the training/val folder a folder for each sample is expected,
  619. # where in each of those different versions of the same data sample will be placed. Visit the following tutorial
  620. # for a real use case and a more detailed description:
  621. # - https://biapy.readthedocs.io/en/latest/tutorials/image-to-image/lightmycells.html
  622. _C.PROBLEM.IMAGE_TO_IMAGE.MULTIPLE_RAW_ONE_TARGET_LOADER = False
  623. # Activation function to be applied to the output channels of the model. It can be a string or a list of strings if
  624. # different activation functions are desired for different channels. Leave empty to use linear activation.
  625. _C.PROBLEM.IMAGE_TO_IMAGE.OUTPUT_CHANNEL_ACT = []
  626. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  627. # 2.6.1 Membrane repair sub-problem (IMAGE_TO_IMAGE)
  628. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  629. # Trains a dataset-agnostic network that repairs membrane-segmentation errors (gaps and
  630. # spurious fragments) coming out of an upstream foundation-model + GMM pipeline. Model input
  631. # is EXCLUSIVELY DERIVED_CHANNELS, computed from SOURCE_CHANNELS (never fed to the model
  632. # directly). Output is affinities learned from GT instance labels. Uses a dedicated data
  633. # generator (Membrane2DRepairDataGenerator/Membrane3DRepairDataGenerator) instead of the
  634. # shared instance-seg/Cellpose/N2V generator.
  635. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR = CN()
  636. # Master switch. When True, PROBLEM.TYPE == "IMAGE_TO_IMAGE" is routed through the dedicated
  637. # membrane-repair data generator and Membrane_Repair_Workflow instead of the regular
  638. # IMAGE_TO_IMAGE_Workflow path.
  639. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ENABLE = False
  640. # Ordered list of the raw, on-disk input channels. Never fed to the model directly -- only
  641. # used to compute DERIVED_CHANNELS (see below). Channels are resolved by name, not
  642. # position, so any order/subset works, e.g. ["membrane"], ["raw"], ["membrane", "raw"] or
  643. # ["raw", "membrane"] ("raw" required whenever 'meijering' is in DERIVED_CHANNELS;
  644. # "membrane" required whenever 'skeleton_dt'/'hessian_blob' are). Any entry that is neither
  645. # "membrane" nor "raw" (e.g. unsupervised per-slice GMM class maps, whose cluster-to-channel
  646. # assignment is not stable across slices) is treated as a "class" channel, folded into the
  647. # single 'class_union' derived channel below -- their names/count/order don't matter beyond
  648. # that, since 'class_union' only takes their per-pixel union.
  649. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SOURCE_CHANNELS = ["membrane", "raw"]
  650. # Ordered list of channels derived on the fly from SOURCE_CHANNELS -- the model's actual
  651. # input; must be non-empty. Options:
  652. # - 'skeleton_dt': clamped Euclidean distance transform of the per-slice membrane skeleton.
  653. # Derived from 'membrane' (required in SOURCE_CHANNELS).
  654. # - 'hessian_blob': Hessian-eigenvalue-based "dense blob" response (mito/synapse/vesicle cue).
  655. # Derived from 'membrane' (required in SOURCE_CHANNELS).
  656. # - 'meijering': standardised multi-scale Meijering ridge filter. Derived from 'raw'
  657. # (required in SOURCE_CHANNELS).
  658. # - 'class_union': per-pixel union (max) of every SOURCE_CHANNELS entry that is not
  659. # 'membrane'/'raw' (at least one such entry required in SOURCE_CHANNELS). Order-
  660. # invariant by construction -- use this instead of feeding per-class channels directly
  661. # whenever the class identity behind each channel isn't stable slice to slice.
  662. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.DERIVED_CHANNELS = ["skeleton_dt", "hessian_blob", "meijering"]
  663. # Per-channel options for DERIVED_CHANNELS. Must be a list with a unique element: a dict of
  664. # dicts, keyed by channel name. Possible options:
  665. # - 'skeleton_dt' channel. Possible options:
  666. # - 'clamp_px': int, clamp distance (in canonical pixels) applied to the DT. Default: 10
  667. # - 'per_slice': bool, whether to skeletonize/derive the DT per z-slice (2D skeleton in a
  668. # 3D stack) rather than on the full 3D volume. Default: True
  669. # - 'hessian_blob' channel. Possible options:
  670. # - 'sigma_range': list of 2 floats, [min, max] Gaussian scales probed for the Hessian.
  671. # Default: [1.0, 3.0]
  672. # - 'meijering' channel. Possible options:
  673. # - 'sigma_range': list of 2 floats, [min, max] Gaussian scales probed for the ridge
  674. # filter. Default: [1.0, 4.0]
  675. # - 'standardize': bool, whether to z-score/percentile-normalize the response for
  676. # cross-dataset comparability. Default: True
  677. # - 'class_union' channel. Possible options:
  678. # - 'threshold': float, threshold applied to each class map before taking the union.
  679. # Default: 0.5
  680. # - identity-passthrough channels (any name matching a SOURCE_CHANNELS entry): no options.
  681. # For example:
  682. # DERIVED_CHANNELS = ['skeleton_dt', 'hessian_blob']
  683. # DERIVED_CHANNELS_EXTRA_OPTS = [{'skeleton_dt': {'clamp_px': 8}, 'hessian_blob': {'sigma_range': [1.0, 2.5]}}]
  684. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.DERIVED_CHANNELS_EXTRA_OPTS = [{}]
  685. # Subset of DERIVED_CHANNELS naming an "exchangeable" group of identity-passthrough class
  686. # channels whose channel-to-semantic mapping isn't stable slice to slice (e.g. per-slice
  687. # GMM cluster ids). When non-empty, this is forwarded to MODEL.STUNET.CLASS_SET_CHANNEL_IDXS
  688. # (translated from names to DERIVED_CHANNELS positions) so the model routes this group
  689. # through a permutation-invariant encoder instead of its regular first layer -- see
  690. # MODEL.STUNET.CLASS_SET_CHANNEL_IDXS's docstring. Only meaningful with MODEL.ARCHITECTURE
  691. # == 'stunet' and MODEL.STUNET.VARIANT == 'custom'. Left empty (default), this is a no-op.
  692. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.CLASS_SET_CHANNELS = []
  693. # Output width and pooling of the CLASS_SET_CHANNELS group's pooled encoding -- forwarded to
  694. # MODEL.STUNET.CLASS_SET_OUT_CHANNELS / CLASS_SET_POOLING. Only used when CLASS_SET_CHANNELS
  695. # is non-empty.
  696. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.CLASS_SET_ENCODER = CN()
  697. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.CLASS_SET_ENCODER.OUT_CHANNELS = 8
  698. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.CLASS_SET_ENCODER.POOLING = 'max'
  699. # Y-side: GT target channels, generated offline from the raw GT instance-label folder via the
  700. # same 'labels_into_channels' machinery INSTANCE_SEG uses (see PROBLEM.INSTANCE_SEG.DATA_CHANNELS
  701. # for the full list of channel letters), then regenerated online after each augmentation warp so
  702. # directional channels never get corrupted by interpolation. Must include 'I' (the virtual raw
  703. # instance-label channel), the regeneration source that is dropped before the batch reaches the
  704. # model -- exactly as INSTANCE_SEG does for its own directional channels. 'A' (affinities) is the
  705. # actual training target.
  706. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.DATA_CHANNELS = ["A", "I"]
  707. # Same shape/semantics as PROBLEM.INSTANCE_SEG.DATA_CHANNELS_EXTRA_OPTS's 'A' entry:
  708. # 'z_affinities'/'y_affinities'/'x_affinities' (paired-by-index neighbour offset lists) and
  709. # 'widen_borders'. E.g. [{'A': {'z_affinities': [1], 'y_affinities': [1], 'x_affinities': [1]}}]
  710. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.DATA_CHANNELS_EXTRA_OPTS = [{}]
  711. # Like PROBLEM.INSTANCE_SEG.CLASS_REBALANCE_WITHIN_CHANNELS, but per affinity offset channel
  712. # instead of pooled across the whole 'A' stack. False = old pooled behavior (reproducibility).
  713. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.CLASS_REBALANCE_WITHIN_CHANNELS = True
  714. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  715. # 2.6.2 Membrane repair test-time post-processing (affinities -> instances)
  716. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  717. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS = CN()
  718. # How to turn predicted affinities into instance labels at test time: 'watershed' or
  719. # 'agglomeration' (see biapy/data/post_processing/affinity_agglomeration.py).
  720. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.METHOD = "agglomeration"
  721. # 'watershed' only: seed threshold for watershed_by_channels's 'A'-only branch.
  722. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.WATERSHED_SEED_TH = 0.5
  723. # 'watershed' only: growth-mask threshold. Equal to WATERSHED_SEED_TH gives plain
  724. # threshold + 3D connected components (no seeded growth).
  725. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.WATERSHED_GROWTH_TH = 0.5
  726. # 'agglomeration' only: seed threshold for the initial oversegmented fragments (high, so
  727. # fragments never straddle a real instance boundary).
  728. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.FRAGMENT_SEED_TH = 0.9
  729. # 'agglomeration' only: growth-mask threshold for those fragments (low, so they cover all
  730. # foreground with no gaps).
  731. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.FRAGMENT_GROWTH_TH = 0.1
  732. # 'agglomeration' only: two fragments merge while their MERGE_QUANTILE-th percentile
  733. # affinity (short-range triple only, see METHOD above) is >= this value.
  734. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.MERGE_TH = 0.5
  735. # 'agglomeration' only: percentile (0-100) of each fragment pair's affinity histogram used
  736. # as its merge score. 50 = median.
  737. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.MERGE_QUANTILE = 50.0
  738. # 'agglomeration' only: minimum supporting voxel-pairs an edge needs before it can trigger a
  739. # merge. 1 effectively disables this.
  740. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.POSTPROCESS.MIN_EDGE_VOXELS = 5
  741. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  742. # 2.6.3 Membrane repair corruption augmentors
  743. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  744. # These synthesize the upstream pipeline's failure modes directly on the membrane source
  745. # channel, so the network learns the repair operation from corrupted -> clean pairs.
  746. # Applied after the geometric warps, before the derived channels are computed.
  747. # PROB is a per-z-slice probability, independently rolled for every slice (2D: probability of
  748. # augmenting the whole image), not a single roll for the whole sample.
  749. #
  750. # Blacks out random bands across the membrane channel (merge error). LENGTH_RANGE: fraction
  751. # (0-1) of border-to-border extent (1.0 = full). THICKNESS_RANGE: pixels. N_LINES: bands
  752. # per slice.
  753. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.GAP_AUG = CN()
  754. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.GAP_AUG.ENABLE = False
  755. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.GAP_AUG.PROB = 0.5
  756. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.GAP_AUG.LENGTH_RANGE = (0.3, 1.0)
  757. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.GAP_AUG.THICKNESS_RANGE = (4, 9)
  758. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.GAP_AUG.N_LINES = (1, 3)
  759. # Inverse of GAP_AUG: paints bands instead of erasing (split error). Same options.
  760. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.BRIDGE_AUG = CN()
  761. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.BRIDGE_AUG.ENABLE = False
  762. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.BRIDGE_AUG.PROB = 0.3
  763. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.BRIDGE_AUG.LENGTH_RANGE = (0.3, 1.0)
  764. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.BRIDGE_AUG.THICKNESS_RANGE = (4, 9)
  765. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.BRIDGE_AUG.N_LINES = (1, 3)
  766. # Heavy acquisition artifact. With probability BAND_PROB: a border-to-border band
  767. # (BAND_THICKNESS_RANGE px) -- membrane channel set to 1 inside it, every other channel
  768. # blacked out; rest of the image untouched. Otherwise: BLOB_N_RANGE ink-blot blobs
  769. # (BLOB_SIZE_RANGE radius, fraction of min(h, w)) blacked out in every channel.
  770. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG = CN()
  771. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG.ENABLE = False
  772. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG.PROB = 0.1
  773. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG.BAND_PROB = 0.5
  774. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG.BAND_THICKNESS_RANGE = (50, 70)
  775. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG.BLOB_SIZE_RANGE = (0.1, 0.3)
  776. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ARTIFACT_AUG.BLOB_N_RANGE = (1, 3)
  777. # Applies a small random dilation/erosion/spur injection to the membrane channel before the
  778. # derived channels are computed, so the model doesn't over-trust exact skeleton geometry.
  779. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SKELETON_PERTURB_AUG = CN()
  780. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SKELETON_PERTURB_AUG.ENABLE = False
  781. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SKELETON_PERTURB_AUG.PROB = 0.3
  782. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SKELETON_PERTURB_AUG.RADIUS_RANGE = (1, 2)
  783. # Zeroes z-slices of each raw source channel (SOURCE_CHANNELS, e.g. membrane or raw)
  784. # independently with probability PROB (see 'slice_dropout' in
  785. # biapy/data/generators/membrane_augmentors.py).
  786. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SLICE_DROPOUT_AUG = CN()
  787. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SLICE_DROPOUT_AUG.ENABLE = False
  788. _C.PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.SLICE_DROPOUT_AUG.PROB = 0.3
  789. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  790. # 3. Dataset
  791. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  792. _C.DATA = CN()
  793. # Save all data of a generator in the given path.
  794. _C.DATA.CHECK_GENERATORS = False
  795. # _C.PROBLEM.NDIM='2D' -> _C.DATA.PATCH_SIZE=(y,x,c) ; _C.PROBLEM.NDIM='3D' -> _C.DATA.PATCH_SIZE=(z,y,x,c)
  796. _C.DATA.PATCH_SIZE = (256, 256, 1)
  797. # Number of classes including the background class (that should be using 0 label)
  798. _C.DATA.N_CLASSES = 2
  799. # Whether to reshape the dimensions that does not satisfy the patch shape selected by padding it with reflect.
  800. _C.DATA.REFLECT_TO_COMPLETE_SHAPE = True
  801. # If 'DATA.PATCH_SIZE' selected has 3 channels, e.g. RGB images are expected, so will force grayscale images to be
  802. # converted into RGB (e.g. in ImageNet some of the images are grayscale)
  803. _C.DATA.FORCE_RGB = False
  804. # If filtering is done, with any of DATA.*.FILTER_SAMPLES.* variables, this will decide how this filtering will be done:
  805. # * True: apply filter image by image.
  806. # * False: apply filtering sample by sample. Each sample represents a patch within an image.
  807. _C.DATA.FILTER_BY_IMAGE = False
  808. # Determines whether to save filtered images. If 'DATA.FILTER_BY_IMAGE' is enabled, two subfolders will be created: one for
  809. # filtered images and another for non-filtered images. Otherwise, no subfolders will be created, and the images will
  810. # display filtered patches as black (all zero values) while retaining original patch values in non-filtered areas.
  811. _C.DATA.SAVE_FILTERED_IMAGES = False
  812. # Number of filtered images to save. Only work when 'DATA.SAVE_FILTERED_IMAGES' is True
  813. _C.DATA.SAVE_FILTERED_IMAGES_NUM = 3
  814. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  815. # 3.1 Normalization options for the data
  816. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  817. _C.DATA.NORMALIZATION = CN()
  818. # Whether to apply or not a percentile clipping before normalizing the data
  819. _C.DATA.NORMALIZATION.PERC_CLIP = CN()
  820. _C.DATA.NORMALIZATION.PERC_CLIP.ENABLE = False
  821. # Lower and upper bound for percentile clip. Must be set when DATA.NORMALIZATION.PERC_CLIP.ENABLE = 'True'
  822. _C.DATA.NORMALIZATION.PERC_CLIP.LOWER_PERC = -1.0
  823. _C.DATA.NORMALIZATION.PERC_CLIP.UPPER_PERC = -1.0
  824. # Lower and upper values to clip. If these are provided the percentiles are not calculated based on
  825. # 'DATA.NORMALIZATION.PERC_CLIP.LOWER_PERC' and 'DATA.NORMALIZATION.PERC_CLIP.UPPER_PERC'
  826. _C.DATA.NORMALIZATION.PERC_CLIP.LOWER_VALUE = [-1.0]
  827. _C.DATA.NORMALIZATION.PERC_CLIP.UPPER_VALUE = [-1.0]
  828. # Normalization type to use. Possible options:
  829. # 'div' to divide values from 0/255 (or 0/65535 if uint16) in [0,1] range
  830. # 'scale_range' same as 'div' but scaling the range to [0-max] and then dividing by the maximum value of the data
  831. # and not by 255 or 65535
  832. # 'zero_mean_unit_variance' to substract the mean and divide by std.
  833. _C.DATA.NORMALIZATION.TYPE = "zero_mean_unit_variance"
  834. # Custom normalization variables: mean and std (they are calculated if not provided)
  835. _C.DATA.NORMALIZATION.ZERO_MEAN_UNIT_VAR = CN()
  836. _C.DATA.NORMALIZATION.ZERO_MEAN_UNIT_VAR.MEAN_VAL = [-1.0]
  837. _C.DATA.NORMALIZATION.ZERO_MEAN_UNIT_VAR.STD_VAL = [-1.0]
  838. # Target/GT-specific normalization (image-to-image style targets only). Off by default = fully
  839. # retrocompatible (target normalized like the input, as before). When enabled, the target is
  840. # normalized with its own FIXED type/mean/std/clip below, and predictions are un-normalized with
  841. # those same fixed values at test time instead of the input's - needed because the input's stats
  842. # are computable at test time (the input always exists) but the target's are not.
  843. _C.DATA.NORMALIZATION.TARGET = CN()
  844. _C.DATA.NORMALIZATION.TARGET.ENABLE = False
  845. # '' reuses 'DATA.NORMALIZATION.TYPE'. Only 'zero_mean_unit_variance' is supported here.
  846. _C.DATA.NORMALIZATION.TARGET.TYPE = ""
  847. _C.DATA.NORMALIZATION.TARGET.PERC_CLIP = CN()
  848. _C.DATA.NORMALIZATION.TARGET.PERC_CLIP.ENABLE = False
  849. # Fixed clip values only (no percentiles - those would need the target image at test time).
  850. _C.DATA.NORMALIZATION.TARGET.PERC_CLIP.LOWER_VALUE = [-1.0]
  851. _C.DATA.NORMALIZATION.TARGET.PERC_CLIP.UPPER_VALUE = [-1.0]
  852. _C.DATA.NORMALIZATION.TARGET.ZERO_MEAN_UNIT_VAR = CN()
  853. # Required (not -1) when 'DATA.NORMALIZATION.TARGET.ENABLE' is True.
  854. _C.DATA.NORMALIZATION.TARGET.ZERO_MEAN_UNIT_VAR.MEAN_VAL = [-1.0]
  855. _C.DATA.NORMALIZATION.TARGET.ZERO_MEAN_UNIT_VAR.STD_VAL = [-1.0]
  856. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  857. # 3.2 Training data options
  858. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  859. _C.DATA.TRAIN = CN()
  860. # Whether to check if the data mask contains correct values, e.g. same classes as defined
  861. _C.DATA.TRAIN.CHECK_DATA = True
  862. _C.DATA.TRAIN.IN_MEMORY = True
  863. _C.DATA.TRAIN.PATH = os.path.join("user_data", "train", "x")
  864. _C.DATA.TRAIN.GT_PATH = os.path.join("user_data", "train", "y")
  865. # Whether your input Zarr contains the raw images and labels together or not. Use 'DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_RAW_PATH'
  866. # and 'DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_GT_PATH' to determine the tag to find within the Zarr
  867. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA = False
  868. # Paths to the raw and gt within the Zarr file. Only used when 'DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA' is True.
  869. # E.g. 'volumes.raw' for raw and 'volumes.labels.neuron_ids' for GT path.
  870. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_RAW_PATH = ""
  871. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_GT_PATH = ""
  872. # For synapse detection. The information must be stored as CREMI dataset (https://cremi.org/data/)
  873. # Path within the file where the ``ids`` are stored. Reference in CREMI: ``annotations/ids``
  874. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_ID_PATH = "annotations.ids"
  875. # Path within the file where the ``types`` are stored (not used). Reference in CREMI: ``annotations/types``
  876. # _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_TYPES_PATH = "annotations.types"
  877. # Path within the file where the ``partners`` are stored. Reference in CREMI: ``annotations/partners``
  878. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_PARTNERS_PATH = "annotations.presynaptic_site.partners"
  879. # Path within the file where the ``locations`` are stored. Reference in CREMI: ``annotations/locations``
  880. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_LOCATIONS_PATH = "annotations.locations"
  881. # Path within the file where the ``resolution`` is stored. Reference in CREMI: ``["volumes/raw"].attrs["offset"]``
  882. _C.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA_RESOLUTION_PATH = 'volumes.raw'
  883. # File to load/save data prepared with the appropiate channels in a instance segmentation problem.
  884. # E.g. _C.PROBLEM.TYPE ='INSTANCE_SEG' and _C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS != 'B'
  885. _C.DATA.TRAIN.INSTANCE_CHANNELS_MASK_DIR = os.path.join(
  886. "user_data", "train", "y_" + "".join(_C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS)
  887. )
  888. # Path to load/save detection masks prepared.
  889. _C.DATA.TRAIN.DETECTION_MASK_DIR = os.path.join("user_data", "train", "y_detection_masks")
  890. # Path to load/save SSL target prepared.
  891. _C.DATA.TRAIN.SSL_SOURCE_DIR = os.path.join("user_data", "train", "x_ssl_source")
  892. # Extract random patches during data augmentation (DA)
  893. _C.DATA.TRAIN.EXTRACT_RANDOM_PATCH = False
  894. # Create a probability map so the patches extracted will have a high probability of having an object in the middle
  895. # of it. Useful to avoid extracting patches which no foreground class information. Use it only when
  896. # 'PROBLEM.TYPE' is 'SEMANTIC_SEG', 'INSTANCE_SEG' or 'DETECTION'
  897. _C.DATA.TRAIN.PROBABILITY_MAP = False # Used when _C.DATA.TRAIN.EXTRACT_RANDOM_PATCH=True
  898. _C.DATA.TRAIN.W_FOREGROUND = 0.94 # Used when _C.DATA.TRAIN.PROBABILITY_MAP=True
  899. _C.DATA.TRAIN.W_BACKGROUND = 0.06 # Used when _C.DATA.TRAIN.PROBABILITY_MAP=True
  900. # Extra train data generation: number of times to duplicate the train data. Useful when
  901. # _C.DATA.TRAIN.EXTRACT_RANDOM_PATCH=True is made, as more original train data can be cover on each epoch
  902. _C.DATA.TRAIN.REPLICATE = 0
  903. # Percentage of overlap in (y,x)/(z,y,x) when cropping validation. Set to 0 to calculate the minimun overlap.
  904. # The values must be floats between range [0, 1). It needs to be a 2D tuple when using _C.PROBLEM.NDIM='2D' and
  905. # 3D tuple when using _C.PROBLEM.NDIM='3D'
  906. _C.DATA.TRAIN.OVERLAP = (0, 0)
  907. # Padding to be done in (y,x)/(z,y,x) when reconstructing train data. Useful to avoid patch 'border effect'.
  908. _C.DATA.TRAIN.PADDING = (0, 0)
  909. # Train data resolution. It is not completely necessary but when configured it is taken into account when
  910. # performing some augmentations, e.g. cutout. If defined it need to be (y,x)/(z,y,x) and needs to be to be a 2D
  911. # tuple when using _C.PROBLEM.NDIM='2D' and 3D tuple when using _C.PROBLEM.NDIM='3D'
  912. _C.DATA.TRAIN.RESOLUTION = (-1,)
  913. # Order of the axes of the image when using Zarr/H5 images in train data.
  914. _C.DATA.TRAIN.INPUT_IMG_AXES_ORDER = "TZCYX"
  915. # Order of the axes of the mask when using Zarr/H5 images in train data.
  916. _C.DATA.TRAIN.INPUT_MASK_AXES_ORDER = "TZCYX"
  917. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  918. # 3.2.1 Training data filtering options
  919. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  920. # DATA.TRAIN.FILTER_SAMPLES allows removing training images by the conditions based on their properties. When using Zarr each patch within the Zarr will be
  921. # processed and will not depend on 'DATA.FILTER_BY_IMAGE' variable.
  922. # Its three variables (PROPS, VALUES and SIGNS) define a set of conditions to remove the images from the training set. If an image satisfies any of the
  923. # conditions, the image won't be used for training.
  924. #
  925. # In PROPS, we define the property to look at to establish the condition. The available properties are: ['foreground', 'mean', 'min', 'max',
  926. # 'target_mean', 'target_min', 'target_max', 'diff', 'diff_by_min_max_ratio', 'diff_by_target_min_max_ratio'].
  927. #
  928. # * 'foreground' is defined as the percentage of pixels/voxels corresponding to the foreground mask. This option is only valid for
  929. # SEMANTIC_SEG, INSTANCE_SEG and DETECTION.
  930. # * 'mean' is defined as the mean intensity value of the raw image inputs.
  931. # * 'min' is defined as the min intensity value of the raw image inputs.
  932. # * 'max' is defined as the max intensity value of the raw image inputs.
  933. # * 'diff' is defined as the difference between ground truth and raw images. Available for all workflows but SELF_SUPERVISED and DENOISING.
  934. # * 'diff_by_min_max_ratio' is defined as the difference between ground truth and raw images multiplied by the ratio between raw image max and min. Available for all workflows but SELF_SUPERVISED and DENOISING.
  935. # * 'target_mean' is defined as the mean intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  936. # * 'target_min' is defined as the min intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  937. # * 'target_max' is defined as the max intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  938. # * 'diff_by_target_min_max_ratio' is defined as the difference between ground truth and raw images multiplied by the ratio between ground truth image max and min. Available for all workflows but SELF_SUPERVISED and DENOISING.
  939. #
  940. # With VALUES and SIGNS, we define the specific values and the comparison operators of each property, respectively.
  941. # The available operators are: ['gt', 'ge', 'lt', 'le'], that corresponds to "greather than" (or ">"), "greather equal" (or ">="), "less than" (or "<"),
  942. # and "less equal" (or "<=").
  943. #
  944. # Here you have a full example of this filtering:
  945. # If you want to remove those samples that have intensity values lower than 0.00001 and a mean average greater than 100 you should
  946. # declare the above three variables as follows (notice you need to know the image data type in advance):
  947. # _C.DATA.TRAIN.FILTER_SAMPLES.PROPS = [['foreground','mean']]
  948. # _C.DATA.TRAIN.FILTER_SAMPLES.VALUES = [[0.00001, 100]]
  949. # _C.DATA.TRAIN.FILTER_SAMPLES.SIGNS = [['lt', 'gt']]
  950. # You can also concatenate more restrictions and they will be applied in order. For instance, if you want to filter those
  951. # samples with a maximum intensity value greater than 1000, and do that before the condition described above, you can define the
  952. # variables this way:
  953. # _C.DATA.TRAIN.FILTER_SAMPLES.PROPS = [['max'], ['foreground','mean']]
  954. # _C.DATA.TRAIN.FILTER_SAMPLES.VALUES = [[1000], [0.00001, 100]]
  955. # _C.DATA.TRAIN.FILTER_SAMPLES.SIGNS = [['gt'], ['lt', 'gt']]
  956. # This way, the images will be removed by 'max' and then by 'foreground' and 'mean'
  957. _C.DATA.TRAIN.FILTER_SAMPLES = CN()
  958. # Whether to enable or not the filtering by properties
  959. _C.DATA.TRAIN.FILTER_SAMPLES.ENABLE = False
  960. # List of lists of properties to apply a filter. Available properties are: ['foreground', 'mean', 'min', 'max',
  961. # 'target_mean', 'target_min', 'target_max', 'diff', 'diff_by_min_max_ratio', 'diff_by_target_min_max_ratio']
  962. _C.DATA.TRAIN.FILTER_SAMPLES.PROPS = []
  963. # List of ints/float that represent the values of the properties listed in 'DATA.TRAIN.FILTER_SAMPLES.PROPS'
  964. # that the images need to satisfy to not be dropped.
  965. _C.DATA.TRAIN.FILTER_SAMPLES.VALUES = []
  966. # List of list of signs to do the comparison. Options: ['gt', 'ge', 'lt', 'le'] that corresponds to "greather than", e.g. ">",
  967. # "greather equal", e.g. ">=", "less than", e.g. "<", and "less equal" e.g. "<=" comparisons.
  968. _C.DATA.TRAIN.FILTER_SAMPLES.SIGNS = []
  969. # Whether to normalize the samples before comparison
  970. _C.DATA.TRAIN.FILTER_SAMPLES.NORM_BEFORE = False
  971. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  972. # 3.3 Validation data options
  973. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  974. _C.DATA.VAL = CN()
  975. # Enabling distributed evaluation (recommended during training)
  976. _C.DATA.VAL.DIST_EVAL = True
  977. # Whether to create validation data from training set or read it from a directory
  978. _C.DATA.VAL.FROM_TRAIN = True
  979. # Use a cross validation strategy instead of just split the train data in two
  980. _C.DATA.VAL.CROSS_VAL = False
  981. # Number of folds. Used when _C.DATA.VAL.CROSS_VAL == True
  982. _C.DATA.VAL.CROSS_VAL_NFOLD = 5
  983. # Number of the fold to choose as validation. Used when _C.DATA.VAL.CROSS_VAL == True
  984. _C.DATA.VAL.CROSS_VAL_FOLD = 1
  985. # Percentage of the training data used as validation. Used when _C.DATA.VAL.FROM_TRAIN = True and _C.DATA.VAL.CROSS_VAL == False
  986. _C.DATA.VAL.SPLIT_TRAIN = 0.1
  987. # Create the validation data with random images of the training data. Used when _C.DATA.VAL.FROM_TRAIN = True
  988. _C.DATA.VAL.RANDOM = True
  989. # Used when _C.DATA.VAL.FROM_TRAIN = False, as DATA.VAL.FROM_TRAIN = True always implies DATA.VAL.IN_MEMORY = True
  990. _C.DATA.VAL.IN_MEMORY = True
  991. # Path to the validation data. Used when _C.DATA.VAL.FROM_TRAIN = False
  992. _C.DATA.VAL.PATH = os.path.join("user_data", "val", "x")
  993. # Path to the validation data mask. Used when _C.DATA.VAL.FROM_TRAIN = False
  994. _C.DATA.VAL.GT_PATH = os.path.join("user_data", "val", "y")
  995. # Whether your input Zarr contains the raw images and labels together or not. Use 'DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_RAW_PATH'
  996. # and 'DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_GT_PATH' to determine the tag to find within the Zarr
  997. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA = False
  998. # Paths to the raw and gt within the Zarr file. Only used when 'DATA.VAL.INPUT_ZARR_MULTIPLE_DATA' is True.
  999. # E.g. 'volumes.raw' for raw and 'volumes.labels.neuron_ids' for GT path.
  1000. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_RAW_PATH = ""
  1001. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_GT_PATH = ""
  1002. # For synapse detection. The information must be stored as CREMI dataset (https://cremi.org/data/)
  1003. # Path within the file where the ``ids`` are stored. Reference in CREMI: ``annotations/ids``
  1004. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_ID_PATH = "annotations.ids"
  1005. # Path within the file where the ``types`` are stored (not used). Reference in CREMI: ``annotations/types``
  1006. # _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_TYPES_PATH = "annotations.types"
  1007. # Path within the file where the ``partners`` are stored. Reference in CREMI: ``annotations/partners``
  1008. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_PARTNERS_PATH = "annotations.presynaptic_site.partners"
  1009. # Path within the file where the ``locations`` are stored. Reference in CREMI: ``annotations/locations``
  1010. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_LOCATIONS_PATH = "annotations.locations"
  1011. # Path within the file where the ``resolution`` is stored. Reference in CREMI: ``["volumes/raw"].attrs["offset"]``
  1012. _C.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA_RESOLUTION_PATH = 'volumes.raw'
  1013. # File to load/save data prepared with the appropiate channels in a instance segmentation problem.
  1014. # E.g. _C.PROBLEM.TYPE ='INSTANCE_SEG' and _C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS != 'B'
  1015. _C.DATA.VAL.INSTANCE_CHANNELS_MASK_DIR = os.path.join(
  1016. "user_data", "val", "y_" + "".join(_C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS)
  1017. )
  1018. # Path to load/save detection masks prepared.
  1019. _C.DATA.VAL.DETECTION_MASK_DIR = os.path.join("user_data", "val", "y_detection_masks")
  1020. # Path to load/save SSL target prepared.
  1021. _C.DATA.VAL.SSL_SOURCE_DIR = os.path.join("user_data", "val", "x_ssl_source")
  1022. # Percentage of overlap in (y,x)/(z,y,x) when cropping validation. Set to 0 to calculate the minimun overlap.
  1023. # The values must be floats between range [0, 1). It needs to be a 2D tuple when using _C.PROBLEM.NDIM='2D' and
  1024. # 3D tuple when using _C.PROBLEM.NDIM='3D'. This is only used when the validation is loaded from disk, and thus,
  1025. # not extracted from training.
  1026. _C.DATA.VAL.OVERLAP = (0, 0)
  1027. # Padding to be done in (y,x)/(z,y,x) when cropping validation data. Useful to avoid patch 'border effect'. This
  1028. # is only used when the validation is loaded from disk, and thus, not extracted from training.
  1029. _C.DATA.VAL.PADDING = (0, 0)
  1030. # Not used yet.
  1031. _C.DATA.VAL.RESOLUTION = (-1,)
  1032. # Order of the axes of the image when using Zarr/H5 images in validation data.
  1033. _C.DATA.VAL.INPUT_IMG_AXES_ORDER = "TZCYX"
  1034. # Order of the axes of the mask when using Zarr/H5 images in validation data.
  1035. _C.DATA.VAL.INPUT_MASK_AXES_ORDER = "TZCYX"
  1036. # Remove validation images by the conditions based on their properties. When using Zarr each patch within the Zarr will be processed and will
  1037. # not depend on 'DATA.FILTER_BY_IMAGE' variable
  1038. # The three variables, DATA.VAL.FILTER_SAMPLES.PROPS, DATA.VAL.FILTER_SAMPLES.VALUES and DATA.VAL.FILTER_SAMPLES.SIGNS will compose a list of
  1039. # conditions to remove the images. They are list of list of conditions. For instance, the conditions can be like this: [['A'], ['B','C']]. Then,
  1040. # if the image satisfies the first list of conditions, only 'A' in this first case (from ['A'] list), or satisfy 'B' and 'C' (from ['B','C'] list)
  1041. # it will be removed from the image. In each sublist all the conditions must be satisfied. Available properties are: ['foreground', 'mean', 'min', 'max',
  1042. # 'target_mean', 'target_min', 'target_max', 'diff', 'diff_by_min_max_ratio', 'diff_by_target_min_max_ratio'].
  1043. #
  1044. # Each property descrition:
  1045. # * 'foreground' is defined as the percentage of pixels/voxels corresponding to the foreground mask. This option is only valid for
  1046. # SEMANTIC_SEG, INSTANCE_SEG and DETECTION.
  1047. # * 'mean' is defined as the mean intensity value of the raw image inputs.
  1048. # * 'min' is defined as the min intensity value of the raw image inputs.
  1049. # * 'max' is defined as the max intensity value of the raw image inputs.
  1050. # * 'diff' is defined as the difference between ground truth and raw images. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1051. # * 'diff_by_min_max_ratio' is defined as the difference between ground truth and raw images multiplied by the ratio between raw image max and min. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1052. # * 'target_mean' is defined as the mean intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1053. # * 'target_min' is defined as the min intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1054. # * 'target_max' is defined as the max intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1055. # * 'diff_by_target_min_max_ratio' is defined as the difference between ground truth and raw images multiplied by the ratio between ground truth image max and min. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1056. #
  1057. # A full example of this filtering:
  1058. # If you want to remove those samples that have less than 0.00001 and a mean average more than 100 (you need to know image data type) you should
  1059. # declare the above three variables as follows:
  1060. # _C.DATA.VAL.FILTER_SAMPLES.PROPS = [['foreground','mean']]
  1061. # _C.DATA.VAL.FILTER_SAMPLES.VALUES = [[0.00001, 100]]
  1062. # _C.DATA.VAL.FILTER_SAMPLES.SIGNS = [['lt', 'gt']]
  1063. # You can also concatenate more restrictions and they will be applied in order. For instance, if you want to filter those
  1064. # samples with a max value more than 1000, and do that before the condition described above, you can define the
  1065. # variables this way:
  1066. # _C.DATA.VAL.FILTER_SAMPLES.PROPS = [['max'], ['foreground','mean']]
  1067. # _C.DATA.VAL.FILTER_SAMPLES.VALUES = [[1000], [0.00001, 100]]
  1068. # _C.DATA.VAL.FILTER_SAMPLES.SIGNS = [['gt'], ['lt', 'gt']]
  1069. # This way, the images will be removed by 'max' and then by 'foreground' and 'mean'
  1070. _C.DATA.VAL.FILTER_SAMPLES = CN()
  1071. # Whether to enable or not the filtering by properties
  1072. _C.DATA.VAL.FILTER_SAMPLES.ENABLE = False
  1073. # List of lists of properties to apply a filter. Available properties are: ['foreground', 'mean', 'min', 'max',
  1074. # 'target_mean', 'target_min', 'target_max', 'diff', 'diff_by_min_max_ratio', 'diff_by_target_min_max_ratio']
  1075. _C.DATA.VAL.FILTER_SAMPLES.PROPS = []
  1076. # List of ints/float that represent the values of the properties listed in 'DATA.VAL.FILTER_SAMPLES.PROPS'
  1077. # that the images need to satisfy to not be dropped.
  1078. _C.DATA.VAL.FILTER_SAMPLES.VALUES = []
  1079. # List of list of signs to do the comparison. Options: ['gt', 'ge', 'lt', 'le'] that corresponds to "greather than", e.g. ">",
  1080. # "greather equal", e.g. ">=", "less than", e.g. "<", and "less equal" e.g. "<=" comparisons.
  1081. _C.DATA.VAL.FILTER_SAMPLES.SIGNS = []
  1082. # Whether to normalize the samples before comparison
  1083. _C.DATA.VAL.FILTER_SAMPLES.NORM_BEFORE = False
  1084. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1085. # 3.4 Test data options
  1086. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1087. _C.DATA.TEST = CN()
  1088. # Whether to check if the data mask contains correct values, e.g. same classes as defined
  1089. _C.DATA.TEST.CHECK_DATA = True
  1090. _C.DATA.TEST.IN_MEMORY = False
  1091. # Whether to load ground truth (GT)
  1092. _C.DATA.TEST.LOAD_GT = False
  1093. # Whether to use validation data as test instead of trying to load test from _C.DATA.TEST.PATH and
  1094. # _C.DATA.TEST.GT_PATH. _C.DATA.VAL.CROSS_VAL needs to be True.
  1095. _C.DATA.TEST.USE_VAL_AS_TEST = False
  1096. # Path to load the test data from. Not used when _C.DATA.TEST.USE_VAL_AS_TEST == True
  1097. _C.DATA.TEST.PATH = os.path.join("user_data", "test", "x")
  1098. # Path to load the test data masks from. Not used when _C.DATA.TEST.USE_VAL_AS_TEST == True
  1099. _C.DATA.TEST.GT_PATH = os.path.join("user_data", "test", "y")
  1100. # File to load/save data prepared with the appropiate channels in a instance segmentation problem.
  1101. # E.g. _C.PROBLEM.TYPE ='INSTANCE_SEG' and _C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS != 'B'
  1102. _C.DATA.TEST.INSTANCE_CHANNELS_MASK_DIR = os.path.join(
  1103. "user_data", "test", "y_" + "".join(_C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS)
  1104. )
  1105. # Path to load/save detection masks prepared.
  1106. _C.DATA.TEST.DETECTION_MASK_DIR = os.path.join("user_data", "test", "y_detection_masks")
  1107. # Path to load/save SSL target prepared.
  1108. _C.DATA.TEST.SSL_SOURCE_DIR = os.path.join("user_data", "test", "x_ssl_source")
  1109. # Percentage of overlap in (y,x)/(z,y,x) when cropping validation. Set to 0 to calculate the minimun overlap.
  1110. # The values must be floats between range [0, 1). It needs to be a 2D tuple when using _C.PROBLEM.NDIM='2D' and
  1111. # 3D tuple when using _C.PROBLEM.NDIM='3D'
  1112. _C.DATA.TEST.OVERLAP = (0, 0)
  1113. # Padding to be done in (y,x)/(z,y,xz) when reconstructing test data. Useful to avoid patch 'border effect'
  1114. _C.DATA.TEST.PADDING = (0, 0)
  1115. # Whether to use median values to fill padded pixels or zeros
  1116. _C.DATA.TEST.MEDIAN_PADDING = False
  1117. # Region of interest (ROI) mask restricting where the inference is done. Anything greater than 0 in the mask is
  1118. # ROI. With 'TEST.BY_CHUNKS.ENABLE' the patches not overlapping the ROI are not predicted, and are left as
  1119. # background in the output Zarr; otherwise the prediction is zeroed outside the ROI. The mask does not need to
  1120. # have the same shape as the test image: it is mapped to it by scaling each axis, so a coarse mask (e.g. one
  1121. # voxel per 64x64x64 block) is enough.
  1122. _C.DATA.TEST.ROI_MASK = CN()
  1123. # Whether to restrict the inference to the ROI mask
  1124. _C.DATA.TEST.ROI_MASK.ENABLE = False
  1125. # Path to the ROI mask. It can be a file (used for all the test samples) or a directory. In a directory, if only one
  1126. # mask is found it is used for all the test samples, otherwise the mask named as the test sample is used for it.
  1127. _C.DATA.TEST.ROI_MASK.PATH = ""
  1128. # Order of the axes of the ROI mask. Leave it empty to use the axes order of the test image:
  1129. # 'DATA.TEST.INPUT_IMG_AXES_ORDER' when reading Zarr/H5 by chunks and 'ZYX'/'YX' otherwise.
  1130. _C.DATA.TEST.ROI_MASK.AXES_ORDER = ""
  1131. # Test data resolution. Need to be provided in (z,y,x) order. Only applies when _C.PROBLEM.TYPE = 'DETECTION' now.
  1132. _C.DATA.TEST.RESOLUTION = (-1,)
  1133. # Whether to read the per-image test resolution from a 'resolution.json' file placed in the parent
  1134. # folder of 'DATA.TEST.PATH' (a mapping of image basename -> (z, y, x) resolution) instead of using
  1135. # 'DATA.TEST.RESOLUTION'. Images missing from the JSON fall back to 'DATA.TEST.RESOLUTION'.
  1136. _C.DATA.TEST.RESOLUTION_FROM_JSON = False
  1137. # Order of the axes of the image when using Zarr/H5 images in test data.
  1138. _C.DATA.TEST.INPUT_IMG_AXES_ORDER = "TZCYX"
  1139. # Order of the axes of the mask when using Zarr/H5 images in test data.
  1140. _C.DATA.TEST.INPUT_MASK_AXES_ORDER = "TZCYX"
  1141. # Whether your input Zarr contains the raw images and labels together or not. Use 'DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_RAW_PATH'
  1142. # and 'DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_GT_PATH' to determine the tag to find within the Zarr
  1143. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA = False
  1144. # Paths to the raw and gt within the Zarr file. Only used when 'DATA.TEST.INPUT_ZARR_MULTIPLE_DATA' is True.
  1145. # E.g. 'volumes.raw' for raw and 'volumes.labels.neuron_ids' for GT path.
  1146. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_RAW_PATH = ""
  1147. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_GT_PATH = ""
  1148. # For synapse detection. The information must be stored as CREMI dataset (https://cremi.org/data/)
  1149. # Path within the file where the ``ids`` are stored. Reference in CREMI: ``annotations/ids``
  1150. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_ID_PATH = "annotations.ids"
  1151. # Path within the file where the ``types`` are stored (not used). Reference in CREMI: ``annotations/types``
  1152. # _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_TYPES_PATH = "annotations.types"
  1153. # Path within the file where the ``partners`` are stored. Reference in CREMI: ``annotations/partners``
  1154. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_PARTNERS_PATH = "annotations.presynaptic_site.partners"
  1155. # Path within the file where the ``locations`` are stored. Reference in CREMI: ``annotations/locations``
  1156. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_LOCATIONS_PATH = "annotations.locations"
  1157. # Path within the file where the ``resolution`` is stored. Reference in CREMI: ``["volumes/raw"].attrs["offset"]``
  1158. _C.DATA.TEST.INPUT_ZARR_MULTIPLE_DATA_RESOLUTION_PATH = 'volumes.raw'
  1159. # Remove test images by the conditions based on their properties. When using Zarr each patch within the Zarr will be processed and will
  1160. # not depend on 'DATA.FILTER_BY_IMAGE' variable
  1161. # The three variables, DATA.TEST.FILTER_SAMPLES.PROPS, DATA.TEST.FILTER_SAMPLES.VALUES and DATA.TEST.FILTER_SAMPLES.SIGNS will compose a
  1162. # list of conditions to remove the images. They are list of list of conditions. For instance, the conditions can be like this: [['A'], ['B','C']].
  1163. # Then, if the image satisfies the first list of conditions, only 'A' in this first case (from ['A'] list), or satisfy 'B' and 'C' (from ['B','C'] list)
  1164. # it will be removed from the image. In each sublist all the conditions must be satisfied. Available properties are: ['foreground', 'mean', 'min', 'max',
  1165. # 'target_mean', 'target_min', 'target_max', 'diff', 'diff_by_min_max_ratio', 'diff_by_target_min_max_ratio'].
  1166. #
  1167. # Each property descrition:
  1168. # * 'foreground' is defined as the percentage of pixels/voxels corresponding to the foreground mask. This option is only valid for
  1169. # SEMANTIC_SEG, INSTANCE_SEG and DETECTION.
  1170. # * 'mean' is defined as the mean intensity value of the raw image inputs.
  1171. # * 'min' is defined as the min intensity value of the raw image inputs.
  1172. # * 'max' is defined as the max intensity value of the raw image inputs.
  1173. # * 'diff' is defined as the difference between ground truth and raw images. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1174. # * 'diff_by_min_max_ratio' is defined as the difference between ground truth and raw images multiplied by the ratio between raw image max and min. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1175. # * 'target_mean' is defined as the mean intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1176. # * 'target_min' is defined as the min intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1177. # * 'target_max' is defined as the max intensity value of the raw image targets. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1178. # * 'diff_by_target_min_max_ratio' is defined as the difference between ground truth and raw images multiplied by the ratio between ground truth image max and min. Available for all workflows but SELF_SUPERVISED and DENOISING.
  1179. #
  1180. #
  1181. # A full example of this filtering:
  1182. # If you want to remove those samples that have less than 0.00001 and a mean average more than 100 (you need to know image data type) you should
  1183. # declare the above three variables as follows:
  1184. # _C.DATA.TEST.FILTER_SAMPLES.PROPS = [['foreground','mean']]
  1185. # _C.DATA.TEST.FILTER_SAMPLES.VALUES = [[0.00001, 100]]
  1186. # _C.DATA.TEST.FILTER_SAMPLES.SIGNS = [['lt', 'gt']]
  1187. # You can also concatenate more restrictions and they will be applied in order. For instance, if you want to filter those
  1188. # samples with a max value more than 1000, and do that before the condition described above, you can define the
  1189. # variables this way:
  1190. # _C.DATA.TEST.FILTER_SAMPLES.PROPS = [['max'], ['foreground','mean']]
  1191. # _C.DATA.TEST.FILTER_SAMPLES.VALUES = [[1000], [0.00001, 100]]
  1192. # _C.DATA.TEST.FILTER_SAMPLES.SIGNS = [['gt'], ['lt', 'gt']]
  1193. # This way, the images will be removed by 'max' and then by 'foreground' and 'mean'
  1194. _C.DATA.TEST.FILTER_SAMPLES = CN()
  1195. # Whether to enable or not the filtering by properties
  1196. _C.DATA.TEST.FILTER_SAMPLES.ENABLE = False
  1197. # List of lists of properties to apply a filter. Available properties are: ['foreground', 'mean', 'min', 'max',
  1198. # 'target_mean', 'target_min', 'target_max', 'diff', 'diff_by_min_max_ratio', 'diff_by_target_min_max_ratio']
  1199. _C.DATA.TEST.FILTER_SAMPLES.PROPS = []
  1200. # List of ints/float that represent the values of the properties listed in 'DATA.TEST.FILTER_SAMPLES.PROPS'
  1201. # that the images need to satisfy to not be dropped.
  1202. _C.DATA.TEST.FILTER_SAMPLES.VALUES = []
  1203. # List of list of signs to do the comparison. Options: ['gt', 'ge', 'lt', 'le'] that corresponds to "greather than", e.g. ">",
  1204. # "greather equal", e.g. ">=", "less than", e.g. "<", and "less equal" e.g. "<=" comparisons.
  1205. _C.DATA.TEST.FILTER_SAMPLES.SIGNS = []
  1206. # Whether to normalize the samples before comparison
  1207. _C.DATA.TEST.FILTER_SAMPLES.NORM_BEFORE = False
  1208. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1209. # 3.5 Pre-processing data options
  1210. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1211. # Same preprocessing will be applied to all selected datasets
  1212. _C.DATA.PREPROCESS = CN()
  1213. # Apply preprocessing to training dataset
  1214. _C.DATA.PREPROCESS.TRAIN = False
  1215. # Apply preprocessing to validation dataset
  1216. _C.DATA.PREPROCESS.VAL = False
  1217. # Apply preprocessing to testing dataset
  1218. _C.DATA.PREPROCESS.TEST = False
  1219. # Resize datasets
  1220. _C.DATA.PREPROCESS.RESIZE = CN()
  1221. _C.DATA.PREPROCESS.RESIZE.ENABLE = False
  1222. # Desired resize size. when using 3D data, size must be also in 3D (ex. (512,512,512))
  1223. _C.DATA.PREPROCESS.RESIZE.OUTPUT_SHAPE = (512, 512)
  1224. # interpolation order: {0: Nearest-neighbor, 1: Bi-linear (default), 2: Bi-quadratic, 3: Bi-cubic, 4: Bi-quartic, 5: Bi-quintic}
  1225. _C.DATA.PREPROCESS.RESIZE.ORDER = 1
  1226. # Points outside the boundaries of the input are filled according to the given mode: {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}
  1227. _C.DATA.PREPROCESS.RESIZE.MODE = "reflect"
  1228. # Used in conjunction with mode 'constant', the value outside the image boundaries.
  1229. _C.DATA.PREPROCESS.RESIZE.CVAL = 0.0
  1230. # Whether to clip the output to the range of values of the input image.
  1231. _C.DATA.PREPROCESS.RESIZE.CLIP = True
  1232. # Whether to keep the original range of values.
  1233. _C.DATA.PREPROCESS.RESIZE.PRESERVE_RANGE = True
  1234. # Whether to apply a Gaussian filter to smooth the image prior to downsampling.
  1235. _C.DATA.PREPROCESS.RESIZE.ANTI_ALIASING = False
  1236. # Zoom datasets.
  1237. _C.DATA.PREPROCESS.ZOOM = CN()
  1238. _C.DATA.PREPROCESS.ZOOM.ENABLE = False
  1239. # WARNING: Only implemented for _C.TEST.BY_CHUNKS = True. It will change the zoom of each patch individually.
  1240. # This is useful when the input image has a different resolution than the one used in the training. The value
  1241. # is the zoom factor to be applied to each patch using scipy.ndimage.zoom.
  1242. # "E.g. [1,2,1,3,3] that needs to match _C.DATA.TEST.INPUT_IMG_AXES_ORDER axes"
  1243. _C.DATA.PREPROCESS.ZOOM.ZOOM_FACTOR = [1, 1, 1, 1, 1]
  1244. # Gaussian blur
  1245. _C.DATA.PREPROCESS.GAUSSIAN_BLUR = CN()
  1246. _C.DATA.PREPROCESS.GAUSSIAN_BLUR.ENABLE = False
  1247. # Standard deviation for Gaussian kernel.
  1248. _C.DATA.PREPROCESS.GAUSSIAN_BLUR.SIGMA = 1
  1249. # The mode parameter determines how the array borders are handled: {'reflect', 'constant', 'nearest', 'mirror', 'wrap'} 'constant' value = 0
  1250. _C.DATA.PREPROCESS.GAUSSIAN_BLUR.MODE = "nearest"
  1251. # If None, the image is assumed to be a grayscale (single channel) image.
  1252. # Otherwise, this parameter indicates which axis of the array corresponds to channels.
  1253. _C.DATA.PREPROCESS.GAUSSIAN_BLUR.CHANNEL_AXIS = None
  1254. # Median blur
  1255. _C.DATA.PREPROCESS.MEDIAN_BLUR = CN()
  1256. _C.DATA.PREPROCESS.MEDIAN_BLUR.ENABLE = False
  1257. # Desired kernel size (including channels). When using 3D data, size must be also in 3D (ex. (3,7,7,1) for (z,y,x,c))
  1258. _C.DATA.PREPROCESS.MEDIAN_BLUR.KERNEL_SIZE = (3,3,1)
  1259. # Histogram matching. More info at: https://en.wikipedia.org/wiki/Histogram_matching
  1260. _C.DATA.PREPROCESS.MATCH_HISTOGRAM = CN()
  1261. _C.DATA.PREPROCESS.MATCH_HISTOGRAM.ENABLE = False
  1262. # the path of the reference images, from which the reference histogram will be extracted
  1263. _C.DATA.PREPROCESS.MATCH_HISTOGRAM.REFERENCE_PATH = os.path.join("user_data", "test", "x")
  1264. # Contrast Limited Adaptive Histogram Equalization. More info at: https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE
  1265. _C.DATA.PREPROCESS.CLAHE = CN()
  1266. _C.DATA.PREPROCESS.CLAHE.ENABLE = False
  1267. # Defines the shape of contextual regions used in the algorithm.
  1268. # By default, kernel_size is 1/8 of image height by 1/8 of its width.
  1269. _C.DATA.PREPROCESS.CLAHE.KERNEL_SIZE = None
  1270. # Clipping limit, normalized between 0 and 1 (higher values give more contrast).
  1271. _C.DATA.PREPROCESS.CLAHE.CLIP_LIMIT = 0.01
  1272. # Canny or edge detection (only 2D - grayscale or RGB)
  1273. _C.DATA.PREPROCESS.CANNY = CN()
  1274. _C.DATA.PREPROCESS.CANNY.ENABLE = False
  1275. # Lower bound for hysteresis thresholding (linking edges). If None, low_threshold is set to 10% of dtype's max.
  1276. _C.DATA.PREPROCESS.CANNY.LOW_THRESHOLD = None
  1277. # Upper bound for hysteresis thresholding (linking edges). If None, high_threshold is set to 20% of dtype's max.
  1278. _C.DATA.PREPROCESS.CANNY.HIGH_THRESHOLD = None
  1279. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1280. # 4. Data augmentation (DA)
  1281. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1282. _C.AUGMENTOR = CN()
  1283. # Flag to activate DA
  1284. _C.AUGMENTOR.ENABLE = False
  1285. # Per-augmentation probability of being applied (each in [0, 1]). Every enabled augmentation
  1286. # is rolled independently against its own probability; there is no longer a single global
  1287. # DA_PROB. The geometric augmentations (ZOOM, RANDOM_ROT, ROT90) are each rolled with their
  1288. # own probability and then composed into a single resampling pass (see affine_transform).
  1289. _C.AUGMENTOR.ZOOM_PROB = 0.5
  1290. _C.AUGMENTOR.RANDOM_RESIZED_CROP_PROB = 0.5
  1291. _C.AUGMENTOR.RANDOM_ROT_PROB = 0.5
  1292. _C.AUGMENTOR.ROT90_PROB = 0.5
  1293. _C.AUGMENTOR.SHEAR_PROB = 0.5
  1294. _C.AUGMENTOR.SHIFT_PROB = 0.5
  1295. _C.AUGMENTOR.VFLIP_PROB = 0.5
  1296. _C.AUGMENTOR.HFLIP_PROB = 0.5
  1297. _C.AUGMENTOR.ZFLIP_PROB = 0.5
  1298. _C.AUGMENTOR.ELASTIC_PROB = 0.5
  1299. _C.AUGMENTOR.G_BLUR_PROB = 0.5
  1300. _C.AUGMENTOR.MEDIAN_BLUR_PROB = 0.5
  1301. _C.AUGMENTOR.MOTION_BLUR_PROB = 0.5
  1302. _C.AUGMENTOR.GAMMA_CONTRAST_PROB = 0.5
  1303. _C.AUGMENTOR.BRIGHTNESS_PROB = 0.5
  1304. _C.AUGMENTOR.CONTRAST_PROB = 0.5
  1305. _C.AUGMENTOR.DROPOUT_PROB = 0.5
  1306. _C.AUGMENTOR.CUTOUT_PROB = 0.5
  1307. _C.AUGMENTOR.CUTBLUR_PROB = 0.5
  1308. _C.AUGMENTOR.CUTMIX_PROB = 0.5
  1309. _C.AUGMENTOR.CUTNOISE_PROB = 0.5
  1310. _C.AUGMENTOR.MISALIGNMENT_PROB = 0.5
  1311. _C.AUGMENTOR.MISSING_SECTIONS_PROB = 0.5
  1312. _C.AUGMENTOR.GRAYSCALE_PROB = 0.5
  1313. _C.AUGMENTOR.CHANNEL_SHUFFLE_PROB = 0.5
  1314. _C.AUGMENTOR.GRIDMASK_PROB = 0.5
  1315. _C.AUGMENTOR.GAUSSIAN_NOISE_PROB = 0.5
  1316. _C.AUGMENTOR.POISSON_NOISE_PROB = 0.5
  1317. _C.AUGMENTOR.SALT_PROB = 0.5
  1318. _C.AUGMENTOR.PEPPER_PROB = 0.5
  1319. _C.AUGMENTOR.SALT_AND_PEPPER_PROB = 0.5
  1320. # Create samples of the DA made. Useful to check the output images made.
  1321. _C.AUGMENTOR.AUG_SAMPLES = True
  1322. # Draw a grid in the augenation samples generated. Used when _C.AUGMENTOR.AUG_SAMPLES=True
  1323. _C.AUGMENTOR.DRAW_GRID = True
  1324. # Number of samples to create
  1325. _C.AUGMENTOR.AUG_NUM_SAMPLES = 10
  1326. # Flag to shuffle the training data on every epoch
  1327. _C.AUGMENTOR.SHUFFLE_TRAIN_DATA_EACH_EPOCH = True
  1328. # Flag to shuffle the validation data on every epoch
  1329. _C.AUGMENTOR.SHUFFLE_VAL_DATA_EACH_EPOCH = False
  1330. # Rotation of 90º to the subvolumes
  1331. _C.AUGMENTOR.ROT90 = False
  1332. # Random rotation between a defined range
  1333. _C.AUGMENTOR.RANDOM_ROT = False
  1334. # Range of random rotations
  1335. _C.AUGMENTOR.RANDOM_ROT_RANGE = (-180, 180)
  1336. # Apply shear to images
  1337. _C.AUGMENTOR.SHEAR = False
  1338. # Shear range. Expected value range is around [-360, 360], with reasonable values being in the range of [-45, 45].
  1339. _C.AUGMENTOR.SHEAR_RANGE = (-20, 20)
  1340. # Apply zoom to images
  1341. _C.AUGMENTOR.ZOOM = False
  1342. # Zoom range. Scaling factor to use, where 1.0 denotes “no change” and 0.5 is zoomed out to 50 percent of the original size.
  1343. _C.AUGMENTOR.ZOOM_RANGE = (0.5, 1.5)
  1344. # Whether to apply or not zoom in Z axis (for 3D volumes).
  1345. _C.AUGMENTOR.ZOOM_IN_Z = False
  1346. # RandomResizedCrop-style augmentation (2D only): resize the whole image/mask so the usual
  1347. # fixed-size crop covers a random area fraction of the original, instead of a fixed pixel
  1348. # window. Rolled against AUGMENTOR.RANDOM_RESIZED_CROP_PROB.
  1349. _C.AUGMENTOR.RANDOM_RESIZED_CROP = False
  1350. # Area-fraction range of the original image the crop should cover, e.g. (0.7, 0.95).
  1351. _C.AUGMENTOR.RANDOM_RESIZED_CROP_SCALE_RANGE = (0.7, 0.95)
  1352. # Apply shift
  1353. _C.AUGMENTOR.SHIFT = False
  1354. # Shift range. Translation as a fraction of the image height/width (x-translation, y-translation), where 0 denotes
  1355. # “no change” and 0.5 denotes “half of the axis size”.
  1356. _C.AUGMENTOR.SHIFT_RANGE = (0.1, 0.2)
  1357. # How to fill up the new values created with affine transformations (rotations, shear, shift and zoom).
  1358. # Only keep modes common to skimage & scipy: 'constant', 'reflect', 'wrap' and 'symmetric
  1359. # Dropped 'edge'/'nearest' for simplicity
  1360. _C.AUGMENTOR.AFFINE_MODE = "reflect"
  1361. # Make vertical flips
  1362. _C.AUGMENTOR.VFLIP = False
  1363. # Make horizontal flips
  1364. _C.AUGMENTOR.HFLIP = False
  1365. # Make z-axis flips
  1366. _C.AUGMENTOR.ZFLIP = False
  1367. # Elastic transformations
  1368. _C.AUGMENTOR.ELASTIC = False
  1369. # Strength of the distortion field. Higher values mean that pixels are moved further with respect to the distortion
  1370. # field's direction. Set this to around 10 times the value of sigma for visible effects.
  1371. _C.AUGMENTOR.E_ALPHA = (12, 16)
  1372. # Standard deviation of the gaussian kernel used to smooth the distortion fields. Higher values (for 128x128 images
  1373. # around 5.0) lead to more water-like effects, while lower values (for 128x128 images around 1.0 and lower) lead to
  1374. # more noisy, pixelated images. Set this to around 1/10th of alpha for visible effects.
  1375. _C.AUGMENTOR.E_SIGMA = 4
  1376. # Parameter that defines the handling of newly created pixels with the elastic transformation
  1377. _C.AUGMENTOR.E_MODE = "constant"
  1378. # Gaussian blur
  1379. _C.AUGMENTOR.G_BLUR = False
  1380. # Standard deviation of the gaussian kernel. Values in the range 0.0 (no blur) to 3.0 (strong blur) are common.
  1381. _C.AUGMENTOR.G_SIGMA = (1.0, 2.0)
  1382. # To blur an image by computing median values over neighbourhoods
  1383. _C.AUGMENTOR.MEDIAN_BLUR = False
  1384. # Median blur kernel size
  1385. _C.AUGMENTOR.MB_KERNEL = (3, 7)
  1386. # Blur images in a way that fakes camera or object movements
  1387. _C.AUGMENTOR.MOTION_BLUR = False
  1388. # Kernel size to use in motion blur
  1389. _C.AUGMENTOR.MOTB_K_RANGE = (8, 12)
  1390. # Gamma contrast
  1391. _C.AUGMENTOR.GAMMA_CONTRAST = False
  1392. # Exponent for the contrast adjustment. Higher values darken the image
  1393. _C.AUGMENTOR.GC_GAMMA = (1.25, 1.75)
  1394. # To apply brightness changes to images
  1395. _C.AUGMENTOR.BRIGHTNESS = False
  1396. # Strength of the brightness range.
  1397. _C.AUGMENTOR.BRIGHTNESS_FACTOR = (-0.1, 0.1)
  1398. # To apply contrast changes to images
  1399. _C.AUGMENTOR.CONTRAST = False
  1400. # Strength of the contrast change range.
  1401. _C.AUGMENTOR.CONTRAST_FACTOR = (-0.1, 0.1)
  1402. # Set a certain fraction of pixels in images to zero (not get confused with the dropout concept of neural networks)
  1403. _C.AUGMENTOR.DROPOUT = False
  1404. # Range to take the probability to drop a pixel
  1405. _C.AUGMENTOR.DROP_RANGE = (0, 0.2)
  1406. # To fill one or more rectangular areas in an image using a fill mode
  1407. _C.AUGMENTOR.CUTOUT = False
  1408. # Range of number of areas to fill the image with. Reasonable values between range [0,4]
  1409. _C.AUGMENTOR.COUT_NB_ITERATIONS = (1, 3)
  1410. # Size of the areas in % of the corresponding image size
  1411. _C.AUGMENTOR.COUT_SIZE = (0.05, 0.3)
  1412. # Value to fill the area of cutout
  1413. _C.AUGMENTOR.COUT_CVAL = 0.0
  1414. # Apply cutout to the segmentation mask
  1415. _C.AUGMENTOR.COUT_APPLY_TO_MASK = False
  1416. # To apply cutblur operation
  1417. _C.AUGMENTOR.CUTBLUR = False
  1418. # Size of the region to apply cutblur
  1419. _C.AUGMENTOR.CBLUR_SIZE = (0.2, 0.4)
  1420. # Range of the downsampling to be made in cutblur
  1421. _C.AUGMENTOR.CBLUR_DOWN_RANGE = (2, 8)
  1422. # Whether to apply cut-and-paste just LR into HR image. If False, HR to LR will be applied also (see Figure 1
  1423. # of the paper https://arxiv.org/pdf/2004.00448.pdf)
  1424. _C.AUGMENTOR.CBLUR_INSIDE = True
  1425. # Apply cutmix operation
  1426. _C.AUGMENTOR.CUTMIX = False
  1427. # Size of the region to apply cutmix
  1428. _C.AUGMENTOR.CMIX_SIZE = (0.2, 0.4)
  1429. # Apply noise to a region of the image
  1430. _C.AUGMENTOR.CUTNOISE = False
  1431. # Range to choose a value that will represent the % of the maximum value of the image that will be used as the std
  1432. # of the Gaussian Noise distribution
  1433. _C.AUGMENTOR.CNOISE_SCALE = (0.05, 0.1)
  1434. # Number of areas to fill with noise
  1435. _C.AUGMENTOR.CNOISE_NB_ITERATIONS = (1, 3)
  1436. # Size of the regions
  1437. _C.AUGMENTOR.CNOISE_SIZE = (0.2, 0.4)
  1438. # Add miss-aligment augmentation
  1439. _C.AUGMENTOR.MISALIGNMENT = False
  1440. # Maximum pixel displacement in 'xy'-plane for misalignment
  1441. _C.AUGMENTOR.MS_DISPLACEMENT = 16
  1442. # Ratio of rotation-based mis-alignment
  1443. _C.AUGMENTOR.MS_ROTATE_RATIO = 0.5
  1444. # Augment the image by creating a black line in a random position
  1445. _C.AUGMENTOR.MISSING_SECTIONS = False
  1446. # Probability of adding a missing section in each channel
  1447. _C.AUGMENTOR.MISSP_CHANNEL_PB = 0.5
  1448. # Iterations to dilate the missing line with
  1449. _C.AUGMENTOR.MISSP_ITERATIONS = (10, 30)
  1450. # Convert images in grasycale gradually based on '_C.AUGMENTOR.GRAY_RANGE'
  1451. _C.AUGMENTOR.GRAYSCALE = False
  1452. # Shuffle channels of the images
  1453. _C.AUGMENTOR.CHANNEL_SHUFFLE = False
  1454. # Apply gridmask to the image. Original paper: https://arxiv.org/pdf/2001.04086v1.pdf
  1455. _C.AUGMENTOR.GRIDMASK = False
  1456. # Determines the keep ratio of an input image
  1457. _C.AUGMENTOR.GRID_RATIO = 0.6
  1458. # Range to choose a d value
  1459. _C.AUGMENTOR.GRID_D_RANGE = (0.4, 1)
  1460. # Rotation of the mask in GridMask. Needs to be between [0,1] where 1 is 360 degrees.
  1461. _C.AUGMENTOR.GRID_ROTATE = 1.0
  1462. # Whether to invert the mask
  1463. _C.AUGMENTOR.GRID_INVERT = False
  1464. # Add Gaussian noise
  1465. _C.AUGMENTOR.GAUSSIAN_NOISE = False
  1466. _C.AUGMENTOR.GAUSSIAN_NOISE_MEAN = 0.0
  1467. _C.AUGMENTOR.GAUSSIAN_NOISE_VAR = 0.05
  1468. _C.AUGMENTOR.GAUSSIAN_NOISE_USE_INPUT_IMG_MEAN_AND_VAR = False
  1469. # Add Poisson noise
  1470. _C.AUGMENTOR.POISSON_NOISE = False
  1471. # Add salt (replaces random pixels with 1)
  1472. _C.AUGMENTOR.SALT = False
  1473. _C.AUGMENTOR.SALT_AMOUNT = 0.05
  1474. # Add pepper (replaces random pixels with 0 (for unsigned images) or -1 (for signed images))
  1475. _C.AUGMENTOR.PEPPER = False
  1476. _C.AUGMENTOR.PEPPER_AMOUNT = 0.05
  1477. # Whether to add Poisson noise
  1478. _C.AUGMENTOR.SALT_AND_PEPPER = False
  1479. _C.AUGMENTOR.SALT_AND_PEPPER_AMOUNT = 0.05
  1480. _C.AUGMENTOR.SALT_AND_PEPPER_PROP = 0.5
  1481. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1482. # 5. Model definition
  1483. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1484. _C.MODEL = CN()
  1485. # Whether to define manually the model ('biapy'), load a pretrained one from BioImage Model Zoo ('bmz') or use one
  1486. # available in TorchVision ('torchvision').
  1487. # Options: ["biapy", "bmz", "torchvision"]
  1488. _C.MODEL.SOURCE = "biapy"
  1489. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1490. # 5.1 BiaPy backend models options
  1491. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1492. # Architecture of the network. Possible values are:
  1493. # * Semantic segmentation: 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unetr', 'unext_v1', 'unext_v2',
  1494. # 'hrnet' and 'stunet'
  1495. # * Instance segmentation: 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unetr', 'unext_v1', 'unext_v2',
  1496. # 'hrnet' and 'stunet'
  1497. # * Detection: 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unetr', 'unext_v1', 'unext_v2', 'hrnet' and
  1498. # 'stunet'
  1499. # * Denoising: 'unet', 'resunet', 'resunet++', 'attention_unet', 'seunet', 'resunet_se', 'unext_v1', 'unext_v2', 'hrnet' and 'stunet'
  1500. # * Super-resolution: 'edsr', 'rcan', 'dfcan', 'wdsr', 'unet', 'resunet', 'resunet++', 'seunet', 'resunet_se', 'attention_unet', 'multiresunet', 'unext_v1'
  1501. # and 'unext_v2'
  1502. # * Self-supervision: 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unetr', 'edsr', 'rcan', 'dfcan', 'wdsr', 'vit',
  1503. # 'mae', 'unext_v1', 'unext_v2', 'hrnet' and 'stunet'
  1504. # * Classification: 'simple_cnn', 'vit' and 'efficientnet_b[0-7]' (only 2D)
  1505. # * Image to image: 'edsr', 'rcan', 'dfcan', 'wdsr', 'unet', 'resunet', 'resunet++', 'seunet', 'resunet_se', 'attention_unet', 'unetr', 'multiresunet', 'unext_v1',
  1506. # 'unext_v2', 'hrnet' and 'stunet'
  1507. _C.MODEL.ARCHITECTURE = "unet"
  1508. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1509. # 5.1.1 U-Net-like architectures options
  1510. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1511. # Number of feature maps on each level of the network. Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se',
  1512. # 'unext_v1', 'unext_v2' architectures.
  1513. _C.MODEL.FEATURE_MAPS = [16, 32, 64, 128, 256]
  1514. # Values to make the dropout with. Set to 0 to prevent dropout. When using it with 'ViT' or 'unetr' a list with just one number must be provided. Works with
  1515. # 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se' and 'unetr' architectures.
  1516. _C.MODEL.DROPOUT_VALUES = [0.0, 0.0, 0.0, 0.0, 0.0]
  1517. # Normalization layer (one of 'bn', 'sync_bn' 'in', 'ln', 'gn' or 'none'). Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet',
  1518. # 'resunet_se', 'unetr', 'hrnet' architectures.
  1519. _C.MODEL.NORMALIZATION = "in"
  1520. # to set the kernel size for the convolutional layers. Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se'
  1521. # and 'unetr' architectures.
  1522. _C.MODEL.KERNEL_SIZE = 3
  1523. # Upsampling layer to use in the model. Options: ["upsampling", "convtranspose"]. Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet',
  1524. # 'seunet' and 'resunet_se' architectures.
  1525. _C.MODEL.UPSAMPLE_LAYER = "convtranspose"
  1526. # Activation function to use along the model (not in the final layer). Options: 'relu', 'tanh', 'leaky_relu', 'elu', 'gelu', 'silu', 'sigmoid', 'softmax', 'linear',
  1527. # 'softplus' and 'none'. Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unetr' and 'hrnet' architectures.
  1528. _C.MODEL.ACTIVATION = "elu"
  1529. # Downsampling to be made in Z. This value will be the third integer of the MaxPooling operation. When facing anysotropic datasets set it to get better performance.
  1530. # Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unext_v1' and 'unext_v2' architectures.
  1531. _C.MODEL.Z_DOWN = [0, 0, 0, 0]
  1532. # Downsampling to be made in XY. This value will be the first and second integer of the MaxPooling operation. When facing anysotropic datasets set it to get better
  1533. # performance. Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unext_v1' and 'unext_v2' architectures.
  1534. _C.MODEL.YX_DOWN = [0, 0, 0, 0]
  1535. # For each level of the model (U-Net levels), set to true or false if the dimensions of the feature maps are isotropic. Works with 'unet', 'resunet', 'resunet++',
  1536. # 'attention_unet', 'multiresunet', 'seunet', 'resunet_se', 'unext_v1' and 'unext_v2' architectures.
  1537. _C.MODEL.ISOTROPY = [True, True, True, True, True]
  1538. # Include extra convolutional layers with larger kernel at the beginning and end of the U-Net-like model. Works with 'unet', 'resunet', 'resunet++', 'attention_unet',
  1539. # 'multiresunet', 'seunet' and 'resunet_se' architectures.
  1540. _C.MODEL.LARGER_IO = False
  1541. # Number of convolutional layers to stack at each level of the U-Net-like model, given as one value per level (i.e. per feature map). For 'unet', 'resunet', 'resunet++',
  1542. # 'attention_unet', 'seunet' and 'resunet_se' architectures these are plain/residual convolutions ([2, 2, ...] reproduces the classic double-convolution U-Net); for
  1543. # 'unext_v1' and 'unext_v2' these are the number of ConvNeXtBlocks in each level. If a single value is provided it is broadcast to all levels.
  1544. _C.MODEL.CONV_LAYERS = [2, 2, 2, 2, 2] # CONV_LAYERS
  1545. # Ordering of the convolution, normalization and activation layers inside each conv block.
  1546. # Options: "conv_norm_act" (default, post-activation: Conv -> Norm -> Act, the historical
  1547. # BiaPy block, keeps existing checkpoints loadable) and "norm_act_conv" (pre-activation:
  1548. # Norm -> Act -> Conv, normalizes every convolution's input including the first;
  1549. # more stable when training from scratch at large learning rates).
  1550. # Works with 'unet', 'resunet', 'resunet++', 'attention_unet', 'seunet' and 'resunet_se'
  1551. # architectures ('multiresunet' only supports "conv_norm_act").
  1552. _C.MODEL.CONV_BLOCK_ORDER = "conv_norm_act"
  1553. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1554. # 5.1.1.1 U-NeXT (v1 and v2) architectures options
  1555. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1556. # "unext_v1" and "unext_v2" architectures variables. These architectures are based on the ConvNeXt architecture (https://arxiv.org/abs/2201.03545) and they
  1557. # are adapted to the U-Net structure.
  1558. # Maximum Stochastic Depth probability for the U-NeXt model.
  1559. _C.MODEL.CONVNEXT_SD_PROB = 0.1
  1560. # Layer Scale parameter for the U-NeXt model. Only valid for the "unext_v1" architecture.
  1561. _C.MODEL.CONVNEXT_LAYER_SCALE = 1e-6
  1562. # Size of the stem kernel in the U-NeXt model.
  1563. _C.MODEL.CONVNEXT_STEM_K_SIZE = 2
  1564. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1565. # 5.1.1.2 UNETR architecture options
  1566. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1567. # Type of ViT model to use as UNETR's backbone. Options are "custom", "vit_base_patch16", "vit_large_patch16",
  1568. # "vit_huge_patch14" and "sam3_vit". On "custom" setting the backbone is built with the 'MODEL.VIT_*' variables,
  1569. # whereas with the rest of the options all of them ('MODEL.VIT_TOKEN_SIZE' included) are set automatically.
  1570. # Notice that UNETR's decoder upsamples the ViT features by a factor of two on each of its levels, so the
  1571. # resulting token size must be a power of two: "vit_huge_patch14" can not be used and "custom" must be selected
  1572. # instead. "sam3_vit" builds the image encoder of SAM 3, which can be initialized with its pretrained weights
  1573. # through 'MODEL.VIT_PRETRAINED_WEIGHTS'. As SAM 3's 14x14 tokens are not a power of two, 16x16 ones are used
  1574. # here and its patch embedding is resized to them. It is 2D only, as SAM 3's pretrained weights are 2D.
  1575. _C.MODEL.UNETR_VIT_MODEL = "custom"
  1576. # Multiple of the transformer encoder layers from of which the skip connection signal is going to be extracted.
  1577. # Leave it as -1 to decide it automatically based on the encoder selected, which spaces the skip connections
  1578. # evenly along it taking one every 'MODEL.VIT_NUM_LAYERS // log2(token size)' blocks. That gives the 3 that
  1579. # used to be the default with the classic 12-layer ViT and 16x16 tokens, and adapts it to deeper encoders,
  1580. # e.g. it gives 8 with the 32 blocks of "sam3_vit" (so blocks 8, 16 and 24 feed the decoder).
  1581. _C.MODEL.UNETR_VIT_HIDD_MULT = -1
  1582. # Number of filters in the first UNETR's layer of the decoder. In each layer the previous number of filters is doubled.
  1583. _C.MODEL.UNETR_VIT_NUM_FILTERS = 16
  1584. # Specific for SR models based on U-Net architectures. Options are ["pre", "post"]
  1585. _C.MODEL.UNET_SR_UPSAMPLE_POSITION = "pre"
  1586. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1587. # 5.1.2 Transformer-based architectures options
  1588. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1589. # Type of ViT model. Options are "custom", "vit_base_patch16", "vit_large_patch16", "vit_huge_patch14" and
  1590. # "sam3_vit". On "custom" setting the rest of the ViT parameters can be modified as other options will set
  1591. # them automatically. "sam3_vit" builds the image encoder of SAM 3 (Segment Anything Model 3), which can be
  1592. # initialized with its pretrained weights through 'MODEL.VIT_PRETRAINED_WEIGHTS'. It uses SAM 3's 14x14
  1593. # tokens, so 'DATA.PATCH_SIZE' must be a multiple of 14, and it is 2D only.
  1594. _C.MODEL.VIT_MODEL = "custom"
  1595. # Pretrained weights to initialize the ViT backbone with. Leave it empty to train from scratch. It can be a
  1596. # Hugging Face repository, i.e. "facebook/sam3" or "facebook/sam3.1" (both share the same image encoder, so
  1597. # "sam3_vit" builds the backbone for either of them), or the path to a local file with the weights. Only used when
  1598. # the selected ViT is "sam3_vit" ('MODEL.VIT_MODEL' or 'MODEL.UNETR_VIT_MODEL'). Notice that SAM 3 is a gated
  1599. # model, so its license needs to be accepted in https://huggingface.co/facebook/sam3 and this machine needs
  1600. # to be authenticated (running "hf auth login" or exporting the HF_TOKEN environment variable) to download it.
  1601. # The weights are not downloaded when 'MODEL.LOAD_CHECKPOINT' is enabled, as the checkpoint replaces them.
  1602. _C.MODEL.VIT_PRETRAINED_WEIGHTS = ""
  1603. # Size of the patches (tokens) that are extracted from the input image. Only used when the ViT model selected
  1604. # is "custom", as the rest of them are built with the token size they were designed with (e.g. "sam3_vit"
  1605. # uses SAM 3's 14x14 tokens, or the closest power of two under UNETR, as its decoder needs it).
  1606. _C.MODEL.VIT_TOKEN_SIZE = 16
  1607. # Dimension of the embedding space
  1608. _C.MODEL.VIT_EMBED_DIM = 768
  1609. # Number of transformer encoder layers
  1610. _C.MODEL.VIT_NUM_LAYERS = 12
  1611. # Number of heads in the multi-head attention layer.
  1612. _C.MODEL.VIT_NUM_HEADS = 12
  1613. # Size of the dense layers of the final classifier. This value will mutiply 'VIT_EMBED_DIM'
  1614. _C.MODEL.VIT_MLP_RATIO = 4.0
  1615. # Normalization layer epsion
  1616. _C.MODEL.VIT_NORM_EPS = 1e-6
  1617. # ViT architecture adapted for self-supervised learning with masked autoencoders (MAE). Original paper: https://arxiv.org/abs/2111.06377
  1618. # Dimension of the embedding space for the MAE decoder
  1619. _C.MODEL.MAE_DEC_HIDDEN_SIZE = 512
  1620. # Number of transformer decoder layers
  1621. _C.MODEL.MAE_DEC_NUM_LAYERS = 8
  1622. # Number of heads in the multi-head attention layer.
  1623. _C.MODEL.MAE_DEC_NUM_HEADS = 16
  1624. # Size of the dense layers of the final classifier
  1625. _C.MODEL.MAE_DEC_MLP_DIMS = 2048
  1626. # Type of the masking strategy. Options: ["grid", "random"]
  1627. _C.MODEL.MAE_MASK_TYPE = "grid"
  1628. # Percentage of the input image to mask (applied only when MODEL.MAE_MASK_TYPE == "random"). Value between 0 and 1.
  1629. _C.MODEL.MAE_MASK_RATIO = 0.5
  1630. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1631. # 5.1.3 RCAN architecture options
  1632. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1633. # Number of RG modules
  1634. _C.MODEL.RCAN_RG_BLOCK_NUM = 10
  1635. # Number of RCAB modules in each RG block
  1636. _C.MODEL.RCAN_RCAB_BLOCK_NUM = 20
  1637. # Filters in the convolutions
  1638. _C.MODEL.RCAN_CONV_FILTERS = 16
  1639. # Channel reduction ratio for channel attention
  1640. _C.MODEL.RCAN_REDUCTION_RATIO = 16
  1641. # Whether to maintain or not the upscaling layer.
  1642. _C.MODEL.RCAN_UPSCALING_LAYER = True
  1643. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1644. # 5.1.4 HRNet architecture options
  1645. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1646. # These parameters can be used as a template for building custom HRNet versions
  1647. _C.MODEL.HRNET = CN()
  1648. # Whether to use a custom configuration for HRNet or use a predefined one. Options: "W18" (hrnet18), "W32" (hrnet32),
  1649. # "W48" (hrnet48), "W64" (hrnet64) or "custom"
  1650. _C.MODEL.HRNET.VARIANT = "W48"
  1651. # Whether to downsample the input in Z or not
  1652. _C.MODEL.HRNET.Z_DOWN = [0, 0, 0]
  1653. # Downsampling to be made in XY. This value will be the first and second integer of the MaxPooling operation.
  1654. # When facing anysotropic datasets set it to get better performance
  1655. _C.MODEL.HRNET.YX_DOWN = [0, 0, 0]
  1656. # Type of block to use in HRNet. Options: 'BASIC', 'BOTTLENECK', 'CONVNEXT_V1' and 'CONVNEXT_V2'
  1657. _C.MODEL.HRNET.BLOCK_TYPE = 'BASIC'
  1658. # Indicate whether to use a custom configuration for HRNet or use a predefined one. Options: "OCR", "ASPP", "PSP", "FCN"
  1659. _C.MODEL.HRNET.HEAD_TYPE = "FCN"
  1660. # Number of stages in the HRNet. This value will determine the length of the rest of the lists. Only used if MODEL.HRNET.VARIANT = "custom"
  1661. _C.MODEL.HRNET.NUM_STAGES = 3
  1662. # Number of modules in each stage. Only used if MODEL.HRNET.VARIANT = "custom". A module is a sequence of blocks (see MODEL.HRNET.BLOCK_TYPE)
  1663. # that are not connected with the rest of branches. In each stage, after the modules, a fusion is made between all the branches. So, the
  1664. # number of modules will determine how many times the fusion is made in each stage.
  1665. _C.MODEL.HRNET.NUM_MODULES = [1, 4, 3]
  1666. # Number of branches in each stage. Only used if MODEL.HRNET.VARIANT = "custom". The number of branches will determine how many parallel convolutions
  1667. # are made in each stage and how many feature maps with different resolutions are generated.
  1668. _C.MODEL.HRNET.NUM_BRANCHES = [2, 3, 4]
  1669. # Number of blocks in each branch of each stage. Only used if MODEL.HRNET.VARIANT = "custom". A block is a convolutional operation
  1670. # (see MODEL.HRNET.BLOCK_TYPE) that is repeated a certain number of times in each branch. The number of blocks will determine the
  1671. # depth of the model.
  1672. _C.MODEL.HRNET.NUM_BLOCKS = [[4, 4], [4, 4, 4], [4, 4, 4, 4]]
  1673. # Number of channels in each block of each branch of each stage. Only used if MODEL.HRNET.VARIANT = "custom". The number of channels
  1674. # will determine the width of the model.
  1675. _C.MODEL.HRNET.NUM_CHANNELS = [[18, 36], [18, 36, 72], [18, 36, 72, 144]]
  1676. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1677. # 5.1.5 STUNet architecture options
  1678. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1679. _C.MODEL.STUNET = CN()
  1680. # Variant of the STUNet model. Options are: 'small', 'base', 'large', 'custom'
  1681. _C.MODEL.STUNET.VARIANT = 'base'
  1682. # Whether to use a pretrained version of STUNet on ImageNet
  1683. _C.MODEL.STUNET.PRETRAINED = False
  1684. # Residual blocks per stage. Only used when VARIANT = "custom"; length must equal len(DIMS).
  1685. _C.MODEL.STUNET.DEPTH = [1, 1, 1, 1, 1, 1]
  1686. # Channels per stage. Only used when VARIANT = "custom".
  1687. _C.MODEL.STUNET.DIMS = [32, 64, 128, 256, 512, 512]
  1688. # Per-stage pooling/stride, (Z,Y,X), one entry per downsampling step (len(DIMS)-1). Only used
  1689. # when VARIANT = "custom"; set anisotropic values (e.g. [1,2,2]) to avoid downsampling Z.
  1690. _C.MODEL.STUNET.POOL_OP_KERNEL_SIZES = [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [1, 1, 1]]
  1691. # Per-stage conv kernel size, (Z,Y,X), one entry per stage (len(DIMS)). Only used when VARIANT
  1692. # = "custom"; set anisotropic values (e.g. [1,3,3]) to avoid mixing information across Z.
  1693. _C.MODEL.STUNET.CONV_KERNEL_SIZES = [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]]
  1694. # Indices (into DATA.PATCH_SIZE's channel axis) of an "exchangeable" group of input channels
  1695. # whose channel-to-semantic mapping isn't stable (e.g. unsupervised per-slice GMM cluster
  1696. # ids that don't track the same physical structure from slice to slice). When non-empty,
  1697. # these channels are routed through a permutation-invariant encoder (shared per-channel 1x1
  1698. # conv + pooling, see biapy.models.blocks.PermInvariantChannelSetEncoder) instead of the
  1699. # network's regular first layer, so the result is exactly invariant to their order -- unlike
  1700. # unioning them into a single channel, real per-channel information survives. The remaining
  1701. # channels are passed through unchanged. Only used when VARIANT = "custom"; requires
  1702. # CLASS_SET_OUT_CHANNELS > 0. Left empty (default), this is a no-op.
  1703. _C.MODEL.STUNET.CLASS_SET_CHANNEL_IDXS = []
  1704. # Output width of the CLASS_SET_CHANNEL_IDXS group's pooled encoding. Only used when
  1705. # CLASS_SET_CHANNEL_IDXS is non-empty.
  1706. _C.MODEL.STUNET.CLASS_SET_OUT_CHANNELS = 8
  1707. # Pooling across the CLASS_SET_CHANNEL_IDXS group: 'max' or 'mean'. Only used when
  1708. # CLASS_SET_CHANNEL_IDXS is non-empty.
  1709. _C.MODEL.STUNET.CLASS_SET_POOLING = 'max'
  1710. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1711. # 5.1.6 NafNet architecture options
  1712. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1713. _C.MODEL.NAFNET = CN()
  1714. # Number of NAFBlocks stacked at the bottleneck (deepest level).
  1715. _C.MODEL.NAFNET.MIDDLE_BLK_NUM = 12
  1716. # Number of NAFBlocks assigned to each downsampling level of the encoder.
  1717. _C.MODEL.NAFNET.ENC_BLK_NUMS = [2, 2, 4, 8]
  1718. # Number of NAFBlocks assigned to each upsampling level of the decoder.
  1719. _C.MODEL.NAFNET.DEC_BLK_NUMS = [2, 2, 2, 2]
  1720. # Channel expansion factor for the depthwise convolution within the gating unit.
  1721. _C.MODEL.NAFNET.DW_EXPAND = 2
  1722. # Expansion factor for the hidden layer within the feed-forward network.
  1723. _C.MODEL.NAFNET.FFN_EXPAND = 2
  1724. # Discriminator architecture
  1725. _C.MODEL.NAFNET.ARCHITECTURE_D = "patchgan"
  1726. # Discriminator PATCHGAN
  1727. _C.MODEL.NAFNET.PATCHGAN = CN()
  1728. # Number of initial convolutional filters in the first layer of the discriminator.
  1729. _C.MODEL.NAFNET.PATCHGAN.BASE_FILTERS = 64
  1730. # Generator backbone used inside the NAFNet GAN pipeline. 'nafnet' (default) uses NAFNet's own
  1731. # NAFBlock encoder/decoder as the generator. 'stunet' swaps in STUNet (configured via
  1732. # MODEL.STUNET) as the generator instead.
  1733. _C.MODEL.NAFNET.GENERATOR_BACKBONE = "nafnet"
  1734. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1735. # 5.1.7 RDBM (Residual Diffusion Bridge Model) architecture options
  1736. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1737. _C.MODEL.RDBM = CN()
  1738. # Base channel width of the conditional U-Net used as the bridge's denoising network.
  1739. _C.MODEL.RDBM.BASE_DIM = 64
  1740. # Channel multiplier per resolution level of the U-Net (encoder/decoder depth = len(DIM_MULTS)).
  1741. _C.MODEL.RDBM.DIM_MULTS = [1, 2, 4, 8]
  1742. # Number of discretization steps of the forward bridge process used during training.
  1743. _C.MODEL.RDBM.TIMESTEPS = 100
  1744. # Number of reverse (sampling) steps at validation/test time. Must be <= TIMESTEPS.
  1745. _C.MODEL.RDBM.SAMPLING_TIMESTEPS = 10
  1746. # Noise scale of the bridge's stochastic term.
  1747. _C.MODEL.RDBM.LAMB = 1.0e-4
  1748. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1749. # 5.1.8 Checkpoint options
  1750. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1751. # To load a model (and more items if available) from a given checkpoint. Items that can be loaded are defined in 'MODEL.ITEMS_TO_LOAD_FROM_CHECKPOINT'.
  1752. _C.MODEL.LOAD_CHECKPOINT = False
  1753. # List of items to load from the checkpoint (if available). Options are:
  1754. # * "weights": to load the model weights
  1755. # * "norm": to load the normalization used. Unless you know that the checkpoint was trained with the same normalization as the one defined in the config,
  1756. # it is recommended to load it from the checkpoint if "weights" is also specified, as the model will expect the input data to be normalized accordingly.
  1757. # * "model_arch": to load the model architecture
  1758. # * "optimizer": to load the optimizer state dict
  1759. # * "epoch": to load the epoch number from which the training will be resumed
  1760. #
  1761. # Defining it with "weights" and "model_arch" will allow to load the model weights and architecture, but not the
  1762. # optimizer state, which is useful when doing inference or fine-tunning. Defining it with all options
  1763. # will allow to resume training from a checkpoint.
  1764. _C.MODEL.ITEMS_TO_LOAD_FROM_CHECKPOINT = ["weights", "norm", "model_arch"]
  1765. # Decide which checkpoint to load from job's dir if PATHS.CHECKPOINT_FILE is ''.
  1766. # Options: 'best_on_val' or 'last_on_train'
  1767. _C.MODEL.LOAD_CHECKPOINT_EPOCH = "best_on_val"
  1768. # Format of the output checkpoint. Options are 'pth' (native PyTorch format) or 'safetensors' (https://github.com/huggingface/safetensors)
  1769. _C.MODEL.OUT_CHECKPOINT_FORMAT = "pth"
  1770. # To skip loading those layers that do not match in shape with the given checkpoint. If this is set to False a regular load function will be
  1771. # done, which will fail if a layer mismatch is found. Only applicable if "weights" is in 'MODEL.ITEMS_TO_LOAD_FROM_CHECKPOINT'. It is useful
  1772. # to set it to True when fine-tunning a model with a different head.
  1773. _C.MODEL.SKIP_UNMATCHED_LAYERS = False
  1774. # Epochs to save a checkpoint of the model apart from the best of the validation. Set it to -1 to not do it.
  1775. _C.MODEL.SAVE_CKPT_FREQ = -1
  1776. # List of regex patterns to match parameter names that should be frozen (i.e. excluded from gradient updates) during
  1777. # training. Each entry is a Python 're' pattern tested against the full parameter name (e.g. "encoder\.layer1\..*").
  1778. # Freezing is applied after loading the checkpoint so that the loaded weights are preserved. Parameters matched by
  1779. # any pattern will have 'requires_grad' set to False and will be excluded from the optimizer. An empty list (default)
  1780. # means no layers are frozen.
  1781. # Examples: ["backbone\.layer1\..*", "backbone\.layer2\.conv.*"]
  1782. _C.MODEL.FREEZE_LAYERS_MATCHING = []
  1783. # Passed as 'find_unused_parameters' to DistributedDataParallel. Set to True if the model has
  1784. # parameters that don't participate in every forward pass (e.g. some BMZ models), otherwise DDP
  1785. # raises "Expected to have finished reduction...". Costs a small per-iteration overhead.
  1786. _C.MODEL.FIND_UNUSED_PARAMETERS = False
  1787. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1788. # 5.2 BioImage Model Zoo (BMZ) options
  1789. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1790. # BMZ model export options
  1791. _C.MODEL.BMZ = CN()
  1792. # DOI or nickname of the model from BMZ to load. It can not be empty if MODEL.SOURCE = "bmz".
  1793. _C.MODEL.BMZ.SOURCE_MODEL_ID = ""
  1794. # Module to export the model to BMZ format. It will be activated when 'MODEL.BMZ.EXPORT.ENABLE' is set to True.
  1795. _C.MODEL.BMZ.EXPORT = CN()
  1796. # Whether to activate or not the exporation of the used model to the BMZ format after train and/or test
  1797. _C.MODEL.BMZ.EXPORT.ENABLE = False
  1798. # Name of the model to create. It should be something meaningful. Take other models in https://bioimage.io/#/ as reference.
  1799. _C.MODEL.BMZ.EXPORT.MODEL_NAME = ""
  1800. # Description of the model. It should be something meaningful. Take other models in https://bioimage.io/#/ as reference.
  1801. # E.g. "Mitochondria segmentation for electron microscopy"
  1802. _C.MODEL.BMZ.EXPORT.DESCRIPTION = ""
  1803. # List of authors of the model. Each item must be a dict containing "name" and "githubuser".
  1804. # E.g. [{"name": "Daniel", "github_user": "danifranco"}]
  1805. _C.MODEL.BMZ.EXPORT.AUTHORS = []
  1806. # License of the model.
  1807. _C.MODEL.BMZ.EXPORT.LICENSE = "CC-BY-4.0"
  1808. # Path to a .md extension file with the documentation of the model. If it is not set so the model documentation will be
  1809. # automatically generated with the information provided. If you want to add more information you can use this option.
  1810. # E.g. to provide more details of the training procedure, data, etc.
  1811. _C.MODEL.BMZ.EXPORT.DOCUMENTATION = ""
  1812. # List of tags. Here the type of dataset and the target object should be provided. BiaPy automatically sets the following tags:
  1813. # * "biapy": to represent that the model was created with BiaPy.
  1814. # * "pytorch": to represent that you are using Pytorch
  1815. # * "2d" or "3d": depending on the image dimensions one or the other is selected.
  1816. # * workflow tag: depending on the workflow the tag is set. E.g. "semantic-segmentation"
  1817. #
  1818. # So, what you can set for instance is: ["electron-microscopy", "mitochondria"]
  1819. _C.MODEL.BMZ.EXPORT.TAGS = []
  1820. # Citations. It must be a list of dictionaries with keys "text" and "doi". E.g.:
  1821. # [{"text": "training library", "doi": "10.1038/s41592-025-02699-y"}, {"text": "architecture", "doi": "10.1109/LGRS.2018.2802944"},
  1822. # {"text": "data", "doi": "10.48550/arXiv.1812.06024"}]
  1823. _C.MODEL.BMZ.EXPORT.CITE = []
  1824. # Information of the dataset. It must be a list of just one dict item with keys "name", "doi" and "image_modality". It can have
  1825. # also "dataset_id" key but it is optional (must match a dataset in the BioImage Model Zoo). E.g:
  1826. # [{
  1827. # "name": "CartoCell",
  1828. # "doi": "10.1016/j.crmeth.2023.100597",
  1829. # "image_modality": "fluorescence microscopy",
  1830. # "dataset_id": "biapy/cartocell_cyst_segmentation",
  1831. # }]
  1832. _C.MODEL.BMZ.EXPORT.DATASET_INFO = [{}]
  1833. # Version of the model
  1834. _C.MODEL.BMZ.EXPORT.MODEL_VERSION = "0.1.0"
  1835. # If you are loading a BMZ model you can enable this option to avoid setting all above variables and instead reuse the same
  1836. # information that was present in that model. You need still to set 'MODEL.BMZ.EXPORT.ENABLE' to 'True' and nothing else.
  1837. _C.MODEL.BMZ.EXPORT.REUSE_BMZ_CONFIG = False
  1838. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1839. # 5.2 TorchVision options (limited support)
  1840. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1841. # BiaPy support using models of Torchvision. However, most of the models were trained in natural images (not biomedical) and most of them
  1842. # are for classification. On top of that, some use bounding-box-annotations, which are not supported in BiaPy so only inference/prediction/test
  1843. # can only be done. 'MODEL.TORCHVISION_MODEL_NAME' variable can not be empty if MODEL.SOURCE = "torchvision".
  1844. # Models available here: https://pytorch.org/vision/stable/models.html
  1845. # They can be listed with: "from torchvision.models import list_models; list_models()"
  1846. #
  1847. # Semantic segmentation (https://pytorch.org/vision/stable/models.html#semantic-segmentation):
  1848. # 'deeplabv3_mobilenet_v3_large', 'deeplabv3_resnet101', 'deeplabv3_resnet50', 'fcn_resnet101', 'fcn_resnet50',
  1849. # 'lraspp_mobilenet_v3_large'
  1850. #
  1851. # Object Detection (https://pytorch.org/vision/stable/models.html#object-detection-instance-segmentation-and-person-keypoint-detection)
  1852. # 'fasterrcnn_mobilenet_v3_large_320_fpn', 'fasterrcnn_mobilenet_v3_large_fpn', 'fasterrcnn_resnet50_fpn',
  1853. # 'fasterrcnn_resnet50_fpn_v2', 'fcos_resnet50_fpn', 'ssd300_vgg16', 'ssdlite320_mobilenet_v3_large',
  1854. # 'retinanet_resnet50_fpn', 'retinanet_resnet50_fpn_v2',
  1855. #
  1856. # Instance Segmentation (https://pytorch.org/vision/stable/models.html#object-detection-instance-segmentation-and-person-keypoint-detection)
  1857. # 'maskrcnn_resnet50_fpn', 'maskrcnn_resnet50_fpn_v2'
  1858. #
  1859. # Image classification (https://pytorch.org/vision/stable/models.html#classification):
  1860. # 'alexnet', 'convnext_base', 'convnext_large', 'convnext_small', 'convnext_tiny', 'densenet121', 'densenet161',
  1861. # 'densenet169', 'densenet201', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3',
  1862. # 'efficientnet_b4', 'efficientnet_b5', 'efficientnet_b6', 'efficientnet_b7', 'efficientnet_v2_l', 'efficientnet_v2_m',
  1863. # 'efficientnet_v2_s', 'googlenet', 'inception_v3', 'maxvit_t', 'mnasnet0_5', 'mnasnet0_75', 'mnasnet1_0', 'mnasnet1_3',
  1864. # 'mobilenet_v2', 'mobilenet_v3_large', 'mobilenet_v3_small', 'quantized_googlenet', 'quantized_inception_v3',
  1865. # 'quantized_mobilenet_v2', 'quantized_mobilenet_v3_large', 'quantized_resnet18', 'quantized_resnet50',
  1866. # 'quantized_resnext101_32x8d', 'quantized_resnext101_64x4d', 'quantized_shufflenet_v2_x0_5', 'quantized_shufflenet_v2_x1_0',
  1867. # 'quantized_shufflenet_v2_x1_5', 'quantized_shufflenet_v2_x2_0', 'regnet_x_16gf', 'regnet_x_1_6gf', 'regnet_x_32gf',
  1868. # 'regnet_x_3_2gf', 'regnet_x_400mf', 'regnet_x_800mf', 'regnet_x_8gf', 'regnet_y_128gf', 'regnet_y_16gf', 'regnet_y_1_6gf',
  1869. # 'regnet_y_32gf', 'regnet_y_3_2gf', 'regnet_y_400mf', 'regnet_y_800mf', 'regnet_y_8gf', 'resnet101', 'resnet152',
  1870. # 'resnet18', 'resnet34', 'resnet50', 'resnext101_32x8d', 'resnext101_64x4d', 'resnext50_32x4d', 'retinanet_resnet50_fpn',
  1871. # 'shufflenet_v2_x0_5', 'shufflenet_v2_x1_0', 'shufflenet_v2_x1_5', 'shufflenet_v2_x2_0',
  1872. # 'squeezenet1_0', 'squeezenet1_1', 'swin_b', 'swin_s', 'swin_t', 'swin_v2_b', 'swin_v2_s', 'swin_v2_t',
  1873. # 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 'vgg19', 'vgg19_bn', 'vit_b_16', 'vit_b_32',
  1874. # 'vit_h_14', 'vit_l_16', 'vit_l_32', 'wide_resnet101_2', 'wide_resnet50_2'
  1875. #
  1876. # Listed but not supported:
  1877. #
  1878. # (NOT SUPPORTED) Video classification (https://pytorch.org/vision/stable/models.html#video-classification):
  1879. # 'mc3_18', 'mvit_v1_b', 'mvit_v2_s', 'r2plus1d_18', 'r3d_18','swin3d_s', 'swin3d_t', 's3d', 'swin3d_b'
  1880. #
  1881. # (NOT SUPPORTED) Optical flow (https://pytorch.org/vision/stable/models.html#optical-flow):
  1882. # 'raft_large', 'raft_small'
  1883. #
  1884. # (NOT SUPPORTED) Person Keypoint Detection (https://pytorch.org/vision/stable/models.html#object-detection-instance-segmentation-and-person-keypoint-detection)
  1885. # 'keypointrcnn_resnet50_fpn'
  1886. #
  1887. _C.MODEL.TORCHVISION_MODEL_NAME = ""
  1888. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1889. # 6. Loss definition options
  1890. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1891. _C.LOSS = CN()
  1892. # List of individually-weighted loss names to sum:
  1893. # sum(LOSS.WEIGHTS[i] * loss_i(pred, target) for i, loss_i in enumerate(LOSS.TYPE))
  1894. # 'LOSS.WEIGHTS' must be the same length. Empty -> per-workflow default (see each
  1895. # workflow's 'define_metrics'). Old single-string combos (e.g. "W_MAE_SSIM") still work,
  1896. # auto-converted in check_configuration.py. Valid names per workflow:
  1897. # * Semantic segmentation: "CE" (default), "DICE", or ["DICE", "CE"] together (fused
  1898. # CE+Dice, not decomposed).
  1899. # * Instance segmentation: set via PROBLEM.INSTANCE_SEG.DATA_CHANNELS(_LOSSES).
  1900. # * Detection: always CE. Classification: always "CE".
  1901. # * Continuous-image (DENOISING, SUPER_RESOLUTION, SELF_SUPERVISED, IMAGE_TO_IMAGE):
  1902. # "MAE" (default), "MSE", "PCC", "CHARBONNIER", "VGG", "LPIPS", "SSIM", "LAPLACIAN",
  1903. # "FFT", "RFFT" -- see 'continuous_image_loss_registry' in metrics.py. DENOISING only
  1904. # supports a single ["MSE"] or ["BCE"]/["HINGE"], never a multi-term mix.
  1905. # * IMAGE_TO_IMAGE/DENOISING also accept "BCE" or "HINGE" (adversarial term, mutually
  1906. # exclusive, needs a discriminator; knobs under LOSS.GAN below).
  1907. # * IMAGE_TO_IMAGE with PROBLEM.IMAGE_TO_IMAGE.MEMBRANE_REPAIR.ENABLE: "BCE", "MALIS",
  1908. # "CLDICE", "SVOX" (at least one positive weight).
  1909. _C.LOSS.TYPE = []
  1910. # Same length as LOSS.TYPE. Unlike the old "W_*" strings, weights don't need to sum to 1.
  1911. _C.LOSS.WEIGHTS = []
  1912. # To weight classes in an imbalanced dataset. Options available are:
  1913. # * 'none': no class rebalancing is applied
  1914. # * 'manual': the weights provided in LOSS.CLASS_WEIGHTS are used to weight each class. This is valid for semantic segmentation, instance segmentation (when instance+classes are predicted)
  1915. # and detection workflows (when centroids + classes are predicted).
  1916. _C.LOSS.CLASS_REBALANCE = "none"
  1917. # If LOSS.CLASS_REBALANCE is set to 'manual', this list of weights will be used to weight each class in the loss calculation.
  1918. # The length of the list must be equal to the number of classes.
  1919. _C.LOSS.CLASS_WEIGHTS = []
  1920. # Whether to ignore a value in the loss and metric calculation. This is only available when LOSS.TYPE == "CE". This value will not only
  1921. # be ignored in the loss computation but in the metrics, e.g. IoU. In membrane repair it marks ignored voxels in the
  1922. # membrane channel: they are excluded from its normalization, fed as 0 and the affinities between two of them ignored.
  1923. _C.LOSS.IGNORE_INDEX = -1
  1924. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1925. # 6.1 Contrastive learning definitions
  1926. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1927. _C.LOSS.CONTRAST = CN()
  1928. _C.LOSS.CONTRAST.ENABLE = False
  1929. _C.LOSS.CONTRAST.MEMORY_SIZE = 5000
  1930. _C.LOSS.CONTRAST.PROJ_DIM = 256
  1931. _C.LOSS.CONTRAST.PIXEL_UPD_FREQ = 10
  1932. # Adversarial-term knobs beyond its weight/formula (those live in LOSS.TYPE/LOSS.WEIGHTS,
  1933. # picking "BCE" or "HINGE"). Used only when one of those is present.
  1934. _C.LOSS.GAN = CN()
  1935. # R1 gradient penalty coefficient (0.0 to disable).
  1936. _C.LOSS.GAN.R1_GAMMA = 0.0
  1937. # If True, scale the adversarial weight by the VQGAN adaptive weight (recon/adv
  1938. # gradient-norm ratio) instead of using it as a fixed scalar.
  1939. _C.LOSS.GAN.ADAPTIVE_GAN_WEIGHT = False
  1940. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1941. # 7. Training phase options
  1942. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1943. _C.TRAIN = CN()
  1944. _C.TRAIN.ENABLE = False
  1945. # Enable verbosity
  1946. _C.TRAIN.VERBOSE = False
  1947. # Optimizer(s) to use. Possible values: "SGD", "ADAM" or "ADAMW".
  1948. _C.TRAIN.OPTIMIZER = ["SGD"]
  1949. # Learning rate(s).
  1950. _C.TRAIN.LR = [1.0e-4]
  1951. # Weight decay
  1952. _C.TRAIN.W_DECAY = 0.02
  1953. # Coefficients used for computing running averages of gradient and its square. Used in ADAM and ADAMW optmizers
  1954. _C.TRAIN.OPT_BETAS = [[0.9, 0.999]]
  1955. # Batch size
  1956. _C.TRAIN.BATCH_SIZE = 2
  1957. # Number of epochs to train the model
  1958. _C.TRAIN.EPOCHS = 360
  1959. # Epochs to wait with no validation data improvement until the training is stopped
  1960. _C.TRAIN.PATIENCE = -1
  1961. # Metrics to apply during training. Depending on the workflow different ones can be applied. If empty, some
  1962. # default metrics will be configured automatically:
  1963. # * Semantic segmentation: 'iou' (called also Jaccard index)
  1964. # * Instance segmentation: automatically set depending on the channels selected (PROBLEM.INSTANCE_SEG.DATA_CHANNELS).
  1965. # * Detection: 'iou' (called also Jaccard index)
  1966. # * Denoising: 'mae', 'mse'
  1967. # * Super-resolution: "psnr", "mae", "mse", "ssim", "pcc"
  1968. # * Self-supervision: "psnr", "mae", "mse", "ssim", "pcc"
  1969. # * Classification: 'accuracy', 'top-5-accuracy'
  1970. # * Image to image: "psnr", "mae", "mse", "ssim", "pcc"
  1971. _C.TRAIN.METRICS = []
  1972. # Gradient clipping max norm applied per optimizer. 0 = disabled.
  1973. _C.TRAIN.GRADIENT_CLIP_NORM = 0.0
  1974. # Callbacks
  1975. # To determine which value monitor to consider which epoch consider the best to save. Currently not used.
  1976. _C.TRAIN.CHECKPOINT_MONITOR = "val_loss"
  1977. # Epochs to save a preview of the model's predictions on a fixed set of samples to PATHS.TRAIN_PRED_SAMPLES. Set it to -1 to not do it.
  1978. _C.TRAIN.SAVE_TRAIN_PREDS_FREQ = -1
  1979. # Number of fixed samples to track when 'TRAIN.SAVE_TRAIN_PREDS_FREQ' != -1.
  1980. _C.TRAIN.SAVE_TRAIN_PREDS_NUM_SAMPLES = 1
  1981. # Whether to also render the tracked samples inline (Jupyter/Colab only; ignored elsewhere).
  1982. _C.TRAIN.SAVE_TRAIN_PREDS_SHOW = False
  1983. # Add profiler callback to the training
  1984. # _C.TRAIN.PROFILER = False
  1985. # # Batch range to be analyzed
  1986. # _C.TRAIN.PROFILER_BATCH_RANGE='10, 100'
  1987. # _C.TRAIN.MAE_CALLBACK_EPOCHS = 5
  1988. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1989. # 7.1 Learning rate (LE) scheduler options
  1990. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1991. # LR Scheduler
  1992. _C.TRAIN.LR_SCHEDULER = CN()
  1993. _C.TRAIN.LR_SCHEDULER.NAME = "" # Possible options: 'warmupcosine', 'reduceonplateau', 'onecycle', 'warmupreduceonplateau'
  1994. # Lower bound on the learning rate used in 'warmupcosine' and 'reduceonplateau'
  1995. _C.TRAIN.LR_SCHEDULER.MIN_LR = [-1.0]
  1996. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1997. # 7.1.1 Reduce on plateau options
  1998. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1999. # The reduce on plateau scheduler reduces the learning rate when a metric has stopped improving.
  2000. #
  2001. # Factor by which the learning rate will be reduced
  2002. _C.TRAIN.LR_SCHEDULER.REDUCEONPLATEAU_FACTOR = 0.5
  2003. # Number of epochs with no improvement after which learning rate will be reduced. Need to be less than 'TRAIN.PATIENCE'
  2004. # otherwise it makes no sense
  2005. _C.TRAIN.LR_SCHEDULER.REDUCEONPLATEAU_PATIENCE = -1
  2006. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2007. # 7.1.2 Cosine decay with warm up options
  2008. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2009. # Cosine decay with a warm up consist in 2 phases: 1) a warm up phase which consists of increasing
  2010. # the learning rate from TRAIN.LR_SCHEDULER.MIN_LR to TRAIN.LR value by a factor
  2011. # during a certain number of epochs defined by 'TRAIN.LR_SCHEDULER.WARMUP_COSINE_DECAY_EPOCHS'
  2012. # 2) after this will began the decay of the learning rate value using the cosine function.
  2013. # Find a detailed explanation in: https://scorrea92.medium.com/cosine-learning-rate-decay-e8b50aa455b
  2014. #
  2015. # Epochs to do the warming up. -1/0 disables the ramp.
  2016. _C.TRAIN.LR_SCHEDULER.WARMUP_COSINE_DECAY_EPOCHS = -1
  2017. # Delays when decay starts: after warm up (if any), TRAIN.LR is held constant until
  2018. # (1 - COSINE_DECAY_FRACTION) fraction of TRAIN.EPOCHS have passed, then cosine-decayed
  2019. # over the final fraction ("delayed cosine decay"). Combinable with the warm up above
  2020. # (ramp, then hold, then decay). Set to a value in (0, 1] to enable; -1 (default) disables
  2021. # it, so decay starts right after warm up as usual.
  2022. _C.TRAIN.LR_SCHEDULER.COSINE_DECAY_FRACTION = -1.0
  2023. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2024. # 8. Test/inference phase options
  2025. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2026. _C.TEST = CN()
  2027. _C.TEST.ENABLE = False
  2028. # Tries to reduce the memory footprint by separating crop/merge operations and by changing dtype of the predictions.
  2029. # It is slower and not as precise as the "normal" inference process but saves memory
  2030. _C.TEST.REDUCE_MEMORY = False
  2031. # Whether to compute the metrics in CPU instead of GPU to reduce GPU memory consumption.
  2032. _C.TEST.METRICS_IN_CPU = False
  2033. # Whether to save the raw output of the model (before any post-processing) alongside the final prediction. It is placed normally
  2034. # in a folder called 'per_image'
  2035. _C.TEST.SAVE_MODEL_RAW_OUTPUT = True
  2036. # Enable verbosity
  2037. _C.TEST.VERBOSE = True
  2038. # Make test-time augmentation. Infer over 8 possible rotations for 2D img and 16 when 3D
  2039. _C.TEST.AUGMENTATION = False
  2040. # Select test-time augmentation mode. Options: "mean" (default), "min", "max".
  2041. # "min"/"max" are only applied to the channels they are meaningful for: a component-wise
  2042. # minimum over several predicted flow/offset fields is not a flow field, so signed vector
  2043. # channels (Cellpose/Omnipose 'Gv'/'Gh'/'Gz', HoVerNet 'V'/'H'/'Z', EmbedSeg 'E_offset')
  2044. # are always averaged no matter what is set here.
  2045. _C.TEST.AUGMENTATION_MODE = "mean"
  2046. # Largest set of test-time augmentation orientations to use. Options:
  2047. # - "auto" (default)/"full": 90 degree rotations + flips (8 in 2D, 16 in 3D).
  2048. # - "flips": axis flips only (4 in 2D, 8 in 3D). What Cellpose does upstream, and the safe
  2049. # choice for representations whose rotations cannot be undone exactly.
  2050. # - "none": no augmentation (identity only).
  2051. # Instance-segmentation representations that cannot represent an orientation exactly shrink
  2052. # this set automatically (e.g. 3D StarDist rays, or EmbedSeg on anisotropic data); the
  2053. # orientations actually used are printed once at the start of inference.
  2054. _C.TEST.AUGMENTATION_GROUP = "auto"
  2055. # Stack 2D images into a 3D image and then process it entirely instead of going image per image
  2056. _C.TEST.ANALIZE_2D_IMGS_AS_3D_STACK = False
  2057. # Whether to reuse the existing ones (from file) or calculate predictions using the model
  2058. _C.TEST.REUSE_PREDICTIONS = False
  2059. # If PROBLEM.NDIM = '2D' this can be activated to process each image entirely instead of patch by patch. Only can be done
  2060. # if the neural network is fully convolutional. Implemented in semantic-segmentation, instance-segmentation and detection workflows.
  2061. _C.TEST.FULL_IMG = False
  2062. # Metrics to apply during test/inference. Depending on the workflow different ones can be applied. If empty, some
  2063. # default metrics will be configured automatically:
  2064. # * Semantic segmentation: 'iou' (called also Jaccard index)
  2065. # * Instance segmentation: automatically set depending on the channels selected (PROBLEM.INSTANCE_SEG.DATA_CHANNELS).
  2066. # Instance metrics will be always calculated.
  2067. # * Detection: 'iou' (called also Jaccard index)
  2068. # * Denoising: 'mae', 'mse'
  2069. # * Super-resolution: "psnr", "mae", "mse", "ssim", "pcc". Additionally, if only if PROBLEM.NDIM == '2D', these
  2070. # can also be selected: "fid", "is", "lpips"
  2071. # * Self-supervision: "psnr", "mae", "mse", "ssim", "pcc". Additionally, if only if PROBLEM.NDIM == '2D', these
  2072. # can also be selected: "fid", "is", "lpips"
  2073. # * Classification: 'accuracy'. Always calculated: Confusion matrix
  2074. # * Image to image: "psnr", "mae", "mse", "ssim", "pcc". Additionally, if only if PROBLEM.NDIM == '2D', these
  2075. # can also be selected: "fid", "is", "lpips"
  2076. _C.TEST.METRICS = []
  2077. # Number of pixels/voxels to exclude from each border when computing test/inference metrics,
  2078. # regardless of workflow. Order is: [z, y, x] (3D) and [y, x] (2D). For example, with an image
  2079. # of 10x100x200 to ignore the first/last Z slices and a 15-pixel border on Y/X, use [1, 15, 15].
  2080. # Predictions near the border are usually less reliable (the model has no context beyond the
  2081. # edge, and patch-merging seams concentrate there too), which can inflate errors that don't
  2082. # reflect the model's real performance. This never changes the predictions themselves (nor
  2083. # anything saved to disk) -- only the region considered when scoring each metric, so only the
  2084. # center of the image is evaluated:
  2085. # * Semantic segmentation / voxel-level instance segmentation & membrane-repair metrics /
  2086. # denoising / super-resolution / image-to-image / self-supervised: the border region of the
  2087. # prediction and GT is excluded before computing pixel-wise metrics (IoU, MAE, MSE, SSIM,
  2088. # PSNR, etc).
  2089. # * Object-level instance segmentation & membrane-repair matching: a copy of the predicted/GT
  2090. # instance label images has this border region blacked out (kept at the original shape)
  2091. # before matching, so the TP/FP/FN color map stays full-size too.
  2092. # * Detection: points (predicted or GT) whose coordinates fall in the border region are
  2093. # excluded from the precision/recall/F1 computation.
  2094. # * Classification: not applicable (no spatial dimension to crop); must be left empty.
  2095. _C.TEST.EVAL_BORDER_CROP = []
  2096. ### Instance segmentation
  2097. # Whether to calculate matching statistics (average overlap, accuracy, recall, precision, etc.)
  2098. _C.TEST.MATCHING_STATS = True
  2099. # Theshold of overlap to consider a TP when calculating the metrics. If more than one value is provided
  2100. # the process is repeated with each of the threshold values
  2101. _C.TEST.MATCHING_STATS_THS = [0.3, 0.5, 0.75]
  2102. # Decide in which thresholds to create a colored image of the TPs, FNs and FPs
  2103. _C.TEST.MATCHING_STATS_THS_COLORED_IMG = []
  2104. # How to aggregate the matching statistics across the dataset. If ``True`` the metrics (accuracy/AP_dsb,
  2105. # precision, recall, etc.) are computed per image and then averaged over images (macro-average), which matches
  2106. # the "AP_dsb" definition reported by EmbedSeg/StarDist. If ``False`` the TP/FP/FN counts are pooled across all
  2107. # images and the metrics are computed once from those totals (micro-average).
  2108. _C.TEST.MATCHING_STATS_BY_IMAGE = True
  2109. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2110. # 8.1 Test/inference by chunks options
  2111. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2112. # In the processing of 3D images, the primary image is segmented into smaller patches. These patches are subsequently
  2113. # passed through a computational network. The outcome is a new image, typically saved as a TIF file, that retains the
  2114. # dimensions of the original input. Notably, if the input image is sizable, this process can be memory-intensive. This
  2115. # is because the quantity of patches is contingent on both the dimensions of the input and the selected padding/overlap
  2116. # parameters (defined as 'DATA.TEST.PADDING' and 'DATA.TEST.OVERLAP').
  2117. # To alleviate potential memory constraints, we offer an alternative: producing an H5/Zarr file with the predicted patches.
  2118. # This method ensures efficient memory usage, as patches are individually incorporated into the H5/Zarr file in their respective
  2119. # positions. This negates the need to store all patches simultaneously for image reconstruction. Importantly, in this
  2120. # approach, only the 'DATA.TEST.PADDING' parameter is considered, excluding 'DATA.TEST.OVERLAP', which sufficiently
  2121. # addresses border effect issues. If the source image is also an H5/Zarr file, it will be processed by chunks, further
  2122. # optimizing memory usage. This process can only be applied in semantic segmentation, instance segmentation and detection
  2123. # workflows.
  2124. #
  2125. _C.TEST.BY_CHUNKS = CN()
  2126. _C.TEST.BY_CHUNKS.ENABLE = False
  2127. # In the process of 'TEST.BY_CHUNKS' you can enable this variable to save the reconstructed prediction as a TIF too.
  2128. # Be aware of this option and be sure that the prediction can fit in you memory entirely, as it is needed for saving as TIF.
  2129. _C.TEST.BY_CHUNKS.SAVE_OUT_TIF = False
  2130. # In how many iterations the H5 writer needs to flush the data. No need to do so with Zarr files.
  2131. _C.TEST.BY_CHUNKS.FLUSH_EACH = 100
  2132. # Z slice index (inclusive) at which chunk processing starts. Use -1 (default) to start from the beginning.
  2133. # Useful for distributing large-volume prediction across multiple cluster jobs, each handling a Z sub-range.
  2134. _C.TEST.BY_CHUNKS.Z_START = -1
  2135. # Z slice index (exclusive) at which chunk processing ends. Use -1 (default) to process until the end.
  2136. # The output Zarr is always the full data shape so multiple jobs can write concurrently.
  2137. _C.TEST.BY_CHUNKS.Z_END = -1
  2138. # Whether to write the raw model predictions into a Zarr file. They are not needed to create the final output, as
  2139. # each tile is post-processed as soon as it is predicted, and they are heavy to store (e.g. 12 float32 channels
  2140. # per voxel for affinities), so they are only written on demand. Forced when the workflow process is disabled or
  2141. # set to 'entire_pred', when 'TEST.REUSE_PREDICTIONS' is enabled or when the raw prediction is the final output
  2142. # of the workflow (e.g. denoising).
  2143. _C.TEST.BY_CHUNKS.WRITE_RAW_PREDICTIONS = False
  2144. # Phases to execute in this job. Allows splitting the full pipeline across multiple cluster jobs.
  2145. # Available phases:
  2146. # * 'prediction' : run the model on each patch. Post-processing runs on the fly unless this is the only
  2147. # phase of the job, in which case the raw predictions are written to a Zarr file.
  2148. # * 'instance_creation' : run per-chunk watershed (instance segmentation, 'chunk_by_chunk' only). Runs within
  2149. # 'prediction' when both phases are selected, otherwise it reads the raw predictions Zarr.
  2150. # * 'instance_merging' : resolve cross-chunk instance IDs (Passes B–E, instance segmentation only).
  2151. # Example multi-job setup for a large volume:
  2152. # Job 1 — Z_START=0, Z_END=500, PHASES=["prediction", "instance_creation"]
  2153. # Job 2 — Z_START=500, Z_END=1000, PHASES=["prediction", "instance_creation"]
  2154. # Job 3 — (no Z range) PHASES=["instance_merging"]
  2155. _C.TEST.BY_CHUNKS.PHASES = ["prediction", "instance_creation", "instance_merging"]
  2156. # After passing all the patches through the model we obtain the model's raw predictions, which may be subsequently processed
  2157. # to generate the final prediction. Each workflow has its own steps for this process:
  2158. #
  2159. # * Semantic segmentation: all raw predictions, which are probabilities of each class, are merged together to create the final
  2160. # predicted image by argmax operation. This process is not memory intensive as the raw predictions are merged patch by
  2161. # patch and not all at once.
  2162. # * Instance segmentation: the raw predictions are merged together to create the final predicted image by a watershed process.
  2163. # This process is memory intensive as the entire predicted image needs to be loaded in memory to do it.
  2164. # * Detection: All the points of interest are detected from the raw predictions. This process is not memory intensive as the
  2165. # points are detected patch by patch and not all at once.
  2166. _C.TEST.BY_CHUNKS.WORKFLOW_PROCESS = CN()
  2167. _C.TEST.BY_CHUNKS.WORKFLOW_PROCESS.ENABLE = True
  2168. # How the workflow process is going to be done. There are two options:
  2169. # * 'chunk_by_chunk' : each chunk will be considered as an individual file. Select this operation if you have not enough
  2170. # memory to process the entire prediction image with 'entire_pred'.
  2171. # * 'entire_pred': the predicted image will be loaded in memory and processed entirely (be aware of your memory budget)
  2172. _C.TEST.BY_CHUNKS.WORKFLOW_PROCESS.TYPE = "chunk_by_chunk"
  2173. # Patches, in (z,y,x) order, grouped into each tile of the workflow process ('chunk_by_chunk' mode only). A tile
  2174. # is post-processed at once, using the 'DATA.TEST.PADDING' of its border patches as context, so it covers
  2175. # PATCHES_PER_TILE * ('DATA.PATCH_SIZE' - 2 * 'DATA.TEST.PADDING') voxels per axis. Tiles divide the patches
  2176. # among them, so this does not change the number of patches passed through the model nor their overlap: larger
  2177. # tiles only mean fewer seams between them, and therefore fewer instances split across tiles that instance
  2178. # segmentation has to merge back. Raising it improves the result, and the limit is the RAM available.
  2179. #
  2180. # Each tile being filled holds the prediction of its region plus the padding around it, i.e.
  2181. # (tile + 2 * padding voxels per axis) * model output channels * 4 bytes
  2182. # and post-processing one takes about two more tiles of working memory. Every one of the 'SYSTEM.NUM_GPUS'
  2183. # processes fills as many tiles at the same time as workers it has ('SYSTEM.NUM_WORKERS'), so a job needs about
  2184. # NUM_GPUS * ((NUM_WORKERS + 2) * tile size + 3 GiB)
  2185. # where those 3 GiB are what BiaPy itself takes per GPU (model, CUDA context and the patches in flight).
  2186. #
  2187. # Measured on a (1024,1024,128) volume with 4 GPUs and 5 workers each, a patch of (128,128,128), a padding of
  2188. # (10,10,10) and 12 output channels (peak RAM of the whole job, and the instances split across tiles that the
  2189. # merging has to join back):
  2190. # PATCHES_PER_TILE tile tile size RAM instances found
  2191. # (1,1,1) (108,108,108) 96 MiB 13.7 GiB 953
  2192. # (2,2,2) (216,216,216) 327 MiB 19.7 GiB 836
  2193. # (3,3,3) (324,324,324) 693 MiB 22.9 GiB 828
  2194. #
  2195. # Values to ask for in the same setup, but on a volume large enough for the tiles not to be cut by its borders:
  2196. # RAM of the job PATCHES_PER_TILE tile needs
  2197. # 100 GiB (3,3,3) (324,324,324) 63 GiB
  2198. # 300 GiB (5,5,5) (540,540,540) 232 GiB
  2199. # 500 GiB (6,6,6) (648,648,648) 385 GiB
  2200. # 700 GiB (7,7,7) (756,756,756) 597 GiB
  2201. # 1000 GiB (8,8,8) (864,864,864) 877 GiB
  2202. # Halve the values above if the model outputs twice the channels, and note that the tile size grows with the
  2203. # cube of this value when the three axes are raised together: raise only the axes that need it if the memory
  2204. # gets tight (e.g. (1,2,2) on anisotropic data, or when an axis is already covered by a single tile).
  2205. _C.TEST.BY_CHUNKS.WORKFLOW_PROCESS.PATCHES_PER_TILE = (1, 1, 1)
  2206. # Minimum normalised IoU required to merge two instances across a chunk boundary
  2207. # (instance segmentation, 'chunk_by_chunk' mode only). Must be in (0, 1].
  2208. _C.TEST.BY_CHUNKS.WORKFLOW_PROCESS.INSTANCE_SEG_MERGE_IOU_TH = 0.3
  2209. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2210. # 8.2 Detection test/inference options
  2211. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2212. # To decide which function is going to be used to create point from probabilities. Options: ['peak_local_max', 'blob_log']
  2213. # 'peak_local_max': https://scikit-image.org/docs/stable/api/skimage.feature.html#skimage.feature.peak_local_max
  2214. # 'blob_log': https://scikit-image.org/docs/stable/api/skimage.feature.html#skimage.feature.blob_log
  2215. _C.TEST.DET_POINT_CREATION_FUNCTION = "peak_local_max"
  2216. # The minimal allowed distance separating peaks. To find the maximum number of peaks, use min_distance=1.
  2217. _C.TEST.DET_PEAK_LOCAL_MAX_MIN_DISTANCE = 1
  2218. # Whether the threshold are going to be set as automaticaly (with Otsu thresholding) or manually.
  2219. # Options available: 'auto' or 'manual'. If this last is used TEST.DET_MIN_TH_TO_BE_PEAK needs to be set.
  2220. _C.TEST.DET_TH_TYPE = "manual"
  2221. # Minimun value to consider a point as a peak. Corresponds to 'threshold_abs' argument of the function
  2222. # 'peak_local_max' of skimage.feature
  2223. _C.TEST.DET_MIN_TH_TO_BE_PEAK = 0.2
  2224. # Corresponds to 'exclude_border' argument of 'peak_local_max' or 'blob_log' function of skimage. If True it will exclude
  2225. # peaks from the border of the image to avoid partial detection.
  2226. _C.TEST.DET_EXCLUDE_BORDER = False
  2227. # Corresponds to 'min_sigma' argument of 'blob_log' function. It is the minimum standard deviation for Gaussian kernel.
  2228. # Keep this low to detect smaller blobs. The standard deviations of the Gaussian filter are given for each axis as a
  2229. # sequence, or as a single number, in which case it is equal for all axes.
  2230. _C.TEST.DET_BLOB_LOG_MIN_SIGMA = 5
  2231. # Corresponds to 'max_sigma' argument of 'blob_log' function. It is the maximum standard deviation for Gaussian kernel.
  2232. # Keep this high to detect larger blobs. The standard deviations of the Gaussian filter are given for each axis as a
  2233. # sequence, or as a single number, in which case it is equal for all axes.
  2234. _C.TEST.DET_BLOB_LOG_MAX_SIGMA = 10
  2235. # Corresponds to 'num_sigma' argument of 'blob_log' function. The number of intermediate values of standard deviations
  2236. # to consider between min_sigma and max_sigma.
  2237. _C.TEST.DET_BLOB_LOG_NUM_SIGMA = 2
  2238. # Maximum distance far away from a GT point to consider a point as a true positive
  2239. _C.TEST.DET_TOLERANCE = 10
  2240. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2241. # 8.3 Post-processing options
  2242. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2243. _C.TEST.POST_PROCESSING = CN()
  2244. # To apply median filtering to the data
  2245. _C.TEST.POST_PROCESSING.MEDIAN_FILTER = False
  2246. # List of median filters to apply. They are going to be applied in the list order. This can only be used in
  2247. # 'SEMANTIC_SEG', 'INSTANCE_SEG' and 'DETECTION' workflows. There are multiple options to compose the list:
  2248. # * 'xy' or 'yx': to apply the filter in x and y axes together
  2249. # * 'zy' or 'yz': to apply the filter in y and z axes together
  2250. # * 'zx' or 'xz': to apply the filter in x and z axes together
  2251. # * 'z': to apply the filter only in z axis
  2252. # Those filter that imply 'z' axis are going to be applied only in 3D or in 2D if TEST.ANALIZE_2D_IMGS_AS_3D_STACK is selected
  2253. _C.TEST.POST_PROCESSING.MEDIAN_FILTER_AXIS = []
  2254. _C.TEST.POST_PROCESSING.MEDIAN_FILTER_SIZE = []
  2255. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2256. # 8.3.1 Instance segmentation post-processing options
  2257. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2258. # Instance refinement:
  2259. # Whether to refine the instances with morphological and filtering operations after being created and before any other post-processing
  2260. # such as Voronoi. This instance refinement is applied on each instance individually and sequentially. The two variables,
  2261. # TEST.POST_PROCESSING.INSTANCE_REFINEMENT.PROPS and TEST.POST_PROCESSING.INSTANCE_REFINEMENT.VALUES of refinements to be applied.
  2262. # For instance, the conditions can be like this: ['A', 'B', 'C'] and they will be applied sequentially.
  2263. # A full example of this refinement:
  2264. # _C.DATA.VAL.FILTER_SAMPLES.PROPS = ['fill_holes', 'remove_small_objects', 'remove_large_objects', 'clear_border']
  2265. # _C.DATA.VAL.FILTER_SAMPLES.VALUES = ['none', 10, 2000, 'none']
  2266. _C.TEST.POST_PROCESSING.INSTANCE_REFINEMENT = CN()
  2267. # Enable/disable instance refinement
  2268. _C.TEST.POST_PROCESSING.INSTANCE_REFINEMENT.ENABLE = False
  2269. # List of morphological operations to apply. They are going to be applied in the list order. Available operations are:
  2270. # * 'dilation': to dilate instances
  2271. # * 'erosion': to erode instances
  2272. # * 'fill_holes': to fill holes inside instances
  2273. # * 'clear_border': to remove instances touching the image border
  2274. # * 'remove_small_objects': to remove small objects
  2275. # * 'remove_large_objects': to remove large objects
  2276. _C.TEST.POST_PROCESSING.INSTANCE_REFINEMENT.OPERATIONS = []
  2277. # Values associated to each operation. For 'dilation' and 'erosion' it corresponds to the size of the structuring element (it can also be a list).
  2278. # For 'remove_small_objects' and 'remove_large_objects' it corresponds to the size threshold in pixels.
  2279. # For 'fill_holes' and 'clear_border' no value is needed so put None in those cases.
  2280. _C.TEST.POST_PROCESSING.INSTANCE_REFINEMENT.VALUES = []
  2281. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2282. # 8.3.1.1 Instance property measurement and filtering options
  2283. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2284. # Whether to measure morphological features on each instances, i.e. 'circularity' (2D), 'elongation' (2D), 'npixels', 'area', 'diameter',
  2285. # 'perimeter', 'sphericity' (3D)
  2286. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES = CN()
  2287. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.ENABLE = False
  2288. # List of properties to measure on each instance. The following properties will be always calculated: label, npixels, areas, centers, elongation (2D),
  2289. # sphericities (2D)/circularities (3D), diameters, perimeter (2D)/surface_area (3D). Apart from them, you can select more properties to be calculated
  2290. # based on scikit-image regionprops function. Check the following link for a detailed list of the extra available properties you can request:
  2291. # https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.regionprops
  2292. # Default property description is as follows:
  2293. # * 'circularity' is defined as the ratio of area over the square of the perimeter, normalized such that the value for a disk equals
  2294. # one: (4 * PI * area) / (perimeter^2). Only measurable for 2D images (use sphericity for 3D images). While values of circularity
  2295. # range theoretically within the interval [0;1], the measurements errors of the perimeter may produce circularity values above 1
  2296. # (Lehmann et al., 201211 ; https://doi.org/10.1093/bioinformatics/btw413).
  2297. #
  2298. # * 'elongation' is the inverse of the circularity. The values of elongation range from 1 for round particles and increase for
  2299. # elongated particles. Calculated as: (perimeter^2)/(4 * PI * area) . It is only measurable for 2D images.
  2300. #
  2301. # * 'npixels' corresponds to the sum of pixels that compose an instance.
  2302. #
  2303. # * 'area' corresponds to the number of pixels taking into account the image resolution (we call it 'area' also even in a 3D
  2304. # image for simplicity, but that will be the volume in that case). In the resulting statistics 'volume' will appear in that
  2305. # case too.
  2306. #
  2307. # * 'diameter' calculated with the bounding box and by taking the maximum value of the box in x and y axes. In 3D, z axis
  2308. # is also taken into account. Does not take into account the image resolution.
  2309. #
  2310. # * 'perimeter', in 2D, approximates the contour as a line through the centers of border pixels using a 4-connectivity. In 3D,
  2311. # it corresponds to the surface area.
  2312. #
  2313. # * 'sphericity', in 3D, it is the ratio of the squared volume over the cube of the surface area, normalized such that the value
  2314. # for a ball equals one: (36 * PI)*((volume^2)/(perimeter^3)). Only measurable for 3D images (use circularity for 2D images).
  2315. #
  2316. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.EXTRA_PROPS = []
  2317. # Remove instances by the conditions based in each instance properties. The three variables, TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.PROPS,
  2318. # TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.VALUES and TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.SIGNS will compose a list
  2319. # of conditions to remove the instances. They are list of list of conditions. For instance, the conditions can be like this: [['A'], ['B','C']]. Then, if the instance satisfies
  2320. # the first list of conditions, only 'A' in this first case (from ['A'] list), or satisfy 'B' and 'C' (from ['B','C'] list) it will be
  2321. # removed from the image. In each sublist all the conditions must be satisfied. Available properties are: ['circularity', 'elongation',
  2322. # 'npixels', 'area', 'diameter', 'perimeter', 'sphericity']. When this post-processing step is selected two .csv files
  2323. # will be created, one with the properties of each instance from the original image (will be placed in PATHS.RESULT_DIR.PER_IMAGE_INSTANCES
  2324. # path), and another with only instances that remain once this post-processing has been applied (will be placed in
  2325. # PATHS.RESULT_DIR.PER_IMAGE_POST_PROCESSING path). In those csv files two more information columns will appear: a list of conditions
  2326. # that each instance has satisfy or not ('Satisfied', 'No satisfied' respectively), and a comment with two possible values, 'Removed'
  2327. # and 'Correct', telling you if the instance has been removed or not, respectively. Some of the properties follow the formulas used in
  2328. # MorphoLibJ library for Fiji https://doi.org/10.1093/bioinformatics/btw413
  2329. #
  2330. # A full example of this post-processing:
  2331. # If you want to remove those instances that have less than 100 pixels and circularity less equal to 0.7 you should
  2332. # declare the above three variables as follows:
  2333. # _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.PROPS = [['npixels', 'circularity']]
  2334. # _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.VALUES = [[100, 0.7]]
  2335. # _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.SIGNS = [['lt', 'le']]
  2336. # You can also concatenate more restrictions and they will be applied in order. For instance, if you want to remove those
  2337. # instances that are bigger than an specific area, and do that before the condition described above, you can define the
  2338. # variables this way:
  2339. # _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.PROPS = [['area'], ['npixels', 'circularity']]
  2340. # _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.VALUES = [[500], [100, 0.7]]
  2341. # _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.SIGNS = [['gt'], ['lt', 'le']]
  2342. # This way, the instances will be removed by 'area' and then by 'npixels' and 'circularity'
  2343. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES = CN()
  2344. # Whether to enable or not the filtering by properties
  2345. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.ENABLE = False
  2346. # List of lists of properties to apply a filter. Available properties are: ['circularity', 'elongation', 'npixels', 'area', 'diameter',
  2347. # 'perimeter', 'sphericity']
  2348. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.PROPS = []
  2349. # List of ints/float that represent the values of the properties listed in TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES
  2350. # that the instances need to satisfy to not be dropped.
  2351. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.VALUES = []
  2352. # List of list of signs to do the comparison. Options: ['gt', 'ge', 'lt', 'le'] that corresponds to "greather than", e.g. ">",
  2353. # "greather equal", e.g. ">=", "less than", e.g. "<", and "less equal" e.g. "<=" comparisons.
  2354. _C.TEST.POST_PROCESSING.MEASURE_PROPERTIES.REMOVE_BY_PROPERTIES.SIGNS = []
  2355. # Whether to apply Voronoi using 'BC' or 'M' channels need to be present
  2356. _C.TEST.POST_PROCESSING.VORONOI_ON_MASK = False
  2357. # Threshold to be applied to the 'M' channel when expanding the instances with Voronoi. Need to be in [0,1] range.
  2358. # Leave it to 0 to adjust the threhold with Otsu
  2359. _C.TEST.POST_PROCESSING.VORONOI_TH = 0.0
  2360. # Set it to try to repare large instances by merging their neighbors with them and removing possible central holes.
  2361. # Its value determines which instances are going to be repared by size (number of pixels that compose the instance)
  2362. # This option is useful when PROBLEM.INSTANCE_SEG.DATA_CHANNELS is 'BP', as multiple central seeds may appear in big
  2363. # instances. Only works in Instance segmentation workflow.
  2364. _C.TEST.POST_PROCESSING.REPARE_LARGE_BLOBS_SIZE = -1
  2365. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2366. # 8.3.2 Detection post-processing options
  2367. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2368. # To remove close points to each other. This can also be set when using 'BP' channels for instance segmentation.
  2369. _C.TEST.POST_PROCESSING.REMOVE_CLOSE_POINTS = False
  2370. # Distance between points to be considered the same. Only applies when TEST.POST_PROCESSING.REMOVE_CLOSE_POINTS = True
  2371. # This can also be set when using 'BP' channels for instance segmentation.
  2372. _C.TEST.POST_PROCESSING.REMOVE_CLOSE_POINTS_RADIUS = 0
  2373. # Whether to apply a watershed to grow the points detected
  2374. _C.TEST.POST_PROCESSING.DET_WATERSHED = False
  2375. # Structure to dilate the initial seeds before watershed. For instance in a 3D problem: [10,10,4]
  2376. _C.TEST.POST_PROCESSING.DET_WATERSHED_FIRST_DILATION = [-1, -1]
  2377. # List of classes to be consider as 'donuts'. For those class points, the 'donuts' type cell means that their nucleus is
  2378. # to big and that the seeds need to be dilated more so the watershed can grow the instances properly.
  2379. _C.TEST.POST_PROCESSING.DET_WATERSHED_DONUTS_CLASSES = [-1]
  2380. # Patch shape to extract all donuts type cells. It needs to be a bit greater than bigest donuts type cell so all of them can
  2381. # be contained in this patch. This is used to analize that area for each point of class `DET_WATERSHED_DONUTS_CLASSES`.
  2382. _C.TEST.POST_PROCESSING.DET_WATERSHED_DONUTS_PATCH = [13, 120, 120]
  2383. # Diameter (in pixels) that a cell need to have to be considered as donuts type
  2384. _C.TEST.POST_PROCESSING.DET_WATERSHED_DONUTS_NUCLEUS_DIAMETER = 30
  2385. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2386. # 9. Auxiliary paths
  2387. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2388. _C.PATHS = CN()
  2389. # Directories to store the results
  2390. _C.PATHS.RESULT_DIR = CN()
  2391. _C.PATHS.RESULT_DIR.PATH = os.path.join(job_dir, "results", job_identifier)
  2392. _C.PATHS.RESULT_DIR.PER_IMAGE = os.path.join(_C.PATHS.RESULT_DIR.PATH, "per_image")
  2393. _C.PATHS.RESULT_DIR.PER_IMAGE_BIN = os.path.join(_C.PATHS.RESULT_DIR.PATH, "per_image_binarized")
  2394. _C.PATHS.RESULT_DIR.PER_IMAGE_INSTANCES = os.path.join(_C.PATHS.RESULT_DIR.PATH, "per_image_instances")
  2395. _C.PATHS.RESULT_DIR.PER_IMAGE_POST_PROCESSING = os.path.join(
  2396. _C.PATHS.RESULT_DIR.PATH, "per_image_post_processing"
  2397. )
  2398. _C.PATHS.RESULT_DIR.FULL_IMAGE = os.path.join(_C.PATHS.RESULT_DIR.PATH, "full_image")
  2399. _C.PATHS.RESULT_DIR.FULL_IMAGE_BIN = os.path.join(_C.PATHS.RESULT_DIR.PATH, "full_image_binarized")
  2400. _C.PATHS.RESULT_DIR.FULL_IMAGE_INSTANCES = os.path.join(_C.PATHS.RESULT_DIR.PATH, "full_image_instances")
  2401. _C.PATHS.RESULT_DIR.FULL_IMAGE_POST_PROCESSING = os.path.join(
  2402. _C.PATHS.RESULT_DIR.PATH, "full_image_post_processing"
  2403. )
  2404. _C.PATHS.RESULT_DIR.AS_3D_STACK = os.path.join(_C.PATHS.RESULT_DIR.PATH, "as_3d_stack")
  2405. _C.PATHS.RESULT_DIR.AS_3D_STACK_BIN = os.path.join(_C.PATHS.RESULT_DIR.PATH, "as_3d_stack_binarized")
  2406. _C.PATHS.RESULT_DIR.AS_3D_STACK_POST_PROCESSING = os.path.join(
  2407. _C.PATHS.RESULT_DIR.PATH, "as_3d_stack_post_processing"
  2408. )
  2409. _C.PATHS.RESULT_DIR.DET_LOCAL_MAX_COORDS_CHECK = os.path.join(
  2410. _C.PATHS.RESULT_DIR.PATH, "per_image_local_max_check"
  2411. )
  2412. _C.PATHS.RESULT_DIR.DET_LOCAL_MAX_COORDS_CHECK_POST_PROCESSING = os.path.join(
  2413. _C.PATHS.RESULT_DIR.PATH, "per_image_local_max_check_post_processing"
  2414. )
  2415. _C.PATHS.RESULT_DIR.DET_ASSOC_POINTS = os.path.join(_C.PATHS.RESULT_DIR.PATH, "point_associations")
  2416. _C.PATHS.RESULT_DIR.INST_ASSOC_POINTS = os.path.join(_C.PATHS.RESULT_DIR.PATH, "instance_associations")
  2417. # Path to store the BMZ model created
  2418. _C.PATHS.BMZ_EXPORT_PATH = os.path.join(_C.PATHS.RESULT_DIR.PATH, "BMZ_files")
  2419. # Path to store profiler files
  2420. _C.PATHS.PROFILER = os.path.join(_C.PATHS.RESULT_DIR.PATH, "profiler")
  2421. # Name of the folder where the charts of the loss and metrics values while training the network are stored.
  2422. _C.PATHS.CHARTS = os.path.join(_C.PATHS.RESULT_DIR.PATH, "charts")
  2423. # Folder where TRAIN.SAVE_TRAIN_PREDS_FREQ previews are stored.
  2424. _C.PATHS.TRAIN_PRED_SAMPLES = os.path.join(_C.PATHS.RESULT_DIR.PATH, "train_pred_samples")
  2425. # Folder where samples of DA will be stored
  2426. _C.PATHS.DA_SAMPLES = os.path.join(_C.PATHS.RESULT_DIR.PATH, "aug")
  2427. # Folder where generator samples (X) will be stored
  2428. _C.PATHS.GEN_CHECKS = os.path.join(_C.PATHS.RESULT_DIR.PATH, "gen_check")
  2429. # Folder where generator samples (Y) will be stored
  2430. _C.PATHS.GEN_MASK_CHECKS = os.path.join(_C.PATHS.RESULT_DIR.PATH, "gen_mask_check")
  2431. # Paths where a few samples of instance channels created will be stored just to check id there is any problem
  2432. _C.PATHS.TRAIN_INSTANCE_CHANNELS_CHECK = os.path.join(
  2433. _C.PATHS.RESULT_DIR.PATH,
  2434. "train_" + "".join(_C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS) + "_instance_channels",
  2435. )
  2436. _C.PATHS.VAL_INSTANCE_CHANNELS_CHECK = os.path.join(
  2437. _C.PATHS.RESULT_DIR.PATH,
  2438. "val_" + "".join(_C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS) + "_instance_channels",
  2439. )
  2440. _C.PATHS.TEST_INSTANCE_CHANNELS_CHECK = os.path.join(
  2441. _C.PATHS.RESULT_DIR.PATH,
  2442. "test_" + "".join(_C.PROBLEM.INSTANCE_SEG.DATA_CHANNELS) + "_instance_channels",
  2443. )
  2444. # Name of the folder where weights files will be stored/loaded from.
  2445. _C.PATHS.CHECKPOINT = os.path.join(job_dir, "checkpoints")
  2446. # Checkpoint file to load/store the model weights
  2447. _C.PATHS.CHECKPOINT_FILE = ""
  2448. # Name of the folder to store the probability map to avoid recalculating it on every run.
  2449. # Overridden at runtime to "<DATA.TRAIN.GT_PATH>_prob_maps" (see create_train_val_augmentors),
  2450. # mirroring the DATA.TRAIN.INSTANCE_CHANNELS_MASK_DIR/DETECTION_MASK_DIR naming convention.
  2451. _C.PATHS.PROB_MAP_DIR = os.path.join(job_dir, "prob_map")
  2452. _C.PATHS.PROB_MAP_FILENAME = "prob_map.npy"
  2453. # Watershed debugging folder
  2454. _C.PATHS.WATERSHED_DIR = os.path.join(_C.PATHS.RESULT_DIR.PATH, "watershed")
  2455. # Path where the images used in MAE will be saved suring inference
  2456. _C.PATHS.MAE_OUT_DIR = os.path.join(_C.PATHS.RESULT_DIR.PATH, "MAE_checks")
  2457. # Directory to save filtered images.
  2458. _C.PATHS.FIL_SAMPLES_DIR = os.path.join(_C.PATHS.RESULT_DIR.PATH, "filtering_information")
  2459. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2460. # 10. Logging
  2461. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2462. _C.LOG = CN()
  2463. _C.LOG.LOG_DIR = os.path.join(job_dir, "logs")
  2464. _C.LOG.TENSORBOARD_LOG_DIR = os.path.join(_C.PATHS.RESULT_DIR.PATH, "tensorboard")
  2465. _C.LOG.LOG_FILE_PREFIX = job_identifier
  2466. _C.LOG.CHART_CREATION_FREQ = 5
  2467. self._C = _C
  2468. def get_cfg_defaults(self) -> CN:
  2469. """
  2470. Get a clone of the default configuration.
  2471. Returns
  2472. -------
  2473. CN
  2474. A cloned YACS CfgNode object with default values.
  2475. """
  2476. # Return a clone so that the defaults will not be altered
  2477. # This is for the "local variable" use pattern
  2478. return self._C.clone()
  2479. def to_dict(self):
  2480. """
  2481. Convert the configuration to a Python dictionary.
  2482. Returns
  2483. -------
  2484. dict
  2485. Dictionary representation of the configuration.
  2486. """
  2487. return dict(self._C)
  2488. def copy(self):
  2489. """
  2490. Create a deep copy of the Config object.
  2491. Returns
  2492. -------
  2493. Config
  2494. A deep copy of the current Config instance.
  2495. """
  2496. return copy.deepcopy(self)
  2497. def __str__(self):
  2498. """
  2499. Return a string representation of the Config object.
  2500. Returns
  2501. -------
  2502. str
  2503. String representation of the configuration.
  2504. """
  2505. return str(self.__dict__)
  2506. def __repr__(self):
  2507. """
  2508. Return a string representation of the Config object.
  2509. Returns
  2510. -------
  2511. str
  2512. String representation of the configuration.
  2513. """
  2514. return str(self.__dict__)
  2515. def update_dependencies(cfg) -> None:
  2516. """
  2517. Update dependent configuration variables after merging user config.
  2518. This function should be called after merging a user-provided .cfg file
  2519. to ensure that all dependent paths and variables are updated accordingly.
  2520. That is, this function should be called after YACS's merge_from_file().
  2521. Parameters
  2522. ----------
  2523. cfg : Config or CN
  2524. The configuration object to update.
  2525. """
  2526. call = getattr(cfg, "_C") if bool(getattr(cfg, "_C", False)) else cfg
  2527. # Remove possible / characters at the end of the paths
  2528. call.DATA.TRAIN.PATH = (
  2529. call.DATA.TRAIN.PATH if call.DATA.TRAIN.PATH[-1] != "/" else call.DATA.TRAIN.PATH[:-1]
  2530. )
  2531. call.DATA.TRAIN.GT_PATH = (
  2532. call.DATA.TRAIN.GT_PATH if call.DATA.TRAIN.GT_PATH[-1] != "/" else call.DATA.TRAIN.GT_PATH[:-1]
  2533. )
  2534. call.DATA.VAL.PATH = (
  2535. call.DATA.VAL.PATH if call.DATA.VAL.PATH[-1] != "/" else call.DATA.VAL.PATH[:-1]
  2536. )
  2537. call.DATA.VAL.GT_PATH = (
  2538. call.DATA.VAL.GT_PATH if call.DATA.VAL.GT_PATH[-1] != "/" else call.DATA.VAL.GT_PATH[:-1]
  2539. )
  2540. call.DATA.TEST.PATH = (
  2541. call.DATA.TEST.PATH if call.DATA.TEST.PATH[-1] != "/" else call.DATA.TEST.PATH[:-1]
  2542. )
  2543. call.DATA.TEST.GT_PATH = (
  2544. call.DATA.TEST.GT_PATH if call.DATA.TEST.GT_PATH[-1] != "/" else call.DATA.TEST.GT_PATH[:-1]
  2545. )
  2546. tdata = call.DATA.TRAIN.GT_PATH if not call.DATA.TRAIN.INPUT_ZARR_MULTIPLE_DATA else call.DATA.TRAIN.PATH
  2547. call.DATA.TRAIN.INSTANCE_CHANNELS_MASK_DIR = tdata
  2548. cpd = '_'.join([str(x) for x in call.PROBLEM.DETECTION.CENTRAL_POINT_DILATION])
  2549. call.DATA.TRAIN.DETECTION_MASK_DIR = call.DATA.TRAIN.GT_PATH + "_detection_masks_" + str(cpd)
  2550. call.DATA.TRAIN.SSL_SOURCE_DIR = call.DATA.TRAIN.PATH + "_ssl_source"
  2551. vdata = call.DATA.VAL.GT_PATH if not call.DATA.VAL.INPUT_ZARR_MULTIPLE_DATA else call.DATA.VAL.PATH
  2552. call.DATA.VAL.INSTANCE_CHANNELS_MASK_DIR = vdata
  2553. # If value is not the default
  2554. call.DATA.VAL.DETECTION_MASK_DIR = call.DATA.VAL.GT_PATH + "_detection_masks_" + str(cpd)
  2555. call.DATA.VAL.SSL_SOURCE_DIR = call.DATA.VAL.PATH + "_ssl_source"
  2556. tdata = call.DATA.TEST.GT_PATH if not call.DATA.TEST.INPUT_ZA

config.py at commit c560d40, under MIT · at the source

Overview

Authors: Pablo Ruiz-Amezcua1,2,3, Daniel Franco-Barranco4,5,6, David Reigada1,3, Teresa Muñoz-Galdeano1,3, Rodrigo M Maza1,3, Manuel Nieto-Diaz1,3
  1. Hospital Nacional de Parapléjicos (SESCAM), Toledo, Spain
  2. Department of Experimental Biology, University of Jaén, Jaén, Spain
  3. Instituto de Investigación Sanitaria de Castilla-La Mancha (IDISCAM), Toledo, Spain
  4. MRC Laboratory of Molecular Biology, Cambridge, UK
  5. Department of Physiology, Development and Neuroscience, University of Cambridge, Cambridge, UK
  6. Donostia International Physics Center (DIPC), San Sebastián, Spain
Journal: Scientific reports, volume 16, issue 1, article 28309
Dates: received 9 February 2026; accepted 8 June 2026; published online 20 June 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1038/s41598-026-57519-w · PMID 42323434 · PMCID PMC13558734 · OpenAlex W7165363949
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: histology / microscopy (modality), mouse (organism), other condition (population), methods / tools (subfield)
Methods: Connectivity, Machine learning
Keywords: Spinal cord injury, Mouse models, Instance segmentation, Semantic representations, Histology, Biological techniques, Computational biology and bioinformatics, Neuroscience
MeSH: Deep Learning*, Image Processing, Computer-Assisted*, Neurons*, Spinal Cord*, Spinal Cord Injuries*, Animals, Fluorescent Antibody Technique, Mice (* major topic)
Topic: Cell Image Analysis Techniques (Biophysics, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Funding: Council of Education, Culture and Sports of the Regional Government of Castilla-La Mancha (Spain) (SBPLY/21/180501/000097); Council of Education, Culture and Sports of the Regional Government of Castilla-La 322 Mancha (Spain) and co-financed by the European Union (FEDER), “A way to make Europe”
Citations: not cited yet (Europe PMC); 45 references in the paper

Abstract

In this study, we present SpineDL, an open-source deep learning (DL) approach for neuron and anatomical structure segmentation of the spinal cord in fluorescence images immunostained with NeuN and DAPI, within the context of murine models of spinal cord injury (SCI). SpineDL comprises two main modules: SpineDL-Neuron, for instance-level identification of neuronal somas; and SpineDL-Structure, for semantic segmentation of key spinal cord structures including gray matter, white matter, ependyma, and damaged tissue. To train the models, we developed the SpineDL dataset, a curated collection of 161 confocal images of mouse spinal cord, manually annotated by SCI researchers and organized into specific subsets. Both models are based on the HRNetV2-W64 architecture and were trained using state-of-the-art data augmentation and optimization techniques, implemented within the BiaPy framework, following an iterative refinement process driven by quantitative evaluation, SCI researcher feedback, and systematic error analysis. Our results demonstrate that SpineDL achieves researcher-level performance in both structural segmentation and neuron identification tasks, showing high robustness across anatomical regions and injury conditions. Overall, this work provides a reproducible and extensible platform for quantitative analysis of neuron distribution in the naïve and injured spinal cord, supporting automation, standardization, and scalability of histopathological workflows in neuroscience research and preclinical studies and translational applications.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 6 matches between paragraphs and lines of code.

biapy.readthedocs.io

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: the link answers
Software Heritage: not checked
Found in: “Code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)

biapyx/biapy

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: c560d4053c46f57eb6c7a3d32f87bdd3ba2c2966, 26 September 2026
Languages: Python (144), Jupyter (32), Shell (1)
Size: 244 files, 177 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, environment (pyproject.toml, .github/workflows/conda-forge-bump.yml, biapy/utils/env/conda_forge_meta.yaml, biapy/utils/env/Dockerfile), tests, continuous integration, 32 notebooks
Not found: CITATION.cff, documentation
Tools: NumPy (97 files), PyTorch (67 files), scikit-image (46 files), Matplotlib (24 files), SciPy (23 files), pandas (20 files), h5py (15 files), Pillow (6 files), OpenCV (4 files), scikit-learn (4 files), Numba (2 files), tifffile (2 files), imageio (1 file), NetworkX (1 file), NiBabel (1 file), Plotly (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
153 files

Code availability

The experiments were performed using the open-source BiaPy library 21, available on GitHub (https://github.com/BiaPyX/BiaPy/tree/master). To facilitate reuse and reproducibility, we developed two comprehensive tutorials: one for the SpineDL-Structure workflow (https://biapy.readthedocs.io/en/latest/tutorials/semantic_seg/SpineDL-structure.html) and another for the SpineDL-Neuron workflow (https://biapy.readthedocs.io/en/latest/tutorials/instance_seg/SpineDL-neuron.html). In addition, both trained models have been published in the BioImage Model Zoo. The SpineDL-Structure model is available as “greedy-deer” (https://bioimage.io/#/artifacts/greedy-deer), and the SpineDL-Neuron model as “proactive-snail” (https://bioimage.io/#/artifacts/proactive-snail).

Reproduced under the paper's license (CC BY), from the paper cited above.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 151 scripts, each with its path and the digest of its content;
  • 6 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Data availability

The SpineDL dataset is available in the Zenodo repository (https://zenodo.org/records/17829532) under the CC BY 4.0 license. Additional metadata, raw images, and information on the subjects included in this study are available in the NeuroCluedo OSF repository (https://osf.io/n32z9/overview), also under the CC BY 4.0 license.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 8 keywords, 8 MeSH terms, 2 funders, 29 references.

Cite

This paper

Ruiz-Amezcua, P., Franco-Barranco, D., Reigada, D., Muñoz-Galdeano, T., Maza, R. M., & Nieto-Diaz, M. (2026). Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL. Scientific reports, 16(1), 28309. https://doi.org/10.1038/s41598-026-57519-w

BibTeX

@article{ruizamezcua2026automated,
author = {Ruiz-Amezcua, Pablo and Franco-Barranco, Daniel and Reigada, David and Muñoz-Galdeano, Teresa and Maza, Rodrigo M and Nieto-Diaz, Manuel},
title = {{Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL}},
journal = {Scientific reports},
year = {2026},
month = jun,
volume = {16},
number = {1},
pages = {28309},
publisher = {Nature Publishing Group},
issn = {2045-2322},
doi = {10.1038/s41598-026-57519-w},
url = {https://doi.org/10.1038/s41598-026-57519-w},
pmid = {42323434},
pmcid = {PMC13558734}
}

RIS

TY - JOUR
AU - Ruiz-Amezcua, Pablo
AU - Franco-Barranco, Daniel
AU - Reigada, David
AU - Muñoz-Galdeano, Teresa
AU - Maza, Rodrigo M
AU - Nieto-Diaz, Manuel
TI - Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL
T2 - Scientific reports
J2 - Sci Rep
PY - 2026
DA - 2026/06/20
VL - 16
IS - 1
SP - 28309
SN - 2045-2322
PB - Nature Publishing Group
DO - 10.1038/s41598-026-57519-w
UR - https://doi.org/10.1038/s41598-026-57519-w
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41598-026-57519-w",
"type": "article-journal",
"title": "Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL",
"container-title": "Scientific reports",
"author": [
{
"family": "Ruiz-Amezcua",
"given": "Pablo"
},
{
"family": "Franco-Barranco",
"given": "Daniel"
},
{
"family": "Reigada",
"given": "David"
},
{
"family": "Muñoz-Galdeano",
"given": "Teresa"
},
{
"family": "Maza",
"given": "Rodrigo M"
},
{
"family": "Nieto-Diaz",
"given": "Manuel"
}
],
"container-title-short": "Sci Rep",
"volume": "16",
"issue": "1",
"page": "28309",
"DOI": "10.1038/s41598-026-57519-w",
"PMID": "42323434",
"PMCID": "PMC13558734",
"ISSN": "2045-2322",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41598-026-57519-w",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
20
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1016/j.xcrm.2026.102766 [code]
A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.
Journal: Cell reports. Medicine
In common: imageio, tifffile, Numba, 11 other tools, other condition
[2] doi:10.1371/journal.pcbi.1014571 [code]
SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.
Journal: PLoS computational biology
In common: imageio, tifffile, Numba, 10 other tools, 1 reference
[3] doi:10.3389/fnsys.2026.1822122 [code]
Convergence-divergence circuits for multimodal integration of innate and learned opponent valences.
Journal: Frontiers in systems neuroscience
In common: tifffile, Numba, NetworkX, 11 other tools
[4] doi:10.1371/journal.pcbi.1013499 [code]
VesiclePy: A machine learning vesicle analysis toolbox for volume electron microscopy.
Journal: PLoS computational biology
In common: imageio, Plotly, OpenCV, 9 other tools, histology / microscopy, methods / tools, 1 reference
[5] doi:10.1038/s41467-026-73373-w [code]
Mapping neuro-vascular unit communications reveals distinct angiogenic programs across developing mouse brain regions.
Journal: Nature communications
In common: imageio, tifffile, OpenCV, 10 other tools, mouse
[6] doi:10.7554/elife.100880 [code]
An applicable and efficient retrograde monosynaptic circuit mapping tool for larval zebrafish.
Journal: eLife
In common: tifffile, Numba, NetworkX, 10 other tools
[7] doi:10.1016/j.isci.2026.116825 [code]
Social hierarchy shapes behavioral and transcriptional responses to chronic stress and ketamine in male mice.
Journal: iScience
In common: Numba, NetworkX, Plotly, 10 other tools, mouse
[8] doi: [code]
Real-time closed-loop feedback system for mouse mesoscale cortical signal and movement control
Journal: eLife
In common: imageio, tifffile, Numba, 9 other tools, mouse
[9] doi:10.7554/elife.109717 [code]
Retrosplenial cortex enables context-dependent goal-directed sensorimotor transformation.
Journal: eLife
In common: imageio, tifffile, Numba, 9 other tools, mouse
[10] doi:10.1016/j.stemcr.2026.103015 [code]
Brain injury reactivates a developmental program driving genesis and integration of transient LGE-class interneurons.
Journal: Stem cell reports
In common: tifffile, Numba, NetworkX, 8 other tools, mouse, 1 reference

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.