MATLAB: How to smooth rough edges along a binary image

gesturehandimage analysisimage processingImage Processing Toolboximage segmentationSignal Processing Toolbox

Hey, I'm trying to mark out the tips and bases of each finger on the following image
I binarized the image using the following piece of code
a = imread('img235.jpg');
a = rgb2gray(a);
msk = a > 30;
props = regionprops(logical(msk), 'Area');
allAreas = sort([props.Area]);
msk = bwareaopen(msk, 25);
msk = imclearborder(msk);
bw2 = bwareafilt(msk,1);
BW2 = imfill(bw2,'holes');
to obtain this image:
I next formed a boundary around the image using bwboundaries and marked out the peaks and valleys of the fingers, and I'm trying to estimate where the edge of the little finger is located by finding the distance between the tip of the little finger and the valley between the little finger and the valley between the little finger and the ring finger.
My problem is that because the boundary between the little finger tip and the valley is smoother than the boundary on the other side of the little finger, I do not obtain a good estimate for the location of the base of the little finger because the jagged edges on this end of the boundary of the little finger mean there are a greater number of pixels along the boundary and the boundary is overall longer than it should be. My question is how do I smooth out these jags/irregularities along the boundary?
I would ideally like to obtain a smooth boundary across the entire hand, such as along the smooth edge of the little finger shown in the image above.

Best Answer

There are several ways. You could simply blur the image with conv2() and re-threshold
windowSize = 51;
kernel = ones(windowSize) / windowSize ^ 2;
blurryImage = conv2(single(binaryImage), kernel, 'same');
binaryImage = blurryImage > 0.5; % Rethreshold
Or you could use a Savitzky-Golay filter along with bwboundaries() to smooth out the coordinates, then use poly2mask() if you need to turn the coordinates into an image again. See attached demo.