一、简介

二、源代码
clear, close all;
clc;
%1.读取图像并求取图像的边界。
rgb = imread('tree.jpeg');%读取原图像
I = rgb2gray(rgb);%转化为灰度图像
figure; subplot(121)%显示灰度图像
imshow(I)
text(732,501,'Image courtesy of Corel','FontSize',7,'HorizontalAlignment','right')
hy = fspecial('sobel');%sobel算子,应用sobel算子锐化图像
hx = hy';
Iy = imfilter(double(I), hy, 'replicate');%滤波求y方向边缘
Ix = imfilter(double(I), hx, 'replicate');%滤波求x方向边缘
gradmag = sqrt(Ix.^2 + Iy.^2);%求摸
subplot(122); imshow(gradmag,[]), %显示梯度
title('Gradient magnitude (gradmag)')
%2. 直接使用梯度模值进行分水岭算法:(往往会存在过的分割的情况,效果不好)
L = watershed(gradmag);%直接应用分水岭算法
Lrgb = label2rgb(L);%转化为彩色图像
figure; imshow(Lrgb), %显示分割后的图像
title('Watershed transform of gradient magnit