《MATLAB图像处理实例详解》:CH_7(图像分割技术)
程序员文章站
2022-05-28 14:28:21
...
图像分割技术
①提取线段
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\xianduan.jpg');
I=rgb2gray(I);
h1=[-1 -1 -1;2 2 2;-1 -1 -1];%横线
h2=[-1 -1 2;-1 2 -1;2 -1 -1];%45°斜线
h3=[-1 2 -1;-1 2 -1;-1 2 -1];%竖线
h4=[2 -1 -1;-1 2 -1;-1 -1 2];%135°斜线
J1=imfilter(I,h1);
J2=imfilter(I,h2);
J3=imfilter(I,h3);
J4=imfilter(I,h4);
J=J1+J2+J3+J4;
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
②微分算子
%Roberts算子
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\gray.jpg');
I=im2double(I);
[J,thresh]=edge(I,'roberts',35/255);%边缘检测,采用Roberts算子,图像分割阈值为35/255
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
%prewitt算子
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\gray.jpg');
I=im2double(I);
[J,thresh]=edge(I,'prewitt',[],'both');%边缘检测,水平和垂直边缘都检测
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
%sobel算子
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\gray.jpg');
I=im2double(I);
[J,thresh]=edge(I,'sobel',[],'horizontal');%边缘检测,检测水平边缘
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
%canny算子
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\grayBeauty.jpg');
I=im2double(I);
J=imnoise(I,'gaussian',0,0.01);
[K,thresh]=edge(J,'canny');
figure;
subplot(121);imshow(J);
subplot(122);imshow(K);
%LOG算子
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\grayBeauty.jpg');
I=im2double(I);
J=imnoise(I,'gaussian',0,0.005);
[K,thresh]=edge(J,'log',[],2.3);%thresh为自动计算的分割阈值
figure;
subplot(121);imshow(J);
subplot(122);imshow(K);
③阈值分割技术
%灰度直方图分割
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\gray.jpg');
J=I>120;
[w,h]=size(I);
for i=1:w
for j=1:h
if(I(i,j) > 130)
K(i,j)=1;
else
K(i,j)=0;
end
end
end
figure;
subplot(131);imshow(I);
subplot(132);imshow(J);
subplot(133);imshow(K);
%彩色图像转换为二值图像
close all;clear all;clc;
[X,map]=imread('E:\Matlab_exercise\图片素材\trees.bmp');
I=ind2gray(X,map);
J=im2bw(X,map,0.4);%转化为二值图像
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
%OTSU阈值分割
close all;clear all;clc;
[X,map]=imread('E:\Matlab_exercise\图片素材\trees.bmp');
I=ind2gray(X,map);
I=im2double(I);
T=graythresh(I);%OTSU阈值分割
J=im2bw(I,T);
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
%迭代式阈值分割
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\grayBeauty.jpg');
I=im2double(I);
T0=0.01;
T1=(min(I(:))+max(I(:)))/2;
r1=find(I>T1);
r2=find(I<=T1);
T2=(mean(I(r1))+mean(I(r2)))/2;
while abs(T2-T1)<T0
T1=T2;
r1=find(I>T1);
r2=find(I<=T1);
T2=(mean(I(r1))+mean(I(r2)))/2;%T2为最佳阈值
end
J=im2bw(I,T2);
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);
④区域分割技术
close all;clear all;clc;
I=imread('E:\Matlab_exercise\图片素材\xianduan.jpg');
I=rgb2gray(I);
J=watershed(I,8);%8连通区域
figure;
subplot(121);imshow(I);
subplot(122);imshow(J);