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 338 339 340 341 342 343 344 345
|
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
"""
Mathematical Operations Module
------------------------------
This module implements mathematical operations on images, such as inversion,
absolute value, real/imaginary part extraction, type casting, and exponentiation.
Main features include:
- Pixel-wise mathematical transformations (e.g., log, exp, abs, real, imag, log10)
- Type casting and other value-level operations
These functions enable flexible manipulation of image data at the value level.
"""
# 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 guidata.dataset as gds
import numpy as np
import sigima.tools.image
from sigima.config import _
from sigima.config import options as sigima_options
from sigima.enums import AngleUnit
from sigima.objects.image import ImageObj
from sigima.proc.base import AngleUnitParam, PhaseParam
from sigima.proc.decorator import computation_function
from sigima.proc.image.base import (
Wrap1to1Func,
dst_1_to_1,
dst_2_to_1,
restore_data_outside_roi,
)
from sigima.tools import coordinates
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__ = [
"DataTypeIParam",
"Log10ZPlusNParam",
"absolute",
"absolute",
"astype",
"complex_from_magnitude_phase",
"complex_from_real_imag",
"convolution",
"deconvolution",
"exp",
"exp",
"imag",
"imag",
"inverse",
"inverse",
"log10",
"log10",
"log10_z_plus_n",
"phase",
"real",
"real",
]
@computation_function()
def inverse(src: ImageObj) -> ImageObj:
"""Compute the inverse of an image and return the new result image object
Args:
src: input image object
Returns:
Result image object 1 / **src** (new object)
"""
dst = dst_1_to_1(src, "inverse")
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
dst.data = np.reciprocal(src.data, dtype=float)
dst.data[np.isinf(dst.data)] = np.nan
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def absolute(src: ImageObj) -> ImageObj:
"""Compute absolute value with :py:data:`numpy.absolute`
Args:
src: input image object
Returns:
Output image object
"""
return Wrap1to1Func(np.absolute)(src)
@computation_function()
def real(src: ImageObj) -> ImageObj:
"""Compute real part with :py:func:`numpy.real`
Args:
src: input image object
Returns:
Output image object
"""
return Wrap1to1Func(np.real)(src)
@computation_function()
def imag(src: ImageObj) -> ImageObj:
"""Compute imaginary part with :py:func:`numpy.imag`
Args:
src: input image object
Returns:
Output image object
"""
return Wrap1to1Func(np.imag)(src)
@computation_function()
def phase(src: ImageObj, p: PhaseParam) -> ImageObj:
"""Compute the phase (argument) of a complex image.
The function uses :py:func:`numpy.angle` to compute the argument and
:py:func:`numpy.unwrap` to unwrap it.
Args:
src: Input image object.
p: Phase parameters.
Returns:
Image object containing the phase, optionally unwrapped.
"""
suffix = "unwrap" if p.unwrap else ""
dst = dst_1_to_1(src, "phase", suffix)
data = src.get_data()
argument = np.angle(data)
if p.unwrap:
argument = np.unwrap(argument)
if p.unit == AngleUnit.DEGREE:
argument = np.rad2deg(argument)
dst.data = argument
dst.zunit = p.unit
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def complex_from_magnitude_phase(
src1: ImageObj, src2: ImageObj, p: AngleUnitParam
) -> ImageObj:
"""Combine magnitude and phase images into a complex image.
.. warning::
This function assumes that the input images have the same dimensions.
Args:
src1: Magnitude (module) image.
src2: Phase (argument) image.
p: Parameters (provides unit for the phase).
Returns:
Image object with complex-valued z.
"""
dst = dst_2_to_1(src1, src2, "mag_phase")
assert p.unit is not None
dst.data = coordinates.polar_to_complex(src1.data, src2.data, unit=p.unit)
return dst
@computation_function()
def complex_from_real_imag(src1: ImageObj, src2: ImageObj) -> ImageObj:
"""Combine two real images into a complex image using real + i * imag.
.. warning::
This function assumes that the input images have the same dimensions and are
properly aligned.
Args:
src1: Real part image.
src2: Imaginary part image.
Returns:
Image object with complex-valued z.
Raises:
ValueError: If the x or y coordinates of the two images are not the same.
"""
dst = dst_2_to_1(src1, src2, "real_imag")
assert src1.data is not None
assert src2.data is not None
dst.data = src1.data + 1j * src2.data
return dst
@computation_function()
def convolution(src: ImageObj, kernel: ImageObj) -> ImageObj:
"""Convolve an image with a kernel.
The kernel should ideally be smaller than the input image and centered.
Args:
src: Input image object.
kernel: Kernel image object.
Returns:
Output image object.
Notes:
The behavior of kernel normalization is controlled by the global configuration
option ``sigima.config.options.auto_normalize_kernel``.
"""
# Get configuration option for kernel normalization
normalize_kernel = sigima_options.auto_normalize_kernel.get()
dst = dst_2_to_1(src, kernel, "⊛")
dst.data = sigima.tools.image.convolve(
src.data,
kernel.data,
normalize_kernel_flag=normalize_kernel,
)
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def deconvolution(src: ImageObj, kernel: ImageObj) -> ImageObj:
"""Deconvolve a kernel from an image using Fast Fourier Transform (FFT).
Args:
src: Input image object.
kernel: Kernel image object.
Returns:
Output image object.
Notes:
The behavior of kernel normalization is controlled by the global configuration
option ``sigima.config.options.auto_normalize_kernel``.
"""
# Get configuration option for kernel normalization
normalize_kernel = sigima_options.auto_normalize_kernel.get()
dst = dst_2_to_1(src, kernel, "⊛⁻¹")
dst.data = sigima.tools.image.deconvolve(
src.data,
kernel.data,
normalize_kernel_flag=normalize_kernel,
)
restore_data_outside_roi(dst, src)
return dst
@computation_function()
def log10(src: ImageObj) -> ImageObj:
"""Compute log10 with :py:data:`numpy.log10`
Args:
src: input image object
Returns:
Output image object
"""
return Wrap1to1Func(np.log10)(src)
@computation_function()
def exp(src: ImageObj) -> ImageObj:
"""Compute exponential with :py:data:`numpy.exp`
Args:
src: input image object
Returns:
Output image object
"""
return Wrap1to1Func(np.exp)(src)
class Log10ZPlusNParam(gds.DataSet):
"""Log10(z+n) parameters"""
n = gds.FloatItem("n")
@computation_function()
def log10_z_plus_n(src: ImageObj, p: Log10ZPlusNParam) -> ImageObj:
"""Compute log10(z+n) with :py:data:`numpy.log10`
Args:
src: input image object
p: parameters
Returns:
Output image object
"""
dst = dst_1_to_1(src, "log10_z_plus_n", f"n={p.n}")
dst.data = np.log10(src.data + p.n)
restore_data_outside_roi(dst, src)
return dst
class DataTypeIParam(gds.DataSet):
"""Convert image data type parameters"""
dtype_str = gds.ChoiceItem(
_("Destination data type"),
list(zip(ImageObj.get_valid_dtypenames(), ImageObj.get_valid_dtypenames())),
help=_("Output image data type."),
)
@computation_function()
def astype(src: ImageObj, p: DataTypeIParam) -> ImageObj:
"""Convert image data type with :py:func:`sigima.tools.datatypes.clip_astype`
Args:
src: input image object
p: parameters
Returns:
Output image object
"""
dst = dst_1_to_1(src, "clip_astype", p.dtype_str)
dst.data = clip_astype(src.data, p.dtype_str)
return dst
|