-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_contour.m
51 lines (45 loc) · 1.44 KB
/
get_contour.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function contours = get_contour(img, thr)
% get the contour of a given image
if ~exist('thr', 'var') || isempty(thr)
thr = 0.95;
end
[d1, d2, d3] = size(img);
contours = cell(d3, 1);
for z=1:d3
tmp_img = imfilter(img(:, :, z), fspecial('gaussian', 2,0.2));
% threshold image
v = sort(img(img>0), 'descend');
vsum = cumsum(v);
v_thr = v(find(vsum>vsum(end)*thr, 1));
% cut the image into few components
W = bwlabel(tmp_img>v_thr);
nlabels = max(W(:));
cont = cell(nlabels, 1);
for label=1:nlabels
img_i = tmp_img.*(W==label);
% crop a small region for computing contours
[tmp1, tmp2, ~] = find(img_i);
if isempty(tmp1)
cont{label} = [];
continue;
else
rmin = max(1, min(tmp1)-3);
rmax = min(d1, max(tmp1)+3);
cmin = max(1, min(tmp2)-3);
cmax = min(d2, max(tmp2)+3);
end
img_i = img_i(rmin:rmax, cmin:cmax);
pvpairs = { 'LevelList' , v_thr*0.0001, 'ZData', img_i};
h = matlab.graphics.chart.primitive.Contour(pvpairs{:});
temp = h.ContourMatrix;
if isempty(temp)
cont{labels} = [];
else
temp(:, 1) = temp(:, 2);
temp = medfilt1(temp')';
temp(:, 1) = temp(:, end);
cont{label} = bsxfun(@plus, temp, [cmin-1; rmin-1]);
end
end
contours{z} = cont;
end