基于形态学的图像分割实验分水岭算法matlab代码
时间: 2024-06-08 09:06:19 浏览: 119
以下是基于形态学的图像分割实验分水岭算法matlab代码:
```matlab
% 读入图像
img = imread('lena.jpg');
figure,imshow(img);
title('Original Image');
% 转换为灰度图像
gray = rgb2gray(img);
figure,imshow(gray);
title('Gray Image');
% 对灰度图像进行中值滤波
gray = medfilt2(gray,[3,3]);
figure,imshow(gray);
title('Median Filtered Image');
% 对灰度图像进行亮度调整
gray = imadjust(gray);
figure,imshow(gray);
title('Adjusted Image');
% 对灰度图像进行水平方向的Sobel算子边缘检测
sobel = fspecial('sobel');
sobel_x = imfilter(double(gray),sobel,'replicate');
figure,imshow(sobel_x);
title('Sobel Edge Detection');
% 对Sobel边缘图像进行阈值处理
sobel_x(sobel_x<30) = 0;
sobel_x(sobel_x>=30) = 1;
figure,imshow(sobel_x);
title('Thresholded Sobel Image');
% 对二值化的Sobel图像进行膨胀
se = strel('disk',2);
dilated = imdilate(sobel_x,se);
figure,imshow(dilated);
title('Dilated Sobel Image');
% 对二值化的Sobel图像进行腐蚀
eroded = imerode(sobel_x,se);
figure,imshow(eroded);
title('Eroded Sobel Image');
% 计算梯度幅值
grad_mag = imgradient(gray);
figure,imshow(grad_mag);
title('Gradient Magnitude');
% 计算梯度方向
grad_dir = imgradient(gray,'direction');
figure,imshow(grad_dir);
title('Gradient Direction');
% 阈值化梯度幅值
grad_mag(grad_mag<50) = 0;
grad_mag(grad_mag>=50) = 1;
figure,imshow(grad_mag);
title('Thresholded Gradient Magnitude');
% 对梯度幅值图像进行膨胀
dilated_grad_mag = imdilate(grad_mag,se);
figure,imshow(dilated_grad_mag);
title('Dilated Gradient Magnitude');
% 计算梯度幅值和Sobel图像的交集
intersect = dilated_grad_mag & dilated;
figure,imshow(intersect);
title('Intersection of Dilated Gradient Magnitude and Dilated Sobel');
% 对交集进行腐蚀
eroded_intersect = imerode(intersect,se);
figure,imshow(eroded_intersect);
title('Eroded Intersection');
% 计算距离变换
dist_transform = bwdist(~eroded_intersect);
figure,imshow(dist_transform);
title('Distance Transform');
% 计算分水岭
watershed = watershed(dist_transform);
figure,imshow(watershed);
title('Watershed Transform');
% 将分水岭的标记可视化
rgb = label2rgb(watershed,'jet',[.5 .5 .5]);
figure,imshow(rgb);
title('Watershed Transform Labels');
```
注意:以上代码仅供参考,具体实现可能因数据集和算法调参而有所不同。
阅读全文