Source code for ddd_pylib.image_manip._projection_operator
from ddd_pylib._base import ImageOperator
import xarray as xr
import numpy as np
[docs]
class ProjectionOperator(ImageOperator):
"""
Flattens (project) an image along a given axis using a specified projection method.
The projection method can be one of the following:
- 'Max'
- 'Min'
- 'Mean'
- 'Sum'
- 'Median'
"""
_projectionMethods = {
"Max": np.max,
"Min": np.min,
"Mean": np.mean,
"Sum": np.sum,
"Median": np.median
}
def __init__(self):
super().__init__()
self._axis = self.defaultProjectionAxis()
self._projectionMethod = self.defaultProjectionMethod()
[docs]
@staticmethod
def defaultProjectionMethod() -> str:
return "Max"
[docs]
@staticmethod
def defaultProjectionAxis() -> str:
return "Z"
[docs]
def getPrefix(self) -> str:
return f"{self._projectionMethod}Proj[{self._axis}]-"
[docs]
def setProjectionAxis(self, axis: str):
self._axis = axis
[docs]
def getProjectionAxis(self) -> str:
return self._axis
[docs]
def setProjectionMethod(self, method: str):
if method not in self._projectionMethods:
raise ValueError(f"Projection method '{method}' is not supported. Supported methods are: {list(self._projectionMethods.keys())}.")
self._projectionMethod = method
[docs]
def getProjectionMethod(self) -> str:
return self._projectionMethod
def _applyToFrame(self, frameData, t, nT):
raise RuntimeError("This operator does not support frame-wise processing. Use the 'run' method instead.")
[docs]
def sanityCheck(self):
"""
Checks that the main image has the projection axis and the projection method is supported.
"""
super().sanityCheck()
img = self.getMainImage()
axes = set(img.dims)
if self._axis not in axes:
raise ValueError(f"Projection axis '{self._axis}' is not present in the image dimensions {axes}.")
if self._projectionMethod not in self._projectionMethods:
raise ValueError(f"Projection method '{self._projectionMethod}' is not supported.")
def _run(self):
self.sanityCheck()
img = self.getMainImage()
proj_func = self._projectionMethods.get(self._projectionMethod, None)
if proj_func is None:
raise ValueError(f"Projection method '{self._projectionMethod}' is not supported.")
projected_data = proj_func(img.values, axis=img.get_axis_num(self._axis))
new_dims = tuple(d for d in img.dims if d != self._axis)
new_scale = {k: v for k, v in img.attrs.get("scale", {}).items() if k != self._axis}
new_units = {k: v for k, v in img.attrs.get("units", {}).items() if k != self._axis}
self._result = xr.DataArray(
projected_data,
dims=new_dims,
attrs={
"scale": new_scale,
"units": new_units
}
)
yield 0