# 标记控制的分水岭分割

1. 计算分割函数。这得到是一个图像，其中暗区域是您尝试分割的对象。

2. 计算前景标记。这些是每个对象中连通的像素斑点。

3. 计算背景标记。这些像素不是任何对象的一部分。

4. 修正分割函数，使其仅在前景和背景标记位置具有最小值。

5. 计算修正分割函数的分水岭变换。

### 步骤 1：读入彩色图像并将其转换为灰度

```rgb = imread('pears.png'); I = rgb2gray(rgb); imshow(I) text(732,501,'Image courtesy of Corel(R)',... 'FontSize',7,'HorizontalAlignment','right')```

### 步骤 2：使用梯度幅值作为分割函数

```gmag = imgradient(I); imshow(gmag,[]) title('Gradient Magnitude')```

```L = watershed(gmag); Lrgb = label2rgb(L); imshow(Lrgb) title('Watershed Transform of Gradient Magnitude')```

### 步骤 3：标记前景对象

```se = strel('disk',20); Io = imopen(I,se); imshow(Io) title('Opening')```

```Ie = imerode(I,se); Iobr = imreconstruct(Ie,I); imshow(Iobr) title('Opening-by-Reconstruction')```

```Ioc = imclose(Io,se); imshow(Ioc) title('Opening-Closing')```

```Iobrd = imdilate(Iobr,se); Iobrcbr = imreconstruct(imcomplement(Iobrd),imcomplement(Iobr)); Iobrcbr = imcomplement(Iobrcbr); imshow(Iobrcbr) title('Opening-Closing by Reconstruction')```

```fgm = imregionalmax(Iobrcbr); imshow(fgm) title('Regional Maxima of Opening-Closing by Reconstruction')```

```I2 = labeloverlay(I,fgm); imshow(I2) title('Regional Maxima Superimposed on Original Image')```

```se2 = strel(ones(5,5)); fgm2 = imclose(fgm,se2); fgm3 = imerode(fgm2,se2);```

```fgm4 = bwareaopen(fgm3,20); I3 = labeloverlay(I,fgm4); imshow(I3) title('Modified Regional Maxima Superimposed on Original Image')```

### 步骤 4：计算背景标记

```bw = imbinarize(Iobrcbr); imshow(bw) title('Thresholded Opening-Closing by Reconstruction')```

```D = bwdist(bw); DL = watershed(D); bgm = DL == 0; imshow(bgm) title('Watershed Ridge Lines')```

### 步骤 5：计算分割函数的分水岭变换。

`gmag2 = imimposemin(gmag, bgm | fgm4);`

`L = watershed(gmag2);`

### 步骤 6：可视化结果

```labels = imdilate(L==0,ones(3,3)) + 2*bgm + 3*fgm4; I4 = labeloverlay(I,labels); imshow(I4) title('Markers and Object Boundaries Superimposed on Original Image')```

```Lrgb = label2rgb(L,'jet','w','shuffle'); imshow(Lrgb) title('Colored Watershed Label Matrix')```

```figure imshow(I) hold on himage = imshow(Lrgb); himage.AlphaData = 0.3; title('Colored Labels Superimposed Transparently on Original Image')```