-2

I have a problem in matrix (A) 9*9, I need to extract median for each block 3*3. Also, I need to know the position of the median in each block.

Note: I know how can extract the median by using m=median(median(B)); and B is block in matrix B = A(i:i+L-1, j:j+L-1);

thank you.

bedo
  • 3
  • 2

2 Answers2

1

If you have the image processing toolbox installed you can use:

medianBlocks = blockproc(A,[3,3],@(X) ones(size(X.data))*median(X.data(:)))
A == medianBlocks
knedlsepp
  • 6,065
  • 3
  • 20
  • 41
0

If you don't have the Image Processing Toolbox, I suggest transforming each neighbourhood so that it fits into a single column then you stack all of these columns together to create a single matrix. Once you have this new matrix, find the median of each column, then use this result for further processing.

The best way to do this would be to use im2col to create this temporary matrix and do the median on this matrix over the columns. The output will give you the median of each neighbourhood in your image.

Ironically, im2col is part of the Image Processing Toolbox. However, Divakar has made a vectorized and more efficient version of it that doesn't require the toolbox and only relies on native MATLAB commands.

See here: Efficient Implementation of `im2col` and `col2im`

As such, depending on whether you want overlapping blocks or sliding blocks, use whichever command suits you. Therefore:

out = im2col_distinct(A, [3 3]); %//OR
%out = im2col_sliding(A, [3 3]);

out_median = median(out);

out_median will contain a vector that has the median of each block in the image. Now, if you want to find which location in each window has the median, you can make a bsxfun call:

loc = bsxfun(@eq, out, out_median);

loc will contain the column-major locations of each block. If you want the row and column locations with respect to each block, you can use ind2sub:

[rows,cols] = ind2sub([3 3], loc);

rows and cols will give you the row and column locations of where the median was located in each block neighbourhood of your image.

Community
  • 1
  • 1
rayryeng
  • 102,964
  • 22
  • 184
  • 193