如何加快代码计算图像上的“每像素”对比度(局部对比度)?

时间:2012-12-20 04:20:22

标签: matlab image-processing

我编写了一个Matlab函数来计算每像素对比度(即窗口中心像素(3x3)与窗口中所有像素的平均值之间的差异,以及所有像素的差异)窗口中的像素。)

对于1024x1024灰度图像,代码运行速度非常慢。有没有什么方法可以加速代码?谢谢!

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

1 个答案:

答案 0 :(得分:4)

这是一种使用图像处理工具箱的方法。鉴于您的图片称为im

平均差异(MD):

 MD = im - imfilter(im,fspecial('average',[3 3]),'same');

标准差差异(SDD):

 SDD = im - stdfilt(im, ones(3));