如何将移动窗口应用于MATLAB中的二维矩阵? [英] How to apply moving windows to a 2D matrix in MATLAB?

查看:1183
本文介绍了如何将移动窗口应用于MATLAB中的二维矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Matlab中的图像中进行特征提取。
为了这个目的,我必须在nXn窗口上应用很多函数(例如在每个3X3窗口中查找变量等。

是否有一种简单有效的方法可以在Matlab除了循环遍历矩阵和每次收集窗口元素?

对于某些函数,我已经能够找到一个等价的掩码并使用filter2应用它们,但是对于其他许多函数,我没有似乎有这样的奢侈品(一个很好的例子:3X3窗口的中位数)。
我想要的是类似于arrayfun的东西,但适用于nXn窗口的东西,而不是个人元素。

Thanks,

Sundar

解决方案

如果您有图像处理工具箱,那么你可以使用 blkproc 来使用自定义函数处理图像的 nxm 块。 p $ p> 函数Ip = imageProcessed(II,blockSize)
%FUNCTION imageProcessed计算平均值块大小为nxm
%块
,如果nargin <2,
%default /块大小的示例值
blockSize = [3 4];如果尺寸(II,3)> 1,
%blkproc需要灰度图像
%,则将b转换为灰度等级(如果它是RGB),则
结束


II = rgb2gray(II)
结束


%自定义平均功能。
myAveFun = @(x)ones(size(x))* sum(x(:))/ length(x(:));

%使用blkproc处理图像
Ip = blkproc(II,[blockSize(1),blockSize(2)],myAveFun);
end

注意:

从MATLAB 2009b的图像处理工具箱开始, blkproc 被剥离并替换为 blockproc (参见R2099b section here )。所以最后两行可以更改为:

  myAveFun = @(blkstrct)ones(size(blkstrct.data))*意思是(blkstrct.data(:))
Ip = blockproc(II,blockSize,myAveFun);


I'm doing feature extraction from an image in Matlab. I'm having to apply many functions over nXn windows for this purpose (such as to find the variance over each 3X3 window, etc.
Is there an easy and efficient way to do this in Matlab other than looping over the matrix and collecting the window elements each time?
For some functions, I've been able to find an equivalent mask and applied them using filter2, but for many others I don't seem to have such a luxury (one good example: median of a 3X3 window).
What I want is something like arrayfun, but something that applies to nXn windows, not individual elements.
Thanks,
Sundar

解决方案

If you have the image processing toolbox then you can use blkproc to process nxm blocks of your image using custom defined functions. Here is an example

function Ip = imageProcessed(II,blockSize)
   % FUNCTION imageProcessed calculates average value of blocks of size nxm
   % blocks 
      if nargin<2,
         % default/example value for block size
         blockSize = [3 4];
      end

      if size(II,3)>1,
          % blkproc requires a grayscale image
          % convert II to gray scale if it is RGB.
          II=rgb2gray(II)
      end


      % Custom average function.
      myAveFun = @(x) ones(size(x))*sum(x(:))/length(x(:));

      % use blkproc to process image
      Ip = blkproc(II,[blockSize(1), blockSize(2)],myAveFun);
end

Note:

As of MATLAB 2009b's Image Processing Toolbox, blkproc was depcrecated and replaced with blockproc (see R2099b section here). So the last two lines could be changed to:

 myAveFun = @(blkstrct) ones(size(blkstrct.data))*mean(blkstrct.data(:))
 Ip = blockproc(II,blockSize,myAveFun);

这篇关于如何将移动窗口应用于MATLAB中的二维矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆