Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions cc_torch/connected_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,26 @@
from cc_torch import _C


def connected_components_labeling(x):
def connected_components_labeling(x, relabel=False):
"""
Connected Components Labeling by Block Union Find(BUF) algorithm.

Args:
x (cuda.ByteTensor): must be uint8, cuda and even num shapes
relabel (bool): whether to return labels in range [0, max_label]

Return:
label (cuda.IntTensor)
"""
if x.ndim == 2:
return _C.cc_2d(x)
ret = _C.cc_2d(x)
elif x.ndim == 3:
return _C.cc_3d(x)
ret = _C.cc_3d(x)
else:
raise ValueError("x must be [H, W] or [D, H, W] shapes")

if relabel:
vs, idxs = torch.unique(ret, return_inverse=True, sorted=True)
ret = torch.arange(len(vs), device=vs.device)[idxs]

return ret
28 changes: 28 additions & 0 deletions tests/test_cc.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,34 @@ def test_2d(self):

output = cc_torch.connected_components_labeling(img_2d)
self.assertTrue((output == expected_output).all())

def test_relabel(self):
img_2d = torch.tensor([
1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0,
1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0,
1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0,
1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0,
1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0], dtype=torch.uint8).reshape(12, 8).cuda()

expected_output = torch.tensor(
[[1, 1, 0, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 1, 1, 1, 0],
[1, 1, 1, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 2],
[0, 0, 0, 1, 0, 0, 2, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 3, 0, 0],
[0, 0, 0, 0, 0, 3, 0, 0],
[0, 4, 0, 3, 3, 3, 3, 3],
[0, 4, 0, 0, 3, 3, 3, 0],
[0, 4, 0, 0, 3, 3, 3, 0]], dtype=torch.int32).cuda()

output = cc_torch.connected_components_labeling(img_2d, relabel=True)
self.assertTrue((output == expected_output).all())

def test_3d(self):
img_2d = torch.tensor([
Expand Down