watershed分水岭算法的matlab例子详解
今天本来想试试mser算法的,结果没看懂。就先看看类似的分水岭算法,用c++又有些看不懂,于是就在matlab先试试,matlab上面没有源码,就拿它的例子试了试,大概明白它的用法,就把注释给贴了上来。
clear all; clc; close all; center1 = -10;%第一个圆圆心的横坐标 center2 = -center1;%第二个圆圆心的横坐标 dist = sqrt(2*(2*center1)^2);%计算两个圆心之间的距离 radius = dist/2 * 1.4;%圆的半径为两者距离的一半的1.4倍,即两个圆肯定会相交 lims = [floor(center1-1.2*radius) ceil(center2+1.2*radius)];%floor 向下取整 ceil向上取整 为整个图像的大小 [x,y] = meshgrid(lims(1):lims(2));%生成一个69*69的网格平面 bw1 = sqrt((x-center1).^2 + (y-center1).^2) <= radius;%计算每个坐标的跟(-10,-10)和(10,10)的距离,如果小于半径则置1,否则置0 bw2 = sqrt((x-center2).^2 + (y-center2).^2) <= radius; bw = bw1 | bw2;%两个二值图像按位相或,合并在一起 figure, imshow(bw,InitialMagnification,fit), title(bw)%显示两个相或之后的结果 D = bwdist(~bw);%对bw求反,然后求距离变换之后的结果 figure, imshow(D,[],InitialMagnification,fit)%画出距离变换之后的结果 title(Distance transform of ~bw)%标题 D = -D;%对距离变换之后的结果求负值 D(~bw) = -Inf;%把~bw中1的部分全部置为-Inf % 功能:分水岭变换 % 用法:L = watershed(A) % 输入:A——输入矩阵(任意维数) % 输出:L——分水岭标记矩阵 % 注:L为整数(>=0),标记0不属于分水岭区域,标记1属于第1个分水岭区域,标记2属于第2个分水岭区域,以此类推。 % 默认对二维矩阵使用8连通,三维矩阵使用26连通,高维矩阵使用conndef(ndims(A),maximal)来定义连通性。 % % L = watershed(A, conn) specifies the connectivity to be used in the watershed computation. conn can have any of the following scalar values. % 输入:A——输入矩阵、conn——连通性 % 输出:L——分水岭标记矩阵 L = watershed(D); %-1的位置置为0,其他位置分别为1,2,3 % 功能:转换标记矩阵到RGB图像 % 用法:RGB = label2rgb(L) % 输入:L——标记矩阵(可由labelmatrix, bwlabel, bwlabeln, watershed返回) % 输出:RGB——彩色图像 % 注:根据L的数值对应,默认对应到colormap(jet)的色彩,返回RGB矩阵 % RGB = label2rgb(L, map) % 输入:L——标记矩阵(可由labelmatrix, bwlabel, bwlabeln, watershed返回)、map——颜色映射表 % 输出:RGB——彩色图像 % 注:map为n*3的矩阵,可以通过MATLAB的colormap函数来返回,比如colormap(jet)等。也可以根据要求自己定义。默认为colormap(jet)。 % RGB = label2rgb(L, map, zerocolor) defines the RGB color of the elements labeled 0 (zero) in the input label matrix L. As the value of zerocolor, specify an RGB triple or one of the strings listed in this table. % 输入:L——标记矩阵(可由labelmatrix, bwlabel, bwlabeln, watershed返回)、map——颜色映射表、zerocolor——对应于标记0的颜色 % 输出:RGB——彩色图像 b % 注:zerocolor可以取值如表1.1,默认为[1 1 1],即白色。 % 表1.1 取值列表 % Value % Color % b % 蓝色 % c % 蓝绿色 % g % 绿色 % k % 黑色 % m % 洋红色 % r % 红色 % w % 白色 % y % 黄色 % RGB = label2rgb(L, map, zerocolor, order) % 输入:L——标记矩阵(可由labelmatrix, bwlabel, bwlabeln, watershed返回)、map——颜色映射表、zerocolor——对应于标记0的颜色、order——标记矩阵和颜色映射表对应方式 % 输出:RGB——彩色图像 % 注:order默认为noshuffle,即根据L的数值来对应颜色。另外可以取值为shuffle,说明使用伪随机方式来对应。 rgb = label2rgb(L,jet,[.5 .5 .5]); figure, imshow(rgb,InitialMagnification,fit) title(Watershed transform of D)
