www.gusucode.com > 《matlab图像处理与界面编程宝典》秦襄培 编著,每章的MATLAB源代码程序 > 第3章/第3.4.2节中的代码.txt

     
I = imread('bag.png');%读入系统自带的图片bag.png
figure, imshow(I);%创建图形窗口,在窗口中显示读入的图像
E = entropyfilt(I);
Eim = mat2gray(E);
imshow(Eim);%
BW1 = im2bw(Eim, .8);
imshow(BW1);%
figure, imshow(I);%创建新图形窗口
BWao = bwareaopen(BW1,2000);%这里可以看到BWao是BW+area+open的缩写
imshow(BWao); %
nhood = true(9);
closeBWao = imclose(BWao,nhood);%对前面的开启运算得到的图像再进行闭合运算
imshow(closeBWao)%
roughMask = imfill(closeBWao,'holes');%填充孔洞
imshow(roughMask);
figure, imshow(I);
I2 = I;
I2(roughMask) = 0;%图像透过遮罩,遮罩图像黑色部分可以透过去,白色部分透不过
imshow(I2);
E2 = entropyfilt(I2);
E2im = mat2gray(E2);% 将矩阵转换成灰度图像
imshow(E2im);
BW2 = im2bw(E2im,graythresh(E2im));
imshow(BW2)
figure, imshow(I);
mask2 = bwareaopen(BW2,1000);
imshow(mask2);
texture1 = I;%将图像I复制为texture1
texture1(~mask2) = 0;%这里有个运算符号~,逻辑非,作用是将mask2黑白颠倒
texture2 = I;%将图像I复制为texture2
texture2(mask2) = 0;
%在MATLAB中,~A代表“取逻辑非”的意思。但是实际上其意义要比通常的取逻辑非稍微广泛一点。
%假如A = 1,那么 ~A = 0;
%假如A = [0 1] ,那么 ~A = [1 0];
%假如A = [0 0 0],那么 ~A= [1 1 1];
%但是假如A= [3 4 5],那么 ~A = [0,0,0]。可见~A有那么一点“广义的逻辑非”的意思。
imshow(texture1);
figure, imshow(texture2);
boundary = bwperim(mask2);%生成边界线
%BWPERIM函数能够起到探测灰度图象内部物体周边缘的作用,返回一幅相同尺寸的二值图象。
segmentResults = I;
segmentResults(boundary) = 255;%设置边界线颜色为白色
imshow(segmentResults);%
S = stdfilt(I,nhood);
imshow(mat2gray(S));
R = rangefilt(I,ones(5));
% rangefilt 函数句法为J = rangefilt(I, NHOOD),对输入图像I做距离滤波,由NHOOD指定领域
imshow(R);