MATLAB: Replacement of groups of neighbor numbers giving priority to a row-wise check

imageimage processingMATLABmatrixmatrix arraymatrix manipulation

Hi community, I need to do a replacement of numbers in a matrix, considering neighbor numbers in 8-directions, for different threshold values that can be selected (threshold value corresponds to the amount of numbers connected, from which the replacement must be done. Above threshold value the group of numbers connected must be replaced). In this matrix, there are groups of numbers 1s embedded in a lot of numbers 2s. However, I need to include a "restriction" about giving priority to a row-wise check. For example, considering this matrix:
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2;
2, 1, 2, 2, 1, 2, 2, 2, 2, 2;
2, 2, 1, 2, 1, 2, 1, 2, 2, 2;
2, 2, 1, 2, 2, 2, 1, 2, 2, 2;
2, 2, 1, 2, 1, 2, 1, 1, 1, 1;
2, 1, 1, 2, 1, 2, 2, 2, 2, 2;
2, 1, 2, 2, 1, 2, 2, 2, 2, 2;
2, 1, 2, 2, 2, 2, 2, 2, 2, 2;
2, 2, 1, 2, 2, 2, 2, 2, 2, 2;
2, 2, 2, 2, 2, 2, 2, 2, 2, 2 ]
I need to stop checking for more neighbor numbers if there are not new rows that contain numbers 1s. In this matrix there are 4 groups of 1s. Considering connections in 8-directions, we have 9, 2, 3 and 6 numbers 1s together. However, for the right-most group of 1s, as only 3 rows are ""invaded"" by numbers 1s, for the replacement I need to do, this group can be considered as a group of 3 numbers 1s connected (hope I´m explaining myself in the right way). In this manner, considering a threshold value of 4, the expected output is:
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2;
2, 2, 2, 2, 1, 2, 2, 2, 2, 2;
2, 2, 2, 2, 1, 2, 1, 2, 2, 2;
2, 2, 2, 2, 2, 2, 1, 2, 2, 2;
2, 2, 2, 2, 1, 2, 1, 1, 1, 1;
2, 2, 2, 2, 1, 2, 2, 2, 2, 2;
2, 2, 2, 2, 1, 2, 2, 2, 2, 2;
2, 2, 2, 2, 2, 2, 2, 2, 2, 2;
2, 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 collaboration!!!

Best Answer

Use the same method as in your previous question except now use the height of the bounding box instead of the area:
m = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2;
2, 1, 2, 2, 1, 2, 2, 2, 2, 2;
2, 2, 1, 2, 1, 2, 1, 2, 2, 2;
2, 2, 1, 2, 2, 2, 1, 2, 2, 2;
2, 2, 1, 2, 1, 2, 1, 1, 1, 1;
2, 1, 1, 2, 1, 2, 2, 2, 2, 2;
2, 1, 2, 2, 1, 2, 2, 2, 2, 2;
2, 1, 2, 2, 2, 2, 2, 2, 2, 2;
2, 2, 1, 2, 2, 2, 2, 2, 2, 2;
2, 2, 2, 2, 2, 2, 2, 2, 2, 2 ]
threshold = 4;
cc = regionprops(logical(2-m), {'BoundingBox', 'PixelIdxList'});
bbox = vertcat(cc.BoundingBox); %bbox(:, 3) is the width, bbox(:, 4) is the height
m(vertcat(cc(bbox(:, 4) >= threshold).PixelIdxList)) = 2