Passed
Pull Request — master (#424)
by Fernando
01:14
created

torchio.transforms.preprocessing.label.keep_largest_component   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 36
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A KeepLargestComponent.__init__() 0 6 1
A KeepLargestComponent.apply_transform() 0 10 2
1
import SimpleITK as sitk
2
3
from .label_transform import LabelTransform
4
5
6
class KeepLargestComponent(LabelTransform):
7
    r"""Keep only the largest connected component in a binary label map.
8
9
    Args:
10
        **kwargs: See :class:`~torchio.transforms.Transform` for additional
11
            keyword arguments.
12
13
    .. note:: For now, this transform only works for binary images, i.e., label
14
        maps with a background and a foreground class. If you are interested in
15
        extending this transform `open a new issue`_.
16
17
    .. _open a new issue: https://github.com/fepegar/torchio/issues/new?assignees=&labels=enhancement&template=feature_request.md&title=Improve%20KeepLargestComponent%20transform
18
    """  # noqa: E501
19
    def __init__(
20
            self,
21
            **kwargs
22
            ):
23
        super().__init__(**kwargs)
24
        self.args_names = []
25
26
    def apply_transform(self, subject):
27
        for image in self.get_images(subject):
28
            assert image.data.ndim == 4 and image.data.shape[0] == 1
29
            sitk_image = image.as_sitk()
30
            connected_components = sitk.ConnectedComponent(sitk_image)
31
            labeled_cc = sitk.RelabelComponent(connected_components)
32
            largest_cc = labeled_cc == 1
33
            tensor, _ = self.sitk_to_nib(largest_cc)
34
            image.set_data(tensor)
35
        return subject
36