一、简介
图像处理领域中,图像分割是图像后续处理的一个至关重要的技术。图像分割能够将图像中感兴趣的区域分割出来,是图像分析、提取图像特征以及图像理解的基础步骤,得到了图像处理领域中研究者们对其越来越多的关注,并提出了很多的图像分割方法。其中在图像分割方法中应用数学形态学是近几年图像分割的热点之一,较为典型的是基于形态学的分水岭分割算法。
分水岭分割是一种强有力的图像分割方法,可以有效地提取图像中我们所关注的区域。分水岭算法因自身具有的优点被广泛应用于各个领域,其优点是对图像中目标轮廓提取较好并且操作简单。在MATLAB灰度图像中使用分水岭方法可以将图像分割成不同的区域,每个区域就可能对应一个我们所关注的对象。对于这些图像的子区域可以进行进一步的处理。
二、部分源码
function Watershed_Fun(fileName)
%灰度化处理
rgb = imread(fileName);
if ndims(rgb) == 3
I = rgb2gray(rgb);
else
I = rgb;
end
sz = size(I);
if sz(1) ~= 256
I = imresize(I, 256/sz(1));
rgb = imresize(rgb, 256/sz(1));
end
hy = fspecial('sobel');
hx = hy';
Iy = imfilter(double(I), hy, 'replicate');
Ix = imfilter(double(I), hx, 'replicate');
gradmag = sqrt(Ix.^2 + Iy.^2);
se = strel('disk', 3);
Io = imopen(I, se);
Ie = imerode(I, se);
Iobr = imreconstruct(Ie, I);
Ioc = imclose(Io, se);
Iobrd = imdilate(Iobr, se);
Iobrcbr = imreconstruct(imcomplement(Iobrd), imcomplement(Iobr));
Iobrcbr = imcomplement(Iobrcbr);
fgm = imregionalmax(Iobrcbr);
se2 = strel(ones(3,3));
fgm2 = imclose(fgm, se2);
fgm3 = imerode(fgm2, se2);
fgm4 = bwareaopen(fgm3, 15);
bw = im2bw(Iobrcbr, graythresh(Iobrcbr));
D = bwdist(bw);
DL = watershed(D);
bgm = DL == 0;
gradmag2 = imimposemin(gradmag, bgm | fgm4);
L = watershed(gradmag2);
Lrgb = label2rgb(L, 'jet', 'w', 'shuffle');
[pathstr, name, ext] = fileparts(fileName);
filefolder = fullfile(pwd, '实验结果', [name, '_实验截图']);
if ~exist(filefolder, 'dir')
mkdir(filefolder);
end
h1 = figure(1);
set(h1, 'Name', '图像灰度化', 'NumberTitle', 'off');
subplot(1, 2, 1); imshow(rgb, []); title('原图像');
subplot(1, 2, 2); imshow(I, []); title('灰度图像');
fileurl = fullfile(filefolder, '1');
set(h1,'PaperPositionMode','auto');
print(h1,'-dtiff','-r200',fileurl);
h2 = figure(2);
set(h2, 'Name', '图像形态学操作', 'NumberTitle', 'off');
subplot(1, 2, 1); imshow(Iobrcbr, []); title('图像形态学操作');
subplot(1, 2, 2); imshow(bw, []); title('图像二值化');
三、运行结果
四、matlab版本
MATLAB R2019a
五、学习与交流
文中不足之处请大家多多指教,学习与交流可以联系企鹅:3752243968
文中部分源码仅供参考,若需要全部代码可以私信(有偿)