Matlab 网格上直方图的快速计算

Matlab 网格上直方图的快速计算,matlab,grid,histogram,Matlab,Grid,Histogram,我有一张灰度200x200的图像,我想计算图像中每个8x8窗口的强度直方图。我怎么能计算得那么快?我现在使用循环,但它太慢了。我当前的代码如下所示: 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 如果您有图像处理工具箱,则可以使用该函数,该函数

我有一张灰度200x200的图像,我想计算图像中每个8x8窗口的强度直方图。我怎么能计算得那么快?我现在使用循环,但它太慢了。我当前的代码如下所示:

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

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

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

我认为下面的代码可以回答您的问题。诀窍是不要调用循环中的任何函数,而是预先分配所有数组。有关环路加速的更多信息,请参见例如。不管怎样,在我的机器上,下面的加速循环速度快了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))