MATLAB: Replace groups of numbers in a matrix checking connections in 8-directions

imageimage processingMATLABmatrixmatrix arraymatrix manipulation

Hi community,
I have a matrix containing numbers 1 and 2, where numbers 2s are 'the background'. In this manner, in my matrix there are mostly small groups of numbers 1s embedded in a lot of numbers 2. However, in some parts of the matrix (mainly in the right-most and left-most parts of it), there are some large groups of 1s that are a 'mistake' and I need to be able to convert these sections of the matrix in numbers 2s. I would like to be able to choose which is the starting amount of numbers 1s in which the modification must be performed. I´m interested in considering numbers 1s connected in all 8 directions.
For example, considering this matrix:
[[2 2 2 2 2 2 1 1 2 1 1 1;2 1 1 2 1 2 1 1 2 1 1 1;2 2 2 2 2 2 1 1 2 1 1 1]]
And, for example, establishing a threshold of 4 numbers 1s, the output expected is:
[2 2 2 2 2 2 2 2 2 2 2 2;2 1 1 2 1 2 2 2 2 2 2 2;2 2 2 2 2 2 2 2 2 2 2 2]
Thank you very much for your help!.

Best Answer

This can indeed be easily achieved with regionprops of the image processing toolbox:
m = [2 2 2 2 2 2;2 1 2 1 2 2;2 2 2 2 1 1;2 2 2 2 1 1;2 2 2 2 2 2;2 1 1 1 2 2];
cc = regionprops(logical(2-m), {'Area', 'PixelIdxList'}); %get 8-connected blocks of 1
m(vertcat(cc([cc.Area] >= 5).PixelIdxList)) = 2