实验五 图像的分割与边缘提取
一.实验目的及要求
1.利用MATLAB研究图像分割与边缘检测的常用算法原理; 2.掌握MATLAB图像域值分割与边缘检测函数的使用方法;
3.了解边缘检测的算法和用途,比较Sobel、Prewitt、Canny等算子边缘检测的差异。
二、实验内容
(一)研究以下程序,分析程序功能;输入执行各命令行,认真观察命令执行的结果。熟悉程序中所使用函数的调用方法,改变有关参数,观察试验结果。
1.图像阈值分割
clear all, close all;
I = imread(' cameraman.tif'); figure (1),imshow(I) figure(2); imhist(I) T=120/255;
Ibw1 = im2bw(I,T); %选择阈值T=120/255对图像二值化; figure(3);
subplot(1,2,1), imshow(Ibw1);
T=graythresh(I); %采用Otsu方法计算最优阈值T对图像二值化; L = uint8(T*255)
Ibw2 = im2bw(I,T);
subplot(1,2,2), imshow(Ibw2); help im2bw; help graythresh;
(令T取不同值,重做上述试验,观察试验结果) clear all, close all;
I = imread('cameraman.tif'); figure (1),imshow(I)
figure(2); imhist(I) T=240/255;
Ibw1 = im2bw(I,T); figure(3);
subplot(1,2,1), imshow(Ibw1); T=graythresh(I); L = uint8(T*255) Ibw2 = im2bw(I,T);
subplot(1,2,2), imshow(Ibw2); help im2bw; help graythresh;
2.边缘检测 clear all, close all; I = imread('moon.tif'); BW1 = edge(I,'sobel'); BW2 = edge(I,'canny'); BW3 = edge(I,'prewitt'); BW4 = edge(I,'roberts'); BW5 = edge(I,'log');
figure(1), imshow(I), title('Original Image'); figure(2), imshow(BW1), title('sobel'); figure(3), imshow(BW2), title('canny'); figure(4), imshow(BW3), title('prewitt'); figure(5), imshow(BW4), title('roberts'); figure(6), imshow(BW5), title('log');
% 在完成上述试验后,查看函数edge()使用说明。 help edge
% 仔细阅读函数edge()使用说明后,研究IPT提供的边缘检测演示程序。 edgedemo
(二)利用MATLAB熟悉并验证其它图像分割方法 灰度阈值分割:
I=imread('C:\\Users\\lan\\Desktop\\新建文件夹\\三生三世十里桃花.jpg'); I=rgb2gray(I); I2=im2bw(I); figure,imshow(I2); I2=im2bw(I,140/255); figure,imshow(I2)
区域分割法:
I=imread('eight.tif'); imshow(I)
c=[222 272 300 270 221 194]; r=[21 21 75 121 121 75];
BW=roipoly(I,c,r); figure,imshow(BW) H=fspecial('unsharp'); J1=roifilt2(H,I,BW); figure,imshow(J1) J2=roifill(I,c,r); figure,imshow(J2)
分水岭分割法:
f=imread('D:\\notime\\tutu\\ai.jpg'); imshow(f);
g=im2bw(f, graythresh(f)); figure,imshow(g); gc=~g; D=bwdist(gc); L=watershed(-D); w=L==0; g2=g&~w;
figure,imshow(g2)
(三)采用MATLAB编程实现自动全局阈值算法,对图像'rice.tif'进行二值化分割
算法步骤:
1)选取一个的初始估计值T;
2)用T分割图像。这样便会生成两组像素集合:G1由所有灰度值大于 T 的像素组成,而G2由所有灰度值小于或等于 T 的像素组成。
3)对G1和G2中所有像素计算平均灰度值?1和?2。 4)计算新的阈值: T =(?1+?2)/2 5)重复步骤(2)到(4),直到逐次迭代所得到的 T 值之差小于一个事先定义的参数To,即,如果 |Tn – Tn-1| I=imread('hudie.gif'); I=double(I)/255; k1=(max(max(I))+min(min(I)))/2; [rows cols]=size(I); count1=0; count2=0; for i=1:rows for j=1:cols if I(i,j) count1=count1+1; G1(count1).I=I(i,j); else count2=count2+1; G2(count2).I=I(i,j); end end end k2=(mean(mean([G1.I]))+mean(mean([G2.I])))/2; while(abs(k2-k1)>(5/255)) k1=k2; count1=0; count2=0; for i=1:rows for j=1:cols if I(i,j) count1=count1+1; G1(count1).I=I(i,j); else count2=count2+1; G2(count2).I=I(i,j); end end end k2=(mean(mean([G1.I]))+mean(mean([G2.I])))/2; end figure(1);imshow(I); figure(2);II=im2bw(I,k2);imshow(II); 三、实验设备 1.计算机; 2.MATLAB6.5; 四、预习与思考 1.预习实验内容,阅读教材熟悉实验原理; 2.查阅资料,熟悉实验中涉及的有关MATLAB函数; 2.利用课余时间,采用MATLAB底层函数编程实现实验内容(二)中的自动全局阈值算法。 五、实验报告要求 1.简述试验的目的和试验原理; 2.叙述各段程序功能,改变有关函数的参数,分析比较实验结果; 3.打印出所编写的实验程序。 4.写出本实验的心得体会及意见。 四、实验总结