Why are my images not displaying correctly?

2 次查看(过去 30 天)
So I'm basically re-writing the imfilter Matlab function. I'm pretty sure the actual filtering part is correct but for some reason my images, when I do imshow, do not display correctly. Does anyone know why? My code is below, along with the image I get when I run it:
function img = spatial_filter(f,w)
%spatial_filter performs spatial correlation
%get size of f, grayscale image
[x,y]=size(f);
%create padded f (called g)
%first, fill with zeros
g=zeros(x+2,y+2);
%then, store f within g
for i=1:x
for j=1:y
g(i+1,j+1)=f(i,j);
end
end
%cycle through the array and apply the filter
for i=1:x
for j=1:y
img(i,j)=g(i,j)*w(1,1)+g(i+1,j)*w(2,1)+g(i+2,j)*w(3,1) ... %first column
+ g(i,j+1)*w(1,2)+g(i+1,j+1)*w(2,2)+g(i+2,j+1)*w(3,2)... %second column
+ g(i,j+2)*w(1,3)+g(i+1,j+2)*w(2,3)+g(i+2,j+2)*w(3,3);
end
end
img=double(img);
imshow(img, []);
end
output image:
  1 个评论
Andrew Padilla
Andrew Padilla 2018-11-12
Could you clarify variables f and w please? I should be able to help if you provide that information.

请先登录,再进行评论。

回答(1 个)

Guillaume
Guillaume 2018-11-12
First, you need to learn to vectorise code, the lines:
for i=1:x
for j=1:y
g(i+1,j+1)=f(i,j);
end
end
can be replaced by:
g(2:end-1, 2:end-1) = f;
And, if you have the image processing toolbox, you could replace the declaration of g and the loop with
g = padarray(f, [1 1]);
Secondly, you haven't predeclared img, so you're growing it in your loop. Not a good idea.
img = zeros(size(g));
I see nothing wrong with your code and when I test it, it does produce the image I expect. However, your
img = double(img);
call is suspicious. If your inputs were double already, that call doesn't do anything. If the inputs weren't then it's very likely that the convolution would have overflowed the original type of the image. In order to identify the problem with your test, give us the inputs that you use to test your code.
Of course, as I've stated several times you're implemented a convolution, so your whole code could be replaced by just one line:
img = conv2(f, w, 'full');

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by