MATLAB: B-spline fitting to 2D discrete data points (pixels of contour image)

curve fittingCurve Fitting Toolboximage processingMATLAB

I am trying to fit a B-spline to a set of ordered discrete data points which represent pixels of a contour extracted from a image.
The below code works fine for some simple shapes, but not for others (please see image here http://imgur.com/5IOVmEt
for examples). Why does this happen, and what would be a better way to approach this problem?
I am quite new to differential geometry and MATLAB in general, appreciate any insights or inputs. Thanks.
x = data(:, 1); y = data(:, 2); % data contains two columns representing x,y coordinates
plot(x, y, 'bo');
fittedmodel = fit(x, y, 'cubicinterp');
plot(fittedmodel, 'r-');

Best Answer

Looks to me like the problem is you sorted your x coordinates and didn't keep them in the order that they were are you traverse around the contour.
Why are you using splines? Do you want to interpolate at a higher resolution and keep the curve smooth and make sure it still goes through each original point? If so, use splines. If you want to smooth the boundary so there are less sharp jaggy edges and spikes and don't care if it goes exactly through each original point, then you can do other things, like perhaps a Savitzky-Golay filter (the sgolay function in the Signal Processing Toolbox).