myImageED.m
function img2 = myImageED(type, binaryImage, Struct, pos)
%支持正方形和长方形,奇数、偶数结构元、自定义中心点的膨胀和腐蚀
%输入:type为类型,binaryImage为输入图片,Struct为结构元, pos为中心点
%支持正方形和长方形,支持奇数偶数结构元,支持自定义中心点
%作者:钟海潇原创
%学校:仲恺
B = Struct;
x = pos(1);
y = pos(2);
[M,N] = size(binaryImage);
[K,L] = size(Struct);
down = abs(K-x); %上下左右各加多少
up = abs(1-x);
right = abs(L-y);
left = abs(1-y);
A = zeros(M+K-1, N+L-1); %竖方向扩大K-1,横方向扩大L-1
A(1+up:M+K-down-1,1+left:N+L-right-1) = binaryImage; %补图
img1 = A; %存图
switch type
case 'swell'
for i = 1+up:M+K-down-1
for j = 1+left:N+L-right-1
tmp = A(i-up:i+down,j-left:j+right); %截取图片
C = tmp.*B; %点乘
s = sum(sum(C)); %求和
if(s > 1) %扩大白色
img1(i,j) = 1;
else
img1(i,j) = 0;
end
end
end
case 'corrosion'
for i = 1+up:M+K-down-1
for j = 1+left:N+L-right-1
tmp = A(i-up:i+down,j-left:j+right); %截取图片
C = tmp.*B; %点乘
s = sum(sum(C)); %求和
sB = sum(sum(B)); %模板求和
if(s < sB) %减少白色
img1(i,j) = 0;
else
img1(i,j) = 1;
end
end
end
end
img2 = img1(1+up:M+K-down-1,1+left:N+L-right-1); %缩小
end
T2.m
clc;
clear all;
img1 = imread('EXP6-2.tif');
img2 = imread('EXP6-1.bmp');
Struct_1 = [0 0 1 0 0; 0 0 1 0 0; 1 1 1 1 1; 0 0 1 0 0; 0 0 1 0 0];
pos_1 = [3 3];
Struct_2 = [0 0 1 0; 0 0 1 0; 1 1 1 1; 0 0 1 0];
pos_2 = [2 3];
img1_1 = myOtsu(img1, 'black');
figure(1);
subplot(335);imshow(img1_1.*256);title('原图');
img1_2 = myImageED('swell', img1_1, Struct_1, pos_1);
img1_3 = myImageED('corrosion', img1_1, Struct_1, pos_1);
subplot(331);imshow(img1_2);title('5x5(3,3)膨胀');
subplot(333);imshow(img1_3);title('5x5(3,3)腐蚀');
img1_4 = myImageED('swell', img1_1, Struct_2, pos_2);
img1_5 = myImageED('corrosion', img1_1, Struct_2, pos_2);
subplot(334);imshow(img1_4);title('4x4(2,3)膨胀');
subplot(336);imshow(img1_5);title('4x4(2,3)腐蚀');
img1_6 = myImageED('swell', img1_3, Struct_1, pos_1);
img1_7 = myImageED('sorrosion', img1_2, Struct_1, pos_1);
subplot(337);imshow(img1_6.*255);title('5x5(3,3)开操作');
subplot(339);imshow(img1_7.*255);title('5x5(3,3)闭操作');
img2_1 = myOtsu(img2, 'while');
figure(2);
subplot(335);imshow(img2_1.*256);title('原图');
img2_2 = myImageED('swell', img2_1, Struct_1, pos_1);
img2_3 = myImageED('corrosion', img2_1, Struct_1, pos_1);
subplot(331);imshow(img2_2);title('5x5(3,3)膨胀');
subplot(333);imshow(img2_3);title('5x5(3,3)腐蚀');
img2_4 = myImageED('swell', img2_1, Struct_2, pos_2);
img2_5 = myImageED('corrosion', img2_1, Struct_2, pos_2);
subplot(334);imshow(img2_4);title('4x4(2,3)膨胀');
subplot(336);imshow(img2_5);title('4x4(2,3)腐蚀');
img2_6 = myImageED('swell', img2_3, Struct_1, pos_1);
img2_7 = myImageED('sorrosion', img2_2, Struct_1, pos_1);
subplot(337);imshow(img2_6.*255);title('5x5(3,3)开操作');
subplot(339);imshow(img2_7.*255);title('5x5(3,3)闭操作');