实验内容:使用sobel算子对coins图像进行边缘提取
边缘检测代码
img = imread('coins.png');
sobel_x = [-1 0 1;
-2 0 2;
-1 0 1];
sobel_y = [-1 -2 -1;
0 0 0;
1 2 1];
gra_x = templateFilter(img, sobel_x);
gra_y = templateFilter(img, sobel_y);
[h,w] = size(img);
gra = zeros(h-2, w-2);
for y=2:h-1
for x=2:w-1
gra(y-1,x-1) = (gra_x(y,x).^2 + gra_y(y,x).^2).^0.5;
end
end
gra = (gra - min(min(gra)))/(max(max(gra))-min(min(gra)));
threshold = 0.45;
edge = zeros(h-2, w-2);
for y=2:h-3
for x=2:w-3
if( gra(y,x) >= threshold)
edge(y,x)=1;
end
end
end
imshow(edge);
模版滤波函数
function newimg = templageFilter(img, T)
[h,w] = size(img);
[Th,Tw] = size(T);
% augmented image
augh = floor(Th/2);
augw = floor(Tw/2);
timg = zeros(h+augh*2, w+augw*2);
% output image
newimg = zeros(h,w);
% initialize augmented image
for y=1:h
timg(y+augh, (augw+1):(w+augw)) = img(y,:);
end
% calculate output image
% for every pixel of the output image
for y=1:h
for x=1:w
sum = 0;
% for every pixel of the template
for Ty=1:Th
for Tx=1:Tw
sum = sum + T(Ty,Tx) .* timg(y+Ty-1,x+Tx-1);
end
end
% set the pixel value
newimg(y,x)=sum;
end
end
end