# How to create a binary mask of an image

Consider an image (img) as

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];


I get

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.

How can I fix these two issues?

• You could try MorphologicalBinarize instead of Binarize and also play with the second argument. – Alexey Popkov Jan 19 '18 at 18:22
• MorphologicalBinarize[img, {.1, .5}, CornerNeighbors -> False] is a good starting point. – Alexey Popkov Jan 19 '18 at 18:33

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


A smoothed outline (thanks to Rahul):

Binarize@CurvatureFlowFilter[img2, 3]


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


With GrowCutComponents[], one can obtain this :

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 :

One can create the masks with Drawing Tools see here

Here is another solution motivated by Alexey.

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


The result is: