MATLAB: Image contrast estimation. How to speed up this code

contrastdigital image processingImage Processing Toolboxsliding windowspeed up

I have to create a contrast map about images. The method is easy: estimate the contrast (C=SD/Mean) in a 5×5 (sliding) window. Move the window pixel by pixel trough the entire picture and save the results in a new matrix.
I created this script to solve the problem, but it is too slow. The base picture is a 1024×1024 16-bit .tif image. The process is ~40-50 sec long, but other programs solve it in less than 3 secs. How can I speed up my script?
My original script:
M=imread('image.tif');
for S=1:2 SM1_b=size(M,1); SM2_b=size(M,2);
M(:,SM2_b+1)=M(:,SM2_b);
M(SM1_b+1,:)=[M(SM1_b,1:SM2_b) M(SM1_b,SM2_b)];
end
M=[M(1,1:SM2_b+1);M(1,1:SM2_b+1);M]; M=[M(1:(size(M,1)),1) M(1:(size(M,1)),1) M]; clear S SM1_b SM2_b
KPic=zeros(1024);
for i=1:1024 for j=1:1024
KPic(i,j)=std2(M(i:i+4,j:j+4))/mean2(M(i:i+4,j:j+4));
end
end

Best Answer

meanImage = conv2(double(grayImage), ones(9)/81, 'same');
stdImage = stdfilt(grayImage, true(9));
C = meanImage ./ stdImage;