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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With