I have a binary image (img) as shown below and I wish to generate a convex hull of the white region.

enter image description here

I tried to use ConvexHullMesh but could not get the desired size with the background to fit into the original image.

cv = ComponentMeasurements[
   FillingTransform[scleraRough1], {"ConvexVertices", "Mask"}];
cvScaled = Rescale@cv[[1, 2, 1]];

How can I generate the desired convex hull (a binary mask surrounded by the background)?

and I get enter image description here


Apparently you can do this straight away with:

Image@MorphologicalComponents[img, Method -> "ConvexHull"]

See this answer https://mathematica.stackexchange.com/a/189196/72682

It's a bit awkward, but you can get them to line up using Inset. I've shown the boundary below, but if you want the face, just remove the RegionBoundary. I also used ImageValuePositions which are pixel centered offset by 0.5, rather than PixelValuePositions.

img = Import["https://i.stack.imgur.com/3ndPk.png"] // Binarize;
(* remove the border *)
img = ImageTake[img, {2, -2}, {2, -2}];
dims = ImageDimensions[img];
cvx = ConvexHullMesh[ImageValuePositions[img, 1]];
Graphics[{Inset[img, {0, 0}, {0, 0}, dims], Red, RegionBoundary[cvx]},
  PlotRangePadding -> None, PlotRange -> Transpose@{{0, 0}, dims}]


To get the image mask you could do:

gr = Graphics[{Inset[img, {0, 0}, {0, 0}, dims], White, cvx}, 
   PlotRangePadding -> None, PlotRange -> Transpose@{{0, 0}, dims}];
Image[gr, ImageSize -> ImageDimensions[img]]

convex hull mask

| improve this answer | |
  • $\begingroup$ Thanks for the straight forward way. When I searched for the ConvexHull in the documentation, I found that it is obsolete now. I didn't know that it can be used in the way you have mentioned in your answer. $\endgroup$ – Majis Aug 17 at 12:36
  • 1
    $\begingroup$ @Majis yes, the simpler one is the best approach too because it fully contains the image, unlike my method with Inset and ImageValuePositions. You can verify with: ImageCompose[ ColorReplace[ Image@MorphologicalComponents[img, Method -> "ConvexHull"], {1 -> Red}], ColorReplace[img, 0 -> RGBColor[0, 0, 0, 0]] ]. There are no partial pixels sticking out the sides. $\endgroup$ – flinty Aug 17 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.