快速计算网格上的直方图

时间:2011-08-15 20:18:39

标签: matlab grid histogram

我有一个灰度200x200图像,我想计算图像中每个8x8窗口的强度直方图。我怎样才能快速计算出来?我现在使用for循环,但它太慢了。我目前的代码如下:

I = imread('image.jpg');
for i=1:8:height-7
    for j=1:8:width-7
       patch = I(i:i+7,j:j+7);
       % compute histogram for the patch
    end
end

2 个答案:

答案 0 :(得分:5)

如果你有图像处理工具箱,你可以使用函数blockproc,它是循环的编译和通用版本。只需将回调函数定义为直方图计算。

B = blockproc(I, [8 8], @myhistfun)

答案 1 :(得分:0)

我认为以下代码可能会回答您的问题。诀窍是不要在循环内调用任何函数并预先分配所有数组。参见例如http://www.quantiphile.com/2010/10/16/optimizing-matlab-code/了解有关循环加速的更多信息。无论如何,在加速循环下我的机器上快17倍。

% image size
height = 800;
width = 1200;
window = 8;

% histogram bin centers
bin_centers = 0.05:0.1:1;

% here a random image as input
img = rand(height, width);

% verion using accelerated loops (for this to work there cannot be any
% function calls to not built-in functions)
tic
img3 = zeros(window^2, height*width/window^2);
ind = 1;
for i=1:window:height
    for j=1:window:width
       patch_ = img(i:i+window-1,j:j+window-1);
       img3(:,ind) = patch_(:);
       ind = ind + 1;
    end
end
hist_img3 = hist(img3, bin_centers);
toc


% probably version of user499372 calling hist function within the loop
tic
hist_img4 = zeros(size(hist_img3));
ind = 1;
for i=1:window:height
    for j=1:window:width
       patch_ = img(i:i+window-1,j:j+window-1);
       hist_img4(:,ind) = hist(patch_(:), bin_centers);
       ind = ind + 1;
       % compute histogram for the patch
    end
end
toc

% test the results
all(all(hist_img3==hist_img4))