Source code for ddd_pylib.points_manip._remove_background_points_operator
from ddd_pylib._base import PointsOperator
[docs]
class RemoveBackgroundPointsOperator(PointsOperator):
"""
Remove points that are not in the foreground of the image.
The foreground is defined by a mask image, where the foreground pixels have a value of 1 and the background pixels have a value of 0.
The operator will remove all points that are in the background of the mask image.
"""
def __init__(self):
super().__init__()
self._labelsImage = None
self._backgroundLabel = self.defaultBackgroundLabel()
[docs]
@staticmethod
def defaultBackgroundLabel():
return 0
[docs]
def getBackgroundLabel(self):
"""
Return the background label value
"""
return self._backgroundLabel
[docs]
def setBackgroundLabel(self, label):
"""
Set the background label value
Args:
label: The background label value
"""
self._backgroundLabel = label
[docs]
def getLabelsImage(self):
"""
Return the labels image as a DataArray
"""
if self._labelsImage is None:
raise ValueError("Labels image is not set")
return self._labelsImage
[docs]
def setLabelsImage(self, labelsImage):
"""
Take a labels image and store it in the _labelsImage attribute
Args:
labelsImage: A labels image as a DataArray
"""
self._labelsImage = labelsImage
[docs]
def sanityCheck(self):
super().sanityCheck()
df = self.getMainDataFrame()
labels = self.getLabelsImage()
lbl_axes = {str(ax) for ax in labels.dims}
cols = set(df.columns).intersection(self.getValidAxes())
if not lbl_axes.issubset(cols):
raise ValueError(f"Labels and dataframe don't share the same axes.")
[docs]
def getPrefix(self):
return "NoBG-"
def _applyToFrame(self, frameData, t, nT):
raise NotImplementedError("This method should not be used in this class.")
def _removeBackgroundPoints(self, df, labels, backgroundLabel):
axes = [str(ax) for ax in labels.dims]
mask = labels.values != backgroundLabel
coords = [df[ax].values for ax in axes]
indices = tuple(coords)
valid_points = mask[indices]
return df[valid_points].copy()
def _run(self):
self.sanityCheck()
self._result = self._removeBackgroundPoints(
self.getMainDataFrame(),
self.getLabelsImage(),
self.getBackgroundLabel()
)
yield 0
if __name__ == "__main__":
import pandas as pd
import numpy as np
from tifffile import imread
from pathlib import Path
import xarray as xr
import napari
folder = Path("/home/clement/Desktop/dump-ddd")
file_path = folder / "blobs-lbl.tif"
data = imread(file_path)
r1 = np.rot90(data, k=2, axes=(0, 1))
flipped = np.flip(data, axis=0)
data = np.stack([data, r1, flipped, data], axis=0)
im = xr.DataArray(
data,
dims=["T", "Y", "X"],
name="labels"
)
points = (np.random.rand(450, 3) * np.array(data.shape)).astype(int)
df = pd.DataFrame(points, columns=["T", "Y", "X"])
op = RemoveBackgroundPointsOperator()
op.setMainDataFrame(df)
op.setLabelsImage(im)
op.setBackgroundLabel(0)
op.run()
result = op.getResult()
viewer = napari.Viewer()
viewer.add_labels(im.values, name="Labels")
viewer.add_points(
df[['T', 'Y', 'X']].values,
name="Points",
size=3,
face_color="transparent",
border_color="green",
)
viewer.add_points(
result[['T', 'Y', 'X']].values,
name="Filtered Points",
size=3,
face_color="red",
border_color="transparent",
)
napari.run()