1 2 3 4 5 6 7 8 9 10 11 12 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 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 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 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
|
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
"""
Arithmetic computation module
-----------------------------
This module provides arithmetic operations for images, such as pixel-wise addition,
subtraction, multiplication, division, as well as operations with constants
and combined arithmetic formulas.
Main features include:
- Pixel-wise addition, subtraction, multiplication, and division between images
- Application of arithmetic operations with constants to images
- Support for quadratic difference and general arithmetic expressions
These functions are typically used for basic algebraic processing and normalization
of image data.
"""
# pylint: disable=invalid-name # Allows short reference names like x, y, ...
# Note:
# ----
# - All `guidata.dataset.DataSet` parameter classes must also be imported
# in the `sigima.params` module.
# - All functions decorated by `computation_function` must be imported in the upper
# level `sigima.proc.image` module.
from __future__ import annotations
import warnings
import numpy as np
from sigima.enums import MathOperator
from sigima.objects.image import ImageObj
from sigima.proc.base import (
ArithmeticParam,
ConstantParam,
)
from sigima.proc.decorator import computation_function
from sigima.proc.image.base import (
dst_1_to_1,
dst_2_to_1,
dst_n_to_1,
restore_data_outside_roi,
)
from sigima.tools.datatypes import clip_astype
# NOTE: Only parameter classes DEFINED in this module should be included in __all__.
# Parameter classes imported from other modules (like sigima.proc.base) should NOT
# be re-exported to avoid Sphinx cross-reference conflicts. The sigima.params module
# serves as the central API point that imports and re-exports all parameter classes.
__all__ = [
"addition",
"addition_constant",
"arithmetic",
"average",
"difference",
"difference_constant",
"division",
"division",
"division_constant",
"product",
"product_constant",
"quadratic_difference",
"standard_deviation",
]
# MARK: compute_n_to_1 functions -------------------------------------------------------
# Functions with N input images and 1 output image
# --------------------------------------------------------------------------------------
# Those functions are perfoming a computation on N input images and return a single
# output image. If we were only executing these functions locally, we would not need
# to define them here, but since we are using the multiprocessing module, we need to
# define them here so that they can be pickled and sent to the worker processes.
# Also, we need to systematically return the output image object, even if it is already
# modified in place, because the multiprocessing module will not be able to retrieve
# the modified object from the worker processes.
@computation_function()
def addition(src_list: list[ImageObj]) -> ImageObj:
"""Add images in the list and return the result image object
Args:
src_list: list of input image objects
Returns:
Output image object (modified in place)
"""
dst = dst_n_to_1(src_list, "Σ") # `dst` data is initialized to `src_list[0]` data
for src in src_list[1:]:
dst.data = np.add(dst.data, src.data, dtype=float)
restore_data_outside_roi(dst, src_list[0])
return dst
@computation_function()
def average(src_list: list[ImageObj]) -> ImageObj:
"""Compute the average of images in the list and return the result image object
Args:
src_list: list of input image objects
Returns:
Output image object (modified in place)
"""
dst = dst_n_to_1(src_list, "µ") # `dst` data is initialized to `src_list[0]` data
for src in src_list[1:]:
dst.data = np.add(dst.data, src.data, dtype=float)
dst.data /= len(src_list)
restore_data_outside_roi(dst, src_list[0])
return dst
@computation_function()
def standard_deviation(src_list: list[ImageObj]) -> ImageObj:
"""Compute the element-wise standard deviation of multiple images.
The first image in the list defines the "base" image. All other images are
used to compute the element-wise standard deviation with the base image.
.. note::
If all images share the same region of interest (ROI), the standard deviation
is computed only within the ROI.
.. warning::
It is assumed that all images have the same size and x-coordinates.
Args:
src_list: List of source images.
Returns:
Image object representing the standard deviation of the source images.
"""
dst = dst_n_to_1(src_list, "𝜎") # `dst` data is initialized to `src_list[0]` data
assert dst.data is not None
y_array = np.array([src.data for src in src_list], dtype=dst.data.dtype)
dst.data = np.std(y_array, axis=0, ddof=0)
restore_data_outside_roi(dst, src_list[0])
return dst
@computation_function()
def product(src_list: list[ImageObj]) -> ImageObj:
"""Multiply images in the list and return the result image object
Args:
src_list: list of input image objects
Returns:
Output image object (modified in place)
"""
dst = dst_n_to_1(src_list, "Π") # `dst` data is initialized to `src_list[0]` data
for src in src_list[1:]:
dst.data = np.multiply(dst.data, src.data, dtype=float)
restore_data_outside_roi(dst, src_list[0])
return dst
@computation_function()
def addition_constant(src: ImageObj, p: ConstantParam) -> ImageObj:
"""Add **dst** and a constant value and return the new result image object
Args:
src: input image object
p: constant value
Returns:
Result image object **src** + **p.value** (new object)
"""
# For the addition of a constant value, we convert the constant value to the same
# data type as the input image, for consistency.
value = np.array(p.value).astype(dtype=src.data.dtype)
dst = dst_1_to_1(src, "+", str(value))
dst.data = np.add(src.data, value, dtype=float)
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def difference_constant(src: ImageObj, p: ConstantParam) -> ImageObj:
"""Subtract a constant value from an image and return the new result image object
Args:
src: input image object
p: constant value
Returns:
Result image object **src** - **p.value** (new object)
"""
# For the subtraction of a constant value, we convert the constant value to the same
# data type as the input image, for consistency.
value = np.array(p.value).astype(dtype=src.data.dtype)
dst = dst_1_to_1(src, "-", str(value))
dst.data = np.subtract(src.data, value, dtype=float)
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def product_constant(src: ImageObj, p: ConstantParam) -> ImageObj:
"""Multiply **dst** by a constant value and return the new result image object
Args:
src: input image object
p: constant value
Returns:
Result image object **src** * **p.value** (new object)
"""
# For the multiplication by a constant value, we do not convert the constant value
# to the same data type as the input image, because we want to allow the user to
# multiply an image by a constant value of a different data type. The final data
# type conversion ensures that the output image has the same data type as the input
# image.
dst = dst_1_to_1(src, "×", str(p.value))
dst.data = np.multiply(src.data, p.value, dtype=float)
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def division_constant(src: ImageObj, p: ConstantParam) -> ImageObj:
"""Divide an image by a constant value and return the new result image object
Args:
src: input image object
p: constant value
Returns:
Result image object **src** / **p.value** (new object)
"""
# For the division by a constant value, we do not convert the constant value to the
# same data type as the input image, because we want to allow the user to divide an
# image by a constant value of a different data type. The final data type conversion
# ensures that the output image has the same data type as the input image.
dst = dst_1_to_1(src, "/", str(p.value))
dst.data = np.divide(src.data, p.value, dtype=float)
restore_data_outside_roi(dst, src)
return dst
# MARK: compute_2_to_1 functions -------------------------------------------------------
# Functions with N input images + 1 input image and N output images
# --------------------------------------------------------------------------------------
@computation_function()
def arithmetic(src1: ImageObj, src2: ImageObj, p: ArithmeticParam) -> ImageObj:
"""Compute arithmetic operation on two images
Args:
src1: input image object
src2: input image object
p: arithmetic parameters
Returns:
Result image object
"""
initial_dtype = src1.data.dtype
title = p.operation.replace("obj1", "{0}").replace("obj2", "{1}")
dst = src1.copy(title=title)
o, a, b = p.operator, p.factor, p.constant
# Apply operator
if o in (MathOperator.MULTIPLY, MathOperator.DIVIDE) and a == 0.0:
dst.data = np.ones_like(src1.data) * b
elif o == MathOperator.ADD:
dst.data = np.add(src1.data, src2.data, dtype=float) * a + b
elif o == MathOperator.SUBTRACT:
dst.data = np.subtract(src1.data, src2.data, dtype=float) * a + b
elif o == MathOperator.MULTIPLY:
dst.data = np.multiply(src1.data, src2.data, dtype=float) * a + b
elif o == MathOperator.DIVIDE:
dst.data = np.divide(src1.data, src2.data, dtype=float) * a + b
# Eventually convert to initial data type
if p.restore_dtype:
dst.data = clip_astype(dst.data, initial_dtype)
restore_data_outside_roi(dst, src1)
return dst
@computation_function()
def difference(src1: ImageObj, src2: ImageObj) -> ImageObj:
"""Compute difference between two images
Args:
src1: input image object
src2: input image object
Returns:
Result image object **src1** - **src2** (new object)
"""
dst = dst_2_to_1(src1, src2, "-")
dst.data = np.subtract(src1.data, src2.data, dtype=float)
restore_data_outside_roi(dst, src1)
return dst
@computation_function()
def quadratic_difference(src1: ImageObj, src2: ImageObj) -> ImageObj:
"""Compute quadratic difference between two images
Args:
src1: input image object
src2: input image object
Returns:
Result image object (**src1** - **src2**) / sqrt(2.0) (new object)
"""
dst = dst_2_to_1(src1, src2, "quadratic_difference")
dst.data = np.subtract(src1.data, src2.data, dtype=float) / np.sqrt(2.0)
restore_data_outside_roi(dst, src1)
return dst
@computation_function()
def division(src1: ImageObj, src2: ImageObj) -> ImageObj:
"""Compute division between two images
Args:
src1: input image object
src2: input image object
Returns:
Result image object **src1** / **src2** (new object)
"""
dst = dst_2_to_1(src1, src2, "/")
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
dst.data = np.divide(src1.data, src2.data, dtype=float)
restore_data_outside_roi(dst, src1)
return dst
|