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
|
# -*- coding: utf-8 -*-
"""
Image preprocessing functions.
This module consolidates preprocessing functions that were previously scattered
across different modules (exposure, geometry, fourier). All functions in this
module operate on high-level ImageObj objects and use parameter classes from
the sigima.proc framework.
"""
from __future__ import annotations
import guidata.dataset as gds
import numpy as np
import sigima.enums
import sigima.tools.image
from sigima.config import _
from sigima.enums import PadLocation2D
from sigima.objects.image import ImageObj
from sigima.proc.decorator import computation_function
from sigima.proc.image.base import dst_1_to_1
__all__ = [
"BinningParam",
"ZeroPadding2DParam",
"binning",
"zero_padding",
]
class BinningParam(gds.DataSet):
"""Binning parameters."""
sx = gds.IntItem(
_("Cluster size (X)"),
default=2,
min=2,
help=_("Number of adjacent pixels to be combined together along X-axis."),
)
sy = gds.IntItem(
_("Cluster size (Y)"),
default=2,
min=2,
help=_("Number of adjacent pixels to be combined together along Y-axis."),
)
operation = gds.ChoiceItem(
_("Operation"),
sigima.enums.BinningOperation,
default=sigima.enums.BinningOperation.SUM,
)
dtypes = ["dtype"] + ImageObj.get_valid_dtypenames()
dtype_str = gds.ChoiceItem(
_("Data type"),
list(zip(dtypes, dtypes)),
help=_("Output image data type."),
)
change_pixel_size = gds.BoolItem(
_("Change pixel size"),
default=True,
help=_(
"If checked, pixel size is updated according to binning factors. "
"Users who prefer to work with pixel coordinates may want to uncheck this."
),
)
@computation_function()
def binning(src: ImageObj, p: BinningParam) -> ImageObj:
"""Binning: image pixel binning (or aggregation).
Depending on the algorithm, the input image may be cropped to fit an integer
number of blocks.
Args:
src: source image
p: parameters
Returns:
Output image
Raises:
ValueError: if source image has non-uniform coordinates
"""
if not src.is_uniform_coords:
raise ValueError("Binning only works with images having uniform coordinates")
# Create destination image
dst = dst_1_to_1(
src,
"binning",
f"{p.sx}x{p.sy},{p.operation},change_pixel_size={p.change_pixel_size}",
)
dst.data = sigima.tools.image.binning(
src.data,
sx=p.sx,
sy=p.sy,
operation=p.operation,
dtype=None if p.dtype_str == "dtype" else p.dtype_str,
)
if p.change_pixel_size:
if not np.isnan(src.dx) and not np.isnan(src.dy):
# Update coordinates with new pixel spacing
new_dx = src.dx * p.sx
new_dy = src.dy * p.sy
dst.set_uniform_coords(new_dx, new_dy, src.x0, src.y0)
return dst
class ZeroPadding2DParam(gds.DataSet):
"""Zero padding parameters for 2D images"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.__obj: ImageObj | None = None
def update_from_obj(self, obj: ImageObj) -> None:
"""Update parameters from image"""
self.__obj = obj
self.choice_callback(None, self.strategy)
def choice_callback(self, item, value): # pylint: disable=unused-argument
"""Callback to update padding values"""
if self.__obj is None:
return
rows, cols = self.__obj.data.shape
if value == "next_pow2":
self.rows = 2 ** int(np.ceil(np.log2(rows))) - rows
self.cols = 2 ** int(np.ceil(np.log2(cols))) - cols
elif value == "multiple_of_64":
self.rows = (64 - rows % 64) if rows % 64 != 0 else 0
self.cols = (64 - cols % 64) if cols % 64 != 0 else 0
strategies = ("next_pow2", "multiple_of_64", "custom")
_prop = gds.GetAttrProp("strategy")
strategy = gds.ChoiceItem(
_("Padding strategy"), zip(strategies, strategies), default=strategies[-1]
).set_prop("display", store=_prop, callback=choice_callback)
_func_prop = gds.FuncProp(_prop, lambda x: x == "custom")
rows = gds.IntItem(_("Rows to add"), min=0, default=0).set_prop(
"display", active=_func_prop
)
cols = gds.IntItem(_("Columns to add"), min=0, default=0).set_prop(
"display", active=_func_prop
)
position = gds.ChoiceItem(
_("Padding position"), PadLocation2D, default=PadLocation2D.BOTTOM_RIGHT
)
@computation_function()
def zero_padding(
src: ImageObj,
p: ZeroPadding2DParam | None = None,
) -> ImageObj:
"""Zero-padding: add zeros to image borders.
Args:
src: input image object
p: parameters
Returns:
Output image object
"""
if p is None:
p = ZeroPadding2DParam.create()
if p.strategy == "custom":
suffix = f"rows={p.rows}, cols={p.cols}"
else:
suffix = f"strategy={p.strategy}"
suffix += f", position={p.position}"
dst = dst_1_to_1(src, "zero_padding", suffix)
result = sigima.tools.image.zero_padding(
src.data,
rows=p.rows,
cols=p.cols,
position=p.position,
)
dst.data = result
return dst
|