12
$\begingroup$

Consider an image (img) as

enter image description here

I want to create a binary mask which will exactly cover the foreground.

If I do the following

b = DeleteSmallComponents@FillingTransform@Binarize[img]; skeleton = SkeletonTransform[b]; pruned = Pruning[skeleton, 1, 1]; mask = InverseDistanceTransform[pruned] 

I get

enter image description here

You can see that the head is not completely white as desired and this may be due to the fact that the bottom of the head is connected to the boundary of image. Secondly, near the neck (as indicated by the green line), some pixels are black which should be white.

enter image description here

How can I fix these two issues?

$\endgroup$
2
  • $\begingroup$ You could try MorphologicalBinarize instead of Binarize and also play with the second argument. $\endgroup$ Commented Jan 19, 2018 at 18:22
  • $\begingroup$ MorphologicalBinarize[img, {.1, .5}, CornerNeighbors -> False] is a good starting point. $\endgroup$ Commented Jan 19, 2018 at 18:33

4 Answers 4

12
$\begingroup$
img2 = FillingTransform@ GeodesicClosing[MorphologicalBinarize[img, {.1, .5}, CornerNeighbors -> False], 10] 

image

A smoothed outline (thanks to Rahul):

Binarize@CurvatureFlowFilter[img2, 3] 

image

$\endgroup$
4
$\begingroup$

This approach uses ImageData to work on the lines, rather than the whole image. After a few manipulations, it detects the first and last white pixel on each line and turn the whole segment to 1 (i.e. white).

img = Import["https://i.sstatic.net/Mw1iJ.png"] edges = EdgeDetect[img, 2] data = ImageData@edges; Table[line = data[[j]]; pos = Flatten@Position[line, 1]; If[Length[pos] > 1, data[[j, pos[[1]] ;; pos[[-1]]]] = 1]; , {j, Length@data}]; Image@data 

enter image description here

$\endgroup$
4
$\begingroup$

With GrowCutComponents[], one can obtain this :

enter image description here

A little bit lifting with Dilation/Erosion will probably improve the result.

How to use GrowCutComponents[] ?

you have to create the 2 masks and evaluate the following :

enter image description here

One can create the masks with Drawing Tools see here

$\endgroup$
1
$\begingroup$

Here is another solution motivated by Alexey.

Opening[DeleteSmallComponents[ ColorNegate[ RegionBinarize[img, {{1, 1}}, 0.1, Method -> "MeanEuclidean"]], CornerNeighbors -> False], 1] 

The result is:

enter image description here

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.