Shrink Labeled regions

Hi,

I was looking for a function in python which can shrink the labels. It is kind of like erosion but of each labelled region. Lets say I have two touching labels, 1 and 2 of two circles. Now I want to shrink both labels/erode pixels so that they do not touch each other by d number of pixels.

In skimage I have a expand_labels function, what I want to do is the opposite, maybe someone wrote it in python and I can just use it than write it from scratch?
@jni @VolkerH

Hey Varun @kapoorlab ,

I recently wrote the shrinkLabels function for clij. It’s a bit tricky, because you may have to relabel objects in case some labels disappeared during the shrinking and continous labeling is needed in the next processing step. Also, what if the shrinking cuts a label into two? Potentially, those islands need to be relabeled. All individual operations I use are also available in python using clEsperanto. Thus, if you find the time to translate these 20 lines to python, I’d be happy about a pull-request to pyclesperanto_prototype. Otherwise, I will implement it myself one day. No pressure. :slight_smile:

Cheers,
Robert

1 Like

I am not quite sure I understand you correctly.
Do you want to shrink each label by n pixels ? Or do you want to shrink until touching labels are separated by at least n pixels and leave non-touching labels untouched?
In the latter case you could find gradients in the label image. Basically every pixel where the label value changes. Then dilate this line by n pixels and use it to mask out the labels.

The obvious brute force way is to iterate through the labels and erode the mask of each label separately. Note that expand_labels in skimage uses the distance transform. There may be some clever way to use the distance transform for shrinking too, but it isn’t immediately obvious to me whether that is really the case.

1 Like

Hi Robert @haesleinhuepf,

I was just reading your code a bit. Labels can disappear yes but if I am eroding only the border pixels they can not be split into two right? I need some time to read and understand your code and then I will be happy to do a PR.

@VolkerH
What I wanted is the former, shrink each label by n pixels, I thought of the brute force way too, just was thinking if I can do something along the lines of expand_labels implementation or if someone has some function like that one.

Thanks guys

1 Like

Thinking about creating a line and using it as a mask. That may actually work for what you want as you would also have a gradient towards the background. So all labels would shrink.

2 Likes

Imagine this is your label image and you erode it by radius 1:

0 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 1 1 1 0 
0 1 1 1 1 1 1 1 1 0 
0 1 1 1 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0

The eroded labels will then expose two islands:

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
5 Likes