-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwatershed_basins.m
67 lines (64 loc) · 2.41 KB
/
watershed_basins.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
%% Terrain to watershed basins
function [colors, outflow] = watershed_basins(Z)
flow_graph = zeros(numel(Z),2);
outflow=[];
for x=1:size(Z,1)
for y=1:size(Z,2)
if(~isnan(Z(x,y)))
%find lowest neighbour
neighbors=[];
if(x>1)
neighbors=[neighbors;x-1 y];
if(y>1)
neighbors=[neighbors;x-1 y-1];
end
end
if(x<size(Z,1))
neighbors=[neighbors;x+1 y];
if(y<size(Z,2))
neighbors=[neighbors;x+1 y+1];
end
end
if(y>1)
neighbors=[neighbors;x y-1];
if(x<size(Z,1))
neighbors=[neighbors;x+1 y-1];
end
end
if(y<size(Z,2))
neighbors=[neighbors;x y+1];
if(x>1)
neighbors=[neighbors;x-1 y+1];
end
end
neighbors=sub2ind(size(Z),neighbors(:,1),neighbors(:,2));
if(sum(max(0,Z(x,y)-Z(neighbors)))==0)
%disp(['there are no lower neighbours to [' num2str(x) ', ' num2str(y) ']']);
flow_graph(sub2ind(size(Z),x,y),:)=[sub2ind(size(Z),x,y) sub2ind(size(Z),x,y)];
outflow = [outflow;sub2ind(size(Z),x,y)];
else
distribution=max(0,Z(x,y)-Z(neighbors))/sum(max(0,Z(x,y)-Z(neighbors)));
[~,ind]=max(distribution);
flow_graph(sub2ind(size(Z),x,y),1)=sub2ind(size(Z),x,y);
flow_graph(sub2ind(size(Z),x,y),2)=neighbors(ind);
end
end
end
end
%go from the root to the leaves, simplifying connections
connected=flow_graph(find(flow_graph(:,1)),:);
disconnected=find(isnan(Z));
%connected(~,1) flows into connected(~,2)
itteration=0;
while ~isempty(setdiff(connected(:,2),outflow))
itteration=itteration+1;
%disp(['itteration ' num2str(itteration)]);
for i=1:length(connected)
% i
connected(i,2)=connected(connected(:,1)==connected(i,2),2);
end
end
colors=Z;
colors(disconnected)=0;
colors(connected(:,1))=connected(:,2);
end