12

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?

user36426
  • 3,335
  • 11
  • 29

4 Answers4

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

image

A smoothed outline (thanks to Rahul):

Binarize@CurvatureFlowFilter[img2, 3]

image

Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368
4

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.stack.imgur.com/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

anderstood
  • 14,301
  • 2
  • 29
  • 80
4

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

andre314
  • 18,474
  • 1
  • 36
  • 69
1

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

user36426
  • 3,335
  • 11
  • 29