MATLAB: How to find the highest 5 adjacent pixels in a matrix

connected pixels

Hi, I am trying to find the 5 highest value pixels in a matrix. The drawback is that the pixels need to be connected. So, if I have:
X=
9.1113 64.762 23.623 77.029 25.644
57.621 67.902 11.94 35.022 61.346
68.336 63.579 60.73 66.201 58.225
54.659 94.517 45.014 41.616 54.074
42.573 20.893 45.873 84.193 86.994
64.444 70.928 66.194 83.292 26.478
I would want something like:
B=
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 45.873 84.193 86.994
0 0 66.194 83.292 0
Any ideas on how to achieve this?
Thank you in advance!

Best Answer

The only way I can think of solving this is to calculate the convolution of your matrix with all possible 5 pixel patterns. You only need to generate the patterns in one quadrant, but with 8-connected components, it's still a lot of patterns:
conv2(yourimage, [1 1 1 1 1], 'valid')
conv2(yourimage, [1 1 1 1 0; 0 0 0 0 1], 'valid')
...
conv2(yourimage, eye(5), 'valid');
...
conv2(yourimage, [1 0; 1 0; 1 0; 1 0; 0 1], 'valid')
conv2(yourimage, [1; 1; 1; 1; 1], 'valid')
The location of the maximum of each convolution is the top-left corner of the corresponding 5 pixel pattern with the maximum sum. The maximum of these maximum is what you're looking for.
Related Question