MATLAB数字图像处理(三)——图像轮廓提取与边缘检测
二值图像轮廓提取
根据掏空内部点算法,运用Matlab编程实现二值图像的轮廓提取。(以二值图像circles为例)
I = imread(circles.png); subplot(1,2,1),imshow(I); [M,N]=size(I); Ic=I; for i = 2:M-1 for j=2:N-1 if(I(i,j)==255&I(i+1,j)==255&I(i-1,j)==255&I(i,j+1)==255&I(i,j-1)==255&I(i+1,j+1)==255&I(i+1,j-1)==255&I(i-1,j+1)==255&I(i-1,j-1)==255) Ic(i,j)=0; end end end subplot(1,2,2),imshow(Ic);
掏空内部点,就是判断该点灰度值,与其领域8个点的灰度值是否属于目标物体的灰度值,如果是,说明其是内部点,将其改为背景灰度。这里生成了一个原图像的副本Ic,在副本上进行轮廓提取。
灰度图像边缘检测
以灰度图像rice为例,利用Matlab图像处理工具箱中的edge函数,分别使用Roberts 算子、Sobel算子、Prewitt 算子对其进行边缘检测。
I=imread(rice.png); subplot(2,2,1),imshow(I); BW1=edge(I,roberts); BW2=edge(I,prewitt); BW3=edge(I,sobel); subplot(2,2,2),imshow(BW1),title(roberts算子); subplot(2,2,3),imshow(BW2),title(prewitt算子); subplot(2,2,4),imshow(BW3),title(sobel算子);
(1)函数格式:BW = edge(I, ‘method’, thresh) (2)格式说明:edge函数输入灰度图像矩阵I,输出二值图像矩阵BW;参数’method’用于指定所使用的边缘检测算子,可以是’roberts’、‘sobel’、‘prewitt’、‘log’、‘canny’;参数thresh用于指定梯度门限值(也称梯度阈值),图像中梯度值大于等于门限值thresh的像素用白色(1)表示,说明这些地方对应边缘,梯度值小于门限值thresh的像素用黑色(0)表示(edge function will ignore all edges that are not stronger than thresh)。若不指定参数thresh,则edge函数会自动选择阈值。所以edge函数最终将原始灰度图像中的边缘和背景用二值图像的形式展现出来,以突出边缘的位置,达到边缘检测的目的。
含噪图像边缘检测
若向原始图像rice中加入高斯噪声,之后再对噪声图像分别运用Roberts 算子、Sobel算子、Prewitt 算子、Log算子(高斯-拉普拉斯算子)进行边缘检测,观察检测结果,试比较4种边缘检测算子的抗噪声干扰能力。
I=imread(rice.png); subplot(2,3,1),imshow(I); G=imnoise(I,gaussian); subplot(2,3,2),imshow(G); BW1=edge(G,roberts); BW2=edge(G,prewitt); BW3=edge(G,sobel); BW4=edge(G,log); subplot(2,3,3),imshow(BW1),title(roberts算子); subplot(2,3,4),imshow(BW2),title(prewitt算子); subplot(2,3,5),imshow(BW3),title(sobel算子); subplot(2,3,6),imshow(BW4),title(log算子);
很明显log算子对高斯噪声的抗干扰能力最强,因为log算子相当于先进行均值滤波(高斯模板卷积),再用拉普拉斯算子,所以对高斯噪声抗干扰能力强。
均值滤波函数
根据均值滤波的基本原理自定义均值滤波函数d=avefilt(x,n),x为输入图像矩阵,n为模板大小(即n×n),d为输出图像矩阵。并调用该函数对含有高斯噪声的图像进行均值滤波处理。
% avefilt.m function d=avefilt(x,n) a=ones(n);%生成n*n的全1矩阵 [M,N]=size(x); x1=double(x); x2=x1; for i=1:M-n+1 for j=1:N-n+1 c=x1(i:i+n-1,j:j+n-1).*a; s=sum(sum(c));%求c矩阵所有元素的和 x2(i+fix((n-1)/2),fix(j+(n-1)/2))=s/(n*n);%使中心元素=均值,fix()向下取整 end end d=uint8(x2);%四舍五入取整映射到0~255范围
% ex3_4.m ori=imread(eight.tif); Gao=imnoise(ori,gaussian); subplot(1,3,1),imshow(ori); subplot(1,3,2),imshow(Gao); after=avefilt(Gao,3); subplot(1,3,3),imshow(after);
均值滤波处理后,有一定的去噪效果,但是图像变得模糊了。