SMOOTHPOLYGON Smooth a polygon using local averaging. RES = smoothPolygon(POLY, M) POLY contains the polygon vertices, and M is the size of smoothing (given as the length of the convolution window). Example img = imread('circles.png'); img = imfill(img, 'holes'); contours = bwboundaries(img'); contour = contours{1}; imshow(img); hold on; drawPolygon(contour, 'b'); contourf = smoothPolygon(contour, 11); drawPolygon(contourf, 'm'); See also polygons2d, smoothPolyline, simplifyPolygon, resamplePolygon
0001 function res = smoothPolygon(poly, M) 0002 %SMOOTHPOLYGON Smooth a polygon using local averaging. 0003 % 0004 % RES = smoothPolygon(POLY, M) 0005 % POLY contains the polygon vertices, and M is the size of smoothing 0006 % (given as the length of the convolution window). 0007 % 0008 % 0009 % Example 0010 % img = imread('circles.png'); 0011 % img = imfill(img, 'holes'); 0012 % contours = bwboundaries(img'); 0013 % contour = contours{1}; 0014 % imshow(img); hold on; drawPolygon(contour, 'b'); 0015 % contourf = smoothPolygon(contour, 11); 0016 % drawPolygon(contourf, 'm'); 0017 % 0018 % See also 0019 % polygons2d, smoothPolyline, simplifyPolygon, resamplePolygon 0020 0021 % ------ 0022 % Author: David Legland 0023 % e-mail: david.legland@grignon.inra.fr 0024 % Created: 2015-02-17, using Matlab 8.4.0.150421 (R2014b) 0025 % Copyright 2015 INRA - Cepia Software Platform. 0026 0027 % compute the number of elements before and after 0028 M1 = floor((M - 1) / 2); 0029 M2 = ceil((M - 1) / 2); 0030 0031 % repeat beginning and end of contour 0032 poly2 = [poly(end-M1+1:end, :) ; poly ; poly(1:M2,:)]; 0033 0034 % create convolution vector 0035 v2 = ones(M, 1) / M; 0036 0037 % apply contour filtering 0038 res(:,1) = conv(poly2(:,1), v2, 'same'); 0039 res(:,2) = conv(poly2(:,2), v2, 'same'); 0040 0041 % keep the interesting part 0042 res = res(M1+1:end-M2, :);