分水岭变换

% Question No: 8
% Consider a binary image composed of small blobs. Segmenting the circular
% blobs using
%   a) Distance Transform
%   b) Watershed Transform

function watersd(x)
f=imread(x);
bw=im2bw(f,graythresh(f));
bwc=~bw;
dst=bwdist(bwc);
ws=watershed(-dst);
w=ws==0;
rf=bw&~w;
figure,imshow(f),title('Original Image');
figure,imshow(bw,[]),title('Negative Image');
figure,imshow(ws,[]),title('Watershed - Distance Transform');
figure,imshow(rf,[]),title('Superimposed - Watershed and original image');

h=fspecial('sobel');
fd=im2double(f);
sq=sqrt(imfilter(fd,h,'replicate').^2+imfilter(fd,h','replicate').^2);
sqoc=imclose(imopen(sq,ones(3,3)),ones(3,3));
wsd=watershed(sqoc);
wg=wsd==0;
rfg=f;
rfg(wg)=255;
figure,imshow(wsd),title('Watershed - Gradient');
figure,imshow(rf),title('Superimposed - Watershed and original image');

im=imextendedmin(f,20);
Lim=watershed(bwdist(im));
figure,imshow(Lim),title('Watershed - Marker Controlled');
em=Lim==0;
rfmin=imimposemin(sq,im|em);
wsdmin=watershed(rfmin);
figure,imshow(rfmin),title('Watershed - Gradient and Marker Controlled');
rfgm=f;
rfgm(wsdmin==0)=255;
figure,imshow(rfgm),title('Superimposed - Watershed (GM) and original image');
end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
分水岭变换(Watershed Transformation)是一种基于图像灰度值和空间信息进行分割的方法,它可以将图像分割成不同的区域,每个区域代表着一个不同的对象。分水岭变换最初是由Vincent和Soille在1991年提出的,它的原理是将图像看作是一个地形图,然后在图像中从不同的高峰处开始向下流水,最终形成一些分割区域。在OpenCV中,可以使用cv2.watershed()函数实现分水岭变换分水岭变换的步骤如下: 1.读取图像并将其转换为灰度图像。 2.对图像进行二值化处理,得到前景和背景的掩模。 3.对掩模进行距离变换,得到每个像素到最近背景像素的距离。 4.对距离变换结果进行阈值处理,得到分水岭线。 5.将分水岭线作为掩模进行分水岭变换,得到图像的分割结果。 下面是一个简单的分水岭变换代码示例: ``` python import cv2 import numpy as np # 读取图像 img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 对图像进行二值化处理 ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # 对掩模进行距离变换 dist_transform = cv2.distanceTransform(thresh, cv2.DIST_L2, 5) # 对距离变换结果进行阈值处理,得到分水岭线 ret, sure_fg = cv2.threshold(dist_transform, 0.7*dist_transform.max(), 255, 0) # 对掩模进行膨胀操作 kernel = np.ones((3,3), np.uint8) sure_fg = cv2.erode(sure_fg, kernel, iterations=1) # 对掩模取反 sure_bg = cv2.dilate(thresh, kernel, iterations=1) sure_bg = cv2.bitwise_not(sure_bg) # 将前景和背景掩模合并 markers = cv2.add(sure_fg, sure_bg) # 分水岭变换 markers = cv2.watershed(img, markers) # 显示分割结果 img[markers == -1] = [0,0,255] cv2.imshow('result', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在上面的代码中,我们首先读取图像并将其转换为灰度图像,然后使用cv2.threshold()函数对图像进行二值化处理,得到前景和背景的掩模。接着使用cv2.distanceTransform()函数对掩模进行距离变换,得到每个像素到最近背景像素的距离。然后使用cv2.threshold()函数对距离变换结果进行阈值处理,得到分水岭线。接着对掩模进行膨胀操作,并对掩模取反得到背景掩模。最后将前景和背景掩模合并,并使用cv2.watershed()函数进行分水岭变换,得到图像的分割结果。最后将分割结果标记为红色并显示出来。 分水岭变换能够有效地进行图像分割,但是它对噪声敏感,需要对图像进行预处理和参数调整才能得到较好的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值