What is wrong with my image filter code?

2 views (last 30 days)
Hello i have a code below,it works with n=3 ,but for kernel n=5 or above it doesnt work
error: ??? Attempted to access window(18); index out of bounds because numel(window)=17.
how can i fix it? Thanks.
% code
clear all
image=imread('cameraman.tif');
n=3
nPercent = 10;
[y x]=size(image);
nMaxHeight=round(y*nPercent/100.0);
nMaxWidth=round(x*nPercent/100.0);
for I=1:nMaxHeight,
for J=1:nMaxWidth,
cx=round(rand(1)*(x-1))+1;
cy=round(rand(1)*(y-1))+1;
aaa=round(rand(1)*255);
if aaa>128
image(cy,cx)=255;
else
image(cy,cx)=1;
end
end
end
for i=1:x
for j=1:y
if(i==1 || j==1 || i==x ||j==y)
image_out(j,i)=image(j,i);
else
for l= 1:n
for k=1:n
window(l+(k-1)*3)=image(j+l-2,i+k-2);
end
end
for l=1:(n*n-1)
for k=2:(n*n)
if (window(l)>window(k))
temp=window(k);
window(k)=window(l);
window(l)=temp;
end
end
end
image_out(j,i)=window(5);
end
end
end
figure
subplot(1,2,1);imshow(image)
subplot(1,2,2);imshow(image_out)

Accepted Answer

Jan
Jan on 26 Mar 2015
Edited: Jan on 26 Mar 2015
If you remove the evil clear all you could use the debugger to step through your code line by line to find out, what's going on.
You create window with n+(n-1)*3 elements, but try to access the values until n*n.
By the way: What about using sort for an efficient sorting?

More Answers (2)

david
david on 26 Mar 2015
how can i use sort?

Image Analyst
Image Analyst on 26 Mar 2015
Don't use "image" as a variable name since it's a built in function.
For the first double for loop, where you threshold the image, simply do:
binaryImage = yourImage > 128;
For the second loop, I'm not exactly sure what you're doing, but you can probably do your second loop without loops using a single call to imfilter(), or conv2(), or medfilt2(), or ordfilt2() .
  8 Comments
david
david on 27 Mar 2015
what about arithmetic filter?did you see anything like that?
Image Analyst
Image Analyst on 27 Mar 2015
I have no idea what their definition of that is. Of course, all filters are arithmetic in that they use numbers.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!