【问题标题】:fast computation of histogram on a grid快速计算网格上的直方图
【发布时间】:2011-08-15 20:18:39
【问题描述】:

我有一张 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

【问题讨论】:

    标签: matlab grid histogram


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我认为下面的代码可能会回答您的问题。诀窍是不要在循环内调用任何函数并预先分配所有数组。参见例如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))
      

      【讨论】:

        猜你喜欢
        • 2022-07-05
        • 1970-01-01
        • 2015-09-27
        • 2014-08-22
        • 2013-08-30
        • 2011-09-17
        • 2011-10-10
        • 1970-01-01
        相关资源
        最近更新 更多