开发者

fast computation of histogram on a grid

I have a greyscale 200x200 image and I would like to compute the histogram of the intensity for each 8x8 window in the image. How can I compute that fast? I use for loops n开发者_如何学JAVAow but it is so slow. My current code looks like:

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


If you have the Image Processing Toolbox you can use the function blockproc which is a compiled and general version of your loop. Just define the callback function to be your histogram calculation.

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


I think below code may answer your question. The trick is not to call any functions inside a loop and have all arrays preallocated. See e.g. http://www.quantiphile.com/2010/10/16/optimizing-matlab-code/ for more on loop acceleration. Anyways, on my machine below accelerated loop is 17 times faster.

% 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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜