Common
This page acts as the technical reference for the common subpackage.
The common package provides typical utilities used with all the other packages in this project, including - Classes and functions for IO operations. - Enums used with various classes. - General mathematical functions and transformation operations in both function and Class forms.
BaseFileSettings
Bases: ABC
Base class for implementing classes that manage IO operations.
BaseFileSettings acts as the guideline for designing classes for camera_linearity_torch's IO operations.
Attributes
input_path: Path a filepath from which the data will be read. output_path: Path a filepath to which data can be saved. Based on the optional output_path init argument. If None is given, then the parent directory of input_path is used as a root in which a new directory called based on default_output_root is created, in which the same filename as the input_path's name will be used to create a new file upon saving. default_output_root: Path a default dirpath to utilize as the directory in which the output file is created upon saving. Based on the default_output_root init argument. If None is given, then defaults to a new dirpath called 'clair_torch_output' in the directory of the input file. cpu_transforms: Transform | Sequence[Transform] | None Optional collection of Transforms that will be performed on the data right after reading it from a file.
Source code in clair_torch/common/base.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
__init__(input_path, output_path=None, default_output_root=None, cpu_transforms=None)
Initializes the instance with the given paths. Output and default roots are optional and defer to a default output root if None is given. output_path overrides any possible default_output_root values. Upon loading data the given cpu_transforms are performed on the data sequentially. Args: input_path: the path at which the file is found. output_path: the path to which output a modified file. default_output_root: a root directory path to utilize if no output_path is given. cpu_transforms: Transform(s) to be performed on the data on the cpu-side upon loading the data.
Source code in clair_torch/common/base.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
|
get_all_metadata()
abstractmethod
Method for getting all the metadata associated with a file. Should always return at least an empty dict. Returns: dict[str, int | float | str]
Source code in clair_torch/common/base.py
122 123 124 125 126 127 128 129 |
|
get_input_paths()
abstractmethod
Method for getting the input path(s) from a FileSettings class. Returns: A single Path or tuple of Paths.
Source code in clair_torch/common/base.py
77 78 79 80 81 82 83 84 |
|
get_numeric_metadata()
abstractmethod
Method for getting numeric metadata associated with a file. Should always return at least an empty dict. Returns: dict[str, int | float]
Source code in clair_torch/common/base.py
104 105 106 107 108 109 110 111 |
|
get_output_paths()
abstractmethod
Method for getting the output path(s) from a FileSettings class. Returns: A single Path or tuple of Paths.
Source code in clair_torch/common/base.py
86 87 88 89 90 91 92 93 |
|
get_text_metadata()
abstractmethod
Method for getting the text metadata associated with a file. Should always return at least an empty dict. Returns: dict[str, str]
Source code in clair_torch/common/base.py
113 114 115 116 117 118 119 120 |
|
get_transforms()
abstractmethod
Method for getting the possible Transform operations from a FileSettings class. Returns: A list of Transforms or None if no Transforms are given.
Source code in clair_torch/common/base.py
95 96 97 98 99 100 101 102 |
|
BaseTransform
Bases: ABC
Base class for Transform classes, which typically wrap a function from general functions. Must be callable, taking a torch.Tensor as input and return a torch.Tensor.
Source code in clair_torch/common/transforms.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
|
from_config(cfg)
classmethod
Deserialization function, which initializes a new instance from a dictionary representation of the class. Args: cfg: the configuration dictionary.
Returns:
Type | Description |
---|---|
A new instance of this class. |
Source code in clair_torch/common/transforms.py
53 54 55 56 57 58 59 60 61 62 63 64 |
|
to_config()
abstractmethod
Serialization function, which dumps the instance into a dictionary representation. Returns: dictionary that can be used to deserialize back into an equivalent instance.
Source code in clair_torch/common/transforms.py
45 46 47 48 49 50 51 |
|
CastTo
Bases: BaseTransform
Transform for casting the tensor to the given datatype and device. If data_type or device are not give, then maintain them as they are.
Source code in clair_torch/common/transforms.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
|
ClampAlongDims
Bases: BaseTransform
Transform for clamping the tensor values between a min and max value, along the given dimension(s).
Source code in clair_torch/common/transforms.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
|
CvToTorch
Bases: BaseTransform
Transform for modifying a tensor from OpenCV dimensions and channel ordering to a PyTorch dimensionality and ordering.
Source code in clair_torch/common/transforms.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
|
FileSettings
Bases: BaseFileSettings
Class for managing input and output paths related to an arbitrary file. Main use is to manage the IO settings for use inside a PyTorch Dataset class.
Attributes:
Inherits attributes from BaseFileSettings.
Source code in clair_torch/common/file_settings.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
__init__(input_path, output_path=None, default_output_root=None, cpu_transforms=None)
Initializes the instance with the given paths. Output and default roots are optional and defer to a default output root if None is given. output_path overrides any possible default_output_root values. Upon loading data the given cpu_transforms are performed on the data sequentially. Args: input_path: the path at which the file is found. output_path: the path to which output a modified file. default_output_root: a root directory path to utilize if no output_path is given. cpu_transforms: Transform(s) to be performed on the data on the cpu-side upon loading the data.
Source code in clair_torch/common/file_settings.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
get_all_metadata()
Unused method stub inherited from the base class. This is used in classes further down the subclass tree. Returns: Empty dict.
Source code in clair_torch/common/file_settings.py
94 95 96 97 98 99 100 |
|
get_candidate_std_output_path()
Method for getting a candidate output path for an uncertainty file. Returns: Constructed uncertainty file output path based on the main input file and its filetype suffix.
Source code in clair_torch/common/file_settings.py
59 60 61 62 63 64 65 66 67 68 |
|
get_input_paths()
Method for getting the input path. Returns: Path.
Source code in clair_torch/common/file_settings.py
43 44 45 46 47 48 49 |
|
get_numeric_metadata()
Unused method stub inherited from the base class. This is used in classes further down the subclass tree. Returns: Empty dict.
Source code in clair_torch/common/file_settings.py
78 79 80 81 82 83 84 |
|
get_output_paths()
Method for getting the output path. Returns: Path.
Source code in clair_torch/common/file_settings.py
51 52 53 54 55 56 57 |
|
get_text_metadata()
Unused method stub inherited from the base class. This is used in classes further down the subclass tree. Returns: Empty dict.
Source code in clair_torch/common/file_settings.py
86 87 88 89 90 91 92 |
|
get_transforms()
Method for getting the possible Transform operations to be performed on the data upon reading it. Returns: List[Transform] or None, if no Transform operations were given on init.
Source code in clair_torch/common/file_settings.py
70 71 72 73 74 75 76 |
|
FrameSettings
Bases: FileSettings
Class for managing input and output paths related to an arbitrary file, with the addition of managing image related metadata. Main use is to manage the IO settings for use inside a PyTorch Dataset class.
Attributes:
Inherits attributes from FileSettings. metadata: BaseMetadata an encapsulated instance of a BaseMetadata subclass for managing the metadata related to images.
Source code in clair_torch/common/file_settings.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
|
get_all_metadata()
Method for getting all the metadata managed by the encapsulated Metadata class. Returns: dict[str, str | int | float | None].
Source code in clair_torch/common/file_settings.py
140 141 142 143 144 145 146 |
|
get_numeric_metadata()
Method for getting the numeric metadata managed by the encapsulated Metadata class. Returns: dict[str, int | float].
Source code in clair_torch/common/file_settings.py
124 125 126 127 128 129 130 |
|
get_text_metadata()
Method for getting the text metadata managed by the encapsulated Metadata class. Returns: dict[str, str].
Source code in clair_torch/common/file_settings.py
132 133 134 135 136 137 138 |
|
is_match(reference, attributes)
Method for evaluating whether the metadata contained in a given FramSettings instance or Metadata instance are a match based on the given sequence of attributes, which act as keys to the metadata dictionary in a Metadata instance. Args: reference: a FrameSettings instance or a BaseMetadata subclass instance. attributes: a sequence of string, which define the dictionary keys, whose associated values must be equal for a successful match.
Returns:
Type | Description |
---|---|
bool
|
bool, True for a successful match, False for failed. |
Source code in clair_torch/common/file_settings.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
|
InterpMode
Bases: Enum
Manages the interpolation modes used in ICRF model classes.
Source code in clair_torch/common/enums.py
10 11 12 13 14 15 16 |
|
MissingStdMode
Bases: Enum
Manages how missing uncertainty images are dealt with in ImageDataset classes.
Source code in clair_torch/common/enums.py
33 34 35 36 37 38 39 |
|
Normalize
Bases: BaseTransform
Transform for normalizing a tensor by a minimum and maximum value. If no values are given, dynamically use min and max of the given tensor.
Source code in clair_torch/common/transforms.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
|
PairedFileSettings
Bases: FileSettings
Class for managing input and output paths of a pair of arbitrary files. Main use is to handle the paired IO operations of a value image and its associated uncertainty image. Composed of two instances of FileSettings.
Attributes:
Inherits attributes from FileSettings.
Source code in clair_torch/common/file_settings.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
|
__init__(val_input_path, std_input_path=None, val_output_path=None, std_output_path=None, default_output_root=None, val_cpu_transforms=None, std_cpu_transforms=None)
Initializes a PairedFileSettings object with the given paths. The class both inherits from FileSettings and is a composition of two instances of FileSettings. Referring to self.val_input_path is the same as referring to self.val_settings.input_path, same follows for other attributes. PairedFileSettings should only be used when an uncertainty input file does exist, even though the std_input_path parameter is Optional. The optionality is left to enable easy implicit seeking of std files. Use regular FileSettings if no uncertainty files are to be used. Args: val_input_path: input path for the main value file. std_input_path: input path for the associated uncertainty file. val_output_path: output path for the modified value file. std_output_path: output path for the modified uncertainty file. default_output_root: a root directory path to utilize if no output_path is given. val_cpu_transforms: transform operations for the value file. std_cpu_transforms transform operations for the uncertainty file.
Source code in clair_torch/common/file_settings.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
|
get_input_paths()
Method for getting the input paths of a PairedFileSettings instance. Overrides the inherited method by deferring the process for the two encapsulated instances. Returns: Tuple of Paths, first for value file, second for uncertainty file.
Source code in clair_torch/common/file_settings.py
225 226 227 228 229 230 231 232 |
|
get_output_paths()
Method for getting the output paths of a PairedFileSettings instance. Overrides the inherited method by deferring the process for the two encapsulated instances. Returns: Tuple of paths, first for value file, second for uncertainty file.
Source code in clair_torch/common/file_settings.py
234 235 236 237 238 239 240 241 |
|
get_transforms()
Method for getting the transformation operations. Overrides the inherited method by deferring the process for the two encapsulated instances. Returns: Tuple of Lists of Transforms, first for value file Transforms, second for uncertainty file Transforms.
Source code in clair_torch/common/file_settings.py
243 244 245 246 247 248 249 250 |
|
PairedFrameSettings
Bases: PairedFileSettings
Class for managing paired files with their associated metadatas, based on the PairedFileSettings class.
Attributes:
Inherits attributes from PairedFileSettings. val_metadata: BaseMetadata an encapsulated instance of a BaseMetadata subclass for managing the metadata related to the value image. std_metadata: BaseMetadata an encapsulated instance of a BaseMetadata subclass for managing the metadata related to the possible uncertainty image. Typically, these are equal to the val_metadata values, so by default this is not parsed. The parse_std_meta init argument is used to determine whether the std_metadata is parsed or not.
Source code in clair_torch/common/file_settings.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
|
__init__(val_input_path, std_input_path=None, val_output_path=None, std_output_path=None, default_output_root=None, val_cpu_transforms=None, std_cpu_transforms=None, parse_std_meta=False, metadata_cls=ImagingMetadata, *metadata_args, **metadata_kwargs)
File settings related aspects are all delegated to the PairedFileSettings super class. Additional responsibility for this class is maintaining and allowing access to the metadatas of each of the encapsulated files via subclasses of BaseMetadata. Args: val_input_path: input path for the main value file. std_input_path: input path for the associated uncertainty file. val_output_path: output path for the modified value file. std_output_path: output path for the modified uncertainty file. default_output_root: a root directory path to utilize if no output_path is given. val_cpu_transforms: transform operations for the value file. std_cpu_transforms transform operations for the uncertainty file. parse_std_meta: whether to parse a Metadata class instance for the STD file. metadata_cls: a subclass of BaseMetadata metadata_args: additional args to pass to instantiating the given metadata_cls. *metadata_kwargs: additional kwargs to pass to instantiating the given metadata_cls.
Source code in clair_torch/common/file_settings.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
|
get_all_metadata()
Method for getting all the metadata of the value image. Returns: dict[str, str | int | float | None]
Source code in clair_torch/common/file_settings.py
319 320 321 322 323 324 325 |
|
get_numeric_metadata()
Method for getting the numeric metadata of the value image. Returns: dict[str, float | int | None]
Source code in clair_torch/common/file_settings.py
303 304 305 306 307 308 309 |
|
get_text_metadata()
Method for getting the text metadata of the value image. Returns: dict[str, str | None]
Source code in clair_torch/common/file_settings.py
311 312 313 314 315 316 317 |
|
is_match(reference, attributes)
Method for evaluating whether the metadata contained in a given FramSettings instance or Metadata instance are a match based on the given sequence of attributes, which act as keys to the metadata dictionary in a Metadata instance. Utilizes the val_metadata associated with the value image. Args: reference: a FrameSettings instance or a BaseMetadata subclass instance. attributes: a sequence of string, which define the dictionary keys, whose associated values must be equal for a successful match.
Returns:
Type | Description |
---|---|
bool
|
bool, True for a successful match, False for failed. |
Source code in clair_torch/common/file_settings.py
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
|
StridedDownscale
Bases: BaseTransform
Transform for applying a spatial downscale on the input tensor.
Source code in clair_torch/common/transforms.py
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
|
TorchToCv
Bases: BaseTransform
Transform for converting a tensor from PyTorch (C, H, W) format with RGB channels to OpenCV format (H, W, C) with BGR channels.
Source code in clair_torch/common/transforms.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
|
VarianceMode
Bases: Enum
Manages how the variance is computed in the WBOMeanVar class.
Source code in clair_torch/common/enums.py
64 65 66 67 68 69 70 |
|
WBOMean
Bases: object
Source code in clair_torch/common/statistics.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
__init__(dim=0)
Weighted batched online mean (WBOMean). Allows the computation of a weighted mean value of a dataset in a single pass. Attributes are read-only properties and the user only needs to assign the dimension(s) over which the value is computed and supply the batches of new values and their associated weights. Args: dim: the dimension(s) along which to compute the values.
Source code in clair_torch/common/statistics.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
internal_detach(*, in_place=True)
Break the autograd graph attached to the internal state. Args: in_place: Whether to call detach so the tensor is modified in-place or to put into a new tensor.
Source code in clair_torch/common/statistics.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
|
update_values(batch_values, batch_weights=None)
The public method for updating the weighted mean value. Returns the new mean on update. Args: batch_values: the new batch of values used for updating the collective weighted mean. batch_weights: the new batch of weights associated with the given batch_values.
Returns:
Type | Description |
---|---|
Tensor
|
The new mean value as a float or Tensor. |
Source code in clair_torch/common/statistics.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
|
WBOMeanVar
Bases: WBOMean
Source code in clair_torch/common/statistics.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
|
__init__(dim=0, variance_mode=VarianceMode.RELIABILITY_WEIGHTS)
Weighted batched online mean and variance. Allows the computation of a weighted mean and variance of a dataset in a single pass. Attributes are read-only properties and the user only needs to assign the dimension(s) over which the value is computed and supply the batches of new values and their associated weights. Args: dim: the dimension(s) along which to compute the values. variance_mode: determines the normalization method to compute the variance.
Source code in clair_torch/common/statistics.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
|
internal_detach(*, in_place=True)
Break the autograd graph attached to the internal state. Args: in_place: Whether to call detach so the tensor is modified in-place or to put into a new tensor.
Source code in clair_torch/common/statistics.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
|
update_values(batch_values, batch_weights=None)
The public method for updating the weighted mean value. Returns the new mean on update. Args: batch_values: the new batch of values used for updating the collective weighted mean. batch_weights: the new batch of weights associated with the given batch_values.
Returns:
Type | Description |
---|---|
tuple[float | Tensor, float | Tensor]
|
The new mean value and variance values as tuple of floats or tensors. |
Source code in clair_torch/common/statistics.py
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
|
clamp_along_dims(x, dim, min_max_pairs)
Clamp a tensor along specified dimension(s).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
dim
|
int | tuple[int, ...]
|
int or tuple of ints, dimensions along which to apply min/max. |
required |
min_max_pairs
|
tuple[float, float] | list[tuple[float, float]]
|
Single tuple (min, max) applied to all slices. List of tuples; length must match the number of slices along dims. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Clamped tensor of same shape as x. |
Source code in clair_torch/common/general_functions.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
|
cli_parse_args_from_config()
CLI utility function to read parameter values from a .yaml config file into a dictionary. Returns: dictionary of the parsed keys and values.
Source code in clair_torch/common/general_functions.py
489 490 491 492 493 494 495 496 497 498 499 500 501 502 |
|
conditional_gaussian_blur(image, mask_map, threshold, kernel_size, differentiable=False, alpha=50.0)
Apply a gaussian blur on input image positions at which the given map has value larger than the given threshold. Optionally use a differentiable soft mask instead of a boolean mask.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
Tensor
|
input image of shape (..., C, H, W). |
required |
mask_map
|
Tensor
|
map for filtering. Shape must be (1, C, H, W) or (N, C, H, W), where N matches the batch dimension of image or is 1 (broadcasted). |
required |
threshold
|
float
|
threshold value for filtering. |
required |
kernel_size
|
int
|
size of the gaussian blur kernel. |
required |
differentiable
|
bool
|
if True, use a soft differentiable mask via sigmoid. |
False
|
alpha
|
float
|
steepness of sigmoid when differentiable=True. |
50.0
|
Returns:
Type | Description |
---|---|
Tensor
|
Filtered image, same shape as input. |
Source code in clair_torch/common/general_functions.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
|
cv_to_torch(x)
Function for transforming a tensor with OpenCV channel and dimension ordering into PyTorch channel and dimension ordering. Expects a tensor with two or three dimensions. Args: x: tensor to transform.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor |
Source code in clair_torch/common/general_functions.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
file_settings_constructor(dir_paths, file_pattern, recursive=False, default_output_root=None, val_cpu_transforms=None, std_cpu_transforms=None, metadata_cls=None, strict_exclusive=True, *metadata_args, **metadata_kwargs)
Utility function for creating instances of FileSettings, PairedFileSettings, FrameSettings and PairedFrameSettings classes. FrameSettings classes are created when a metadata class is provided, otherwise FileSettings are created. The created objects are assigned to three categories, each having a list of their own to hold the objects: 1. Paired files, containing either PairedFrameSettings or PairedFileSettings objects. 2. Main files, containing either FrameSettings or FileSettings objects. 3. Uncertainty files, containing either FrameSettings or FileSettings objects. The strict_exclusive parameter controls whether a file can be present in the objects of multiple categories of only one. In strict mode, for example, the main file and uncertainty file present in a PairedSettings object aren't allowed to also be present in a Settings object in the main and uncertainty categories. Args: dir_paths: one or multiple paths from which to collect files for creating objects. file_pattern: a regex pattern for the file search. Use '.png' for example to search for any .png file. recursive: whether to extend the file search recursively to subdirectories of the given paths. default_output_root: optional default output root directory for the created objects. val_cpu_transforms: optional main file transform operations to attach to the created objects. std_cpu_transforms: optional uncertainty file transform operations to attach to the created objects. metadata_cls: a subclass of BaseMetadata to use in creating FrameSettings and PairedFrameSettings objects. strict_exclusive: whether to allow a particular file to exist in multiple object categories, or only in the highest priority one. metadata_args: args for the instantiation of the given metadata_cls. **metadata_kwargs: kwargs for the instantiation of the given metadata_cls.
Returns:
Source code in clair_torch/common/file_settings.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
|
flat_field_mean(flat_field, mid_area_side_fraction)
Computes the spatial mean over a centered square ROI for each image and channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
flat_field
|
Tensor
|
Input tensor of shape (N, C, H, W) |
required |
mid_area_side_fraction
|
float
|
Fraction of spatial dims to use for the ROI. Must lie in range [0.0, 1.0]. |
required |
Returns:
Name | Type | Description |
---|---|---|
Tensor |
Tensor
|
Mean over the ROI, shape (...) |
Source code in clair_torch/common/general_functions.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
|
flatfield_correction(images, flatfield, flatfield_mean_val, epsilon=1e-06)
Computes a flat-field corrected version of input image by utilizing the given flat-field image and a given spatial mean. Ideally expects both images and flatfield in shape (N, C, H, W) but others are allowed. Match argument shapes based on requirements. For example with images (N, C, H, W) use flatfield (1, C, H, W) to apply same flatfield across the batch dimension, (N, 1, H, W) to apply unique flatfields across batch while disregarding channel specific features. Similarly, use flatfield_mean_val (1, C, 1, 1) to apply channel-specific scaling uniformly across the batch.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Tensor
|
Image tensor of shape (N, C, H, W). |
required |
flatfield
|
Tensor
|
Flat field calibration image, same shape as |
required |
flatfield_mean_val
|
Tensor
|
Values used to scale the image. Match shape based on the given images and flatfield. |
required |
epsilon
|
float
|
Small constant to avoid division by zero. |
1e-06
|
Returns:
Name | Type | Description |
---|---|---|
Tensor |
Tensor
|
Corrected image tensor, same shape as input. |
Source code in clair_torch/common/general_functions.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
|
get_pairwise_valid_pixel_mask(image_value_stack, i_idx, j_idx, image_std_stack=None, val_lower=0.0, val_upper=1.0, std_lower=None, std_upper=None)
For a batch of images, for all pairs given by indices i_idx and j_idx, compute a pairwise boolean mask by marking invalid pixels as False, if they lie outside the valid range defined by lower and upper, in either one of the images in a given pair. Args: image_value_stack: batch of value images, shape (N, C, H, W). i_idx: the first set of indices to create pairs off of, shape (P,). j_idx: the second set of indices to create pairs off of, shape (P,). image_std_stack: batch of uncertainty images associated with the images in image_value_stack, shape (N, C, H, W). val_lower: lower threshold for marking pixels as invalid in value image. val_upper: upper threshold for marking pixels as invalid in value image. std_lower: lower threshold for marking pixels as invalid in std image. std_upper: upper threshold for marking pixels as invalid in std image.
Returns:
Type | Description |
---|---|
Tensor
|
A boolean tensor that marks invalid pixel positions in a pair with False, shape (P, C, H, W). |
Source code in clair_torch/common/general_functions.py
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
|
get_valid_exposure_pairs(increasing_exposure_values, exposure_ratio_threshold=None)
Generate valid (i, j) index pairs for exposure comparison, based on a minimum ratio threshold.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
increasing_exposure_values
|
Tensor
|
Shape (N,) exposure values in an increasing order. |
required |
exposure_ratio_threshold
|
float
|
Minimum exposure ratio to accept a pair. |
None
|
Returns:
Type | Description |
---|---|
tuple[Tensor, Tensor, Tensor]
|
Tuple of: - i_idx: (P,) indices of first images in valid pairs (i < j) - j_idx: (P,) indices of second images - ratio_pairs: (P,) exposure ratios exposure[i] / exposure[j] |
Source code in clair_torch/common/general_functions.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
|
group_frame_settings_by_attributes(list_of_frame_settings, attributes)
Sort FrameSettings objects into separate groups based on the values of the given attributes. Args: list_of_frame_settings: list of the FrameSettings to sort. attributes: the attributes to base the grouping on.
Returns:
Type | Description |
---|---|
List[Tuple[dict[str, str | float | int], List[FrameSettings]]]
|
List of tuples, the first item in the tuple containing a dictionary of the attributes used to generate that |
List[Tuple[dict[str, str | float | int], List[FrameSettings]]]
|
group. The second item in the tuple contains a list of the FrameSettings objects belonging to that group. |
Source code in clair_torch/common/file_settings.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
|
load_icrf_txt(path, source_channel_order=ChannelOrder.BGR, source_dimension_order=DimensionOrder.BSC)
Utility function for loading an inverse camera response function from a .txt file. Expects a 2D NumPy array with shape (N, C), with N representing the number of datapoints Args: path: path to the text file containing the ICRF data. source_channel_order: the order in which the channels are expected to be in the file. source_dimension_order: the order in which the dimensions are expected to be in the file.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor representing the ICRF. |
Source code in clair_torch/common/data_io.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
|
load_image(file_path, transforms=None)
Generic function to load a single image from the given path. Allows also the definition of transformations to be performed on the image before returning it upstream. Args: file_path: path to the image file. transforms: single Transform or Iterable of Transforms to be performed on the image before returning it.
Returns:
Type | Description |
---|---|
Tensor
|
The loaded and possibly operated image in Tensor format. |
Source code in clair_torch/common/data_io.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
|
load_principal_components(file_paths)
Loads principal component data from text files, one file per color channel. The files in the input paths should be ordered in the desired channel order. E.g. for RGB images it should point to the red, green and blue files in order.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_paths
|
list[str | Path]
|
List of paths to the .txt files (one per channel). |
required |
Returns:
Type | Description |
---|---|
Tensor
|
A torch.Tensor of shape (n_points, n_components, channels). |
Source code in clair_torch/common/data_io.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
|
load_video_frames_generator(file_path, transforms=None)
Function for loading frames from a video file through a generator. Args: file_path: path to the video file. transforms: optional list of transform operations to perform on each frame before yielding them.
Returns:
Type | Description |
---|---|
None
|
Generator, which yields torch.Tensors. |
Source code in clair_torch/common/data_io.py
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
|
normalize_tensor(x, max_val=None, min_val=None, target_range=(0.0, 1.0))
Normalize a tensor by a given min and max value. If not provided, uses the min and max of the tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
max_val
|
Optional[float]
|
Optional maximum value for normalization. |
None
|
min_val
|
Optional[float]
|
Optional minimum value for normalization. |
None
|
target_range
|
tuple[float, float]
|
Tuple specifying the (min, max) target range. |
(0.0, 1.0)
|
Returns:
Type | Description |
---|---|
Tensor
|
The normalized tensor. |
Source code in clair_torch/common/general_functions.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
|
save_icrf_txt(icrf, path, target_channel_order=ChannelOrder.BGR, target_dimension_order=DimensionOrder.BSC)
Utility function to save an ICRF into a .txt file of the given filepath. Args: icrf: the ICRF tensor. target_channel_order: the order in which the channels are to be in the saved data. target_dimension_order: the order in which the dimensions are to be in the saved data. path: the filepath where to save the file.
Returns:
Type | Description |
---|---|
None
|
None |
Source code in clair_torch/common/data_io.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
save_image(tensor, image_save_path, dtype=np.dtype('float64'), params=None)
Save a PyTorch tensor as a 32-bit float per channel TIFF image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tensor
|
Tensor
|
A PyTorch tensor of shape (C, H, W) or (H, W), dtype float32. |
required |
image_save_path
|
str | Path
|
Path to save the image. |
required |
dtype
|
dtype
|
the NumPy datatype to use to save the image. |
dtype('float64')
|
params
|
Optional[Sequence[int]]
|
Sequence of params to pass to OpenCV imwrite function. |
None
|
Source code in clair_torch/common/data_io.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
|
weighted_mean_and_std(values, weights=None, mask=None, dim=None, keepdim=False, eps=1e-08, compute_std=True)
Computes the weighted mean and variance of values
, with optional weights and boolean mask.
Args:
values (Tensor): Input tensor.
weights (Tensor or None): Optional weights, broadcastable to values
.
mask (Tensor or None): Optional boolean mask, where True = valid value.
dim (int or tuple of ints): Axis or axes to reduce over.
keepdim (bool): Keep reduced dimensions.
eps (float): Small value to avoid division by zero.
compute_std: whether to compute std or not.
Returns:
Type | Description |
---|---|
(mean, variance)
|
Tuple of tensors, each of the reduced shape. |
Source code in clair_torch/common/general_functions.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|