matlabparticle-filter

Denoising using particle filter in matlab


I am trying to denoise an image using particle filter. Its not a full implementation of particle filter, I am just using the some part of it. I am new to matlab and I am getting the following error

"Index exceeds matrix dimensions.

Error in particle_filter_denoising (line 42)
         Xkposeterior=[EImg(i,j-1);EImg(i-1,j);EImg(i-1,j-1)];"

I tried debugging, but I am not able to find why the code is going wrong.

    Img = imread('a.jpg');
Img= rgb2gray(Img);
Img=im2double(Img);
V =0.001;
clc;

x_N=V ;
x_R=V *2;
NImg=imnoise(Img,'gaussian',Var);

subplot(1,3,1);imshow(Img);title('Original Image');
subplot(1,3,2);imshow(NImg);title('Noisy Gaussian Image');

[r  c] =size(Img);
EImg=zeros(r,c);
EImg(1,:) =Img(1,:);
EImg(:,1)=Img(:,1);
A=[0.35 0.35 0.3;0 1 0;0 0 1];

%Initial state
Xkposeterior=[EImg(2,  1);EImg(1,2);EImg(1,1)];
X_prior = A*Xkposeterior;

%particles
N=100;
X_Particle=[];

X_P_wi=[];

for i = 1:N
    X_Particle(i) = X_prior(1) + sqrt(V) * randn;
end




%%Xkposeterior=[EImg(2,1);EImg(1,2);EImg(1,1)];
for i=2:r
    for j=2:c
         Zk=NImg(i,j);

         Xkposeterior=[EImg(i,j-1);EImg(i-1,j);EImg(i-1,j-1)];
         X_prior = A*Xkposeterior;
         for k_particle=1:N
             X_Particle(k_particle)=X_prior(1) + sqrt(V) * randn;
             X_P_wi(k_particle)=(1/sqrt(2*pi*x_R)) * exp(-(Zk - X_Particle(k_particle))^2/(2*x_R));
         end
         X_P_wi = X_P_wi./sum(X_P_wi);
         for m = 1 : N
            X_Particle(m) = X_Particle(find(rand <= cumsum( X_P_wi),1));
         end    

         EImg= mean(X_Particle);



    end
end




subplot(1,3,3);imshow(EImg, []);title(' Particle Denoised Image');

Solution

  • The error means that i or j is larger than the number of rows or columns in EImg.

    The reason why that is happening is that you are overwriting EImg on each iteration of the loop, at the line: EImg=mean(X_Particle). This makes EImg a different sized array, and so it wont have r rows and c columns anymore. I can't tell you how to fix the problem, because I don't know what the code does, but that is why you are seeing the error.