![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581356/image.png)
How to isolate object from a background of variable brightness
2 views (last 30 days)
Show older comments
I am trying to isolate worms in these images below which have a variable background:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581006/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581011/image.png)
I binarize the image using
im = imbinarize(255-rgb2gray(image),'adaptive','Sensitivity',.62,'ForegroundPolarity','dark')
and get:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581016/image.png)
I then use
imfill(im,'holes')
to get
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581021/image.png)
Now that I have a black 'halo' around my desired object, I want to isolate it from the background so that I can process it further - measure its area and the length of its skeleton.
But I am not sure how to do this.
The images always have only 1 of these worms - there are no other objects in the image. Just the background with striations and uneven lighting with 1 useful object in them.
Any help would be much appreciated :)
I've also attached the original image below.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581026/image.bmp)
Thanks in advance :)
0 Comments
Accepted Answer
DGM
on 13 Apr 2021
Edited: DGM
on 13 Apr 2021
There are probably more robust methods, but here is my attempt:
image=imread('worm.bmp');
im0 = imbinarize(255-rgb2gray(image),'adaptive','Sensitivity',0.60,'ForegroundPolarity','dark');
se = strel('disk',5);
im = imerode(im0,se); % break up the bg
im = bwareafilt(im,1); % isolate primary object
im = imdilate(im,se); % restore
im = imfill(im,'holes');
Think of it as image opening, but with object isolation done in the middle, so that noise connectivity is at its lowest. It seems to work with both the test images.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/581356/image.png)
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!