Reducing a matrix size by averaging blocks within the matrix.

17 次查看(过去 30 天)
I have a 1024x1280 matrix. I want to reduce this to a smaller matrix of 512x640 by taking an average of 2x2 blocks and making that a 1x1 block.
e.g. say the first 2x2 block within the large matrix is [1,3; 7,9]
then this would average that 2x2 block to a 1x1 block of [5]
I have no idea how to do this so any help would be greatly appreciated.

采纳的回答

Stephen23
Stephen23 2015-11-4
编辑:Stephen23 2015-11-4
You could use conv2 and select every second element of its output:
>> X = [1,3,5,6,7,8;7,9,5,3,1,0;9,8,7,6,5,4;0,1,2,3,4,5]
X =
1 3 5 6 7 8
7 9 5 3 1 0
9 8 7 6 5 4
0 1 2 3 4 5
>> Y = conv2(X,[1,1;1,1],'valid');
>> Z = Y(1:2:end,1:2:end)/4
Z =
5.0000 4.7500 4.0000
4.5000 4.5000 4.5000
  2 个评论
F S
F S 2019-5-17
Could you do that also for blocks with other shapes than just 2x2, e.g. if I need the mean of 10x10 or 35x4 sized blocks?
Image Analyst
Image Analyst 2019-5-17
Yes, you just need to figure out where to pluck the output values from - and that could be tricky but it IS possible.

请先登录,再进行评论。

更多回答(2 个)

Thorsten
Thorsten 2015-11-4
fun = @(block_struct) mean(block_struct.data(:));
Y = blockproc(X, [2 2], fun)

Image Analyst
Image Analyst 2015-11-4
I just answered this 2 days ago in http://www.mathworks.com/matlabcentral/answers/252349#answer_198175 where I said:
If you have the Image Processing Toolbox (use "ver" to check), then you can use blockproc():
myData = rand(1024,1280); % Sample data
% Define the mean function to be used with blockproc.
myMeanFunction = @(block_struct) mean(block_struct.data);
% Get the means by each 2-by-2 block.
blockMeans = blockproc(myData, [2, 2], myMeanFunction)
You can also use
smallArray = imresize(bigArray, 0.5);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by