I wrote a Matlab function to compute the per-pixel contrast (i.e., the difference between the center pixel of a window (3×3) and the mean of all the pixels in the window, and the difference over the standard deviation of all the pixels in the window).
The code runs very slow for an 1024×1024 gray scale image. Is there any method to speed up the code? Thanks!
function [ imContrast ] = LocalContrast( im )
% [ imContrast ] = LocalContrast( im )
% Compute the contrast between a center contrast and its neighbors.
%
% Equation: window_size = 3x3
% x_contrast = (x_center - mu) / std(pixels_in_window)
% mu: mean of the pixels' gray values in the window
%
% Input:
% im - original image in gray scale
%
% Output:
% imContrast - feature matrix of contrast, same size of im
[rows, cols] = size(im);
imContrast = double(zeros(size(im)));
% Boundary - keep the gray values of those in im
imContrast(1,:) = im(1,:) / 255;
imContrast(rows,:) = im(rows,:) / 255;
imContrast(:,1) = im(:,1) / 255;
imContrast(:,cols) = im(:,cols) / 255;
% Compute contrast for each pixel
for x = 2:(rows-1)
for y = 2:(cols-1)
winPixels = [ im(x-1,y-1), im(x-1,y), im(x-1,y+1),...
im(x,y-1), im(x,y), im(x,y+1),...
im(x+1,y-1), im(x+1,y), im(x+1,y+1)];
winPixels = double(winPixels);
mu = mean(winPixels);
stdWin = std(winPixels);
imContrast(x,y) = (double(im(x,y)) - mu) / stdWin;
end
end
end
Here’s a way around it that uses the image processing toolbox. Given your image is called
im,the mean difference (MD):
the standard deviation difference (SDD):