Solved it! The trick is to use the contour map, that is returned. Since I only want the outline of the surface, I first plot the contourf with 0 levels and take the contour map from that plot. Makes things a lot easier.
A = peaks(10);
A(A<=0) = nan;
% generate the outline
[C, ~] = contourf(A, 0, 'linewidth', 1);
% plot the contour
[~, h] = contourf(A, 50, 'linecolor', 'none');
colormap(flipud(gray));
% set background to red to make it transparent later
set(gca, 'color', 'red');
% fill off and on to apply the red background to holes
set(h, 'fill', 'off');
set(h, 'fill', 'on');
% obtain all lines of the outline
CC = C;
clear C;
n = 0;
sFrom = 2;
sTo = 1;
while true
n = n+1;
sTo = sFrom+CC(2, sFrom-1)-1;
C{n} = CC(:, sFrom:sTo);
sFrom = sTo+2;
if sTo == size(CC, 2)
break;
end % if
end % while
% now plot the outlines into the contour
hold on
for n = 1:numel(C)
plot(C{n}(1,:), C{n}(2,:), 'k', 'linewidth', 2);
end % for
hold off
% save the figure
print(gcf, '-r300', '-dpng', 'peaks.png');
% use external tool mogrify to make everything in red transparent
system('mogrify -transparent red peaks.png');
This generates the desired result:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/174095/image.png)