SMOOTHPOLYLINE Smooth a polyline using local averaging. RES = smoothPolygon(POLY, M) POLY contains the polyline vertices, and M is the size of smoothing (given as the length of the convolution window). Extremities of the polyline are smoothed with reduced window (last and first vertices are kept identical, second and penultimate vertices are smoothed with 3 values, etc.). Example img = imread('circles.png'); img = imfill(img, 'holes'); contours = bwboundaries(img'); poly = contours{1}(201:500,:); figure; drawPolyline(poly, 'b'); hold on; poly2 = smoothPolyline(poly, 21); drawPolygon(poly2, 'm'); See also polygons2d, smoothPolygon, simplifyPolyline, resamplePolyline
0001 function res = smoothPolyline(poly, M) 0002 %SMOOTHPOLYLINE Smooth a polyline using local averaging. 0003 % 0004 % RES = smoothPolygon(POLY, M) 0005 % POLY contains the polyline vertices, and M is the size of smoothing 0006 % (given as the length of the convolution window). 0007 % Extremities of the polyline are smoothed with reduced window (last and 0008 % first vertices are kept identical, second and penultimate vertices are 0009 % smoothed with 3 values, etc.). 0010 % 0011 % Example 0012 % img = imread('circles.png'); 0013 % img = imfill(img, 'holes'); 0014 % contours = bwboundaries(img'); 0015 % poly = contours{1}(201:500,:); 0016 % figure; drawPolyline(poly, 'b'); hold on; 0017 % poly2 = smoothPolyline(poly, 21); 0018 % drawPolygon(poly2, 'm'); 0019 % 0020 % See also 0021 % polygons2d, smoothPolygon, simplifyPolyline, resamplePolyline 0022 0023 % ------ 0024 % Author: David Legland 0025 % e-mail: david.legland@grignon.inra.fr 0026 % Created: 2015-02-17, using Matlab 8.4.0.150421 (R2014b) 0027 % Copyright 2015 INRA - Cepia Software Platform. 0028 0029 % compute the number of elements before and after 0030 M1 = floor((M - 1) / 2); 0031 M2 = ceil((M - 1) / 2); 0032 0033 % create convolution vector 0034 v2 = ones(M, 1) / M; 0035 0036 % apply filtering on central part of the polyline 0037 res(:,1) = conv(poly(:,1), v2, 'same'); 0038 res(:,2) = conv(poly(:,2), v2, 'same'); 0039 0040 % need to recompute the extremities 0041 for i = 1:M1 0042 i2 = 2 * i - 1; 0043 res(i, 1) = mean(poly(1:i2, 1)); 0044 res(i, 2) = mean(poly(1:i2, 2)); 0045 end 0046 for i = 1:M2 0047 i2 = 2 * i - 1; 0048 res(end - i + 1, 1) = mean(poly(end-i2+1:end, 1)); 0049 res(end - i + 1, 2) = mean(poly(end-i2+1:end, 2)); 0050 end