identify the adjacent pixels in matlab

2019-06-22 12:58发布

问题:

Let's assume A be,

     1 1 1 1 1 1
     1 2 2 3 3 3
     4 4 2 2 3 3
     4 4 2 2 2 3
     4 4 4 4 3 3
     5 5 5 5 5 5

I need to identify all the numbers which are adjacent to a particular intensity value. E.g. the intensities 1, 3, and 4 are adjacent to the intensity value 2. What is the effective way to do it in Matlab?

I can use the following,

   glcm = graycomatrix(A)

But if A have a larger number of intensity values e.g. 10000 graycomatrix will not be an efficient method.

回答1:

You can build a mask with a 2D convolution, select the values according to that mask, and then reduce them to unique values:

% // Data:
A = [ 1 1 1 1 1 1
      1 2 2 3 3 3
      4 4 2 2 3 3
      4 4 2 2 2 3
      4 4 4 4 3 3
      5 5 5 5 5 5 ];
value = 2;
adj = [0 1 0; 1 0 1; 0 1 0]; %// define adjacency. [1 1 1;1 0 1;1 1 1] to include diagonals

%// Let's go
mask = conv2(double(A==value), adj, 'same')>0; %// pixels adjacent to those equal to `value`
result = unique(A(mask));

In the example, this produces

result =
     1
     2
     3
     4

Note that the result includes 2 because some pixels with value 2 have adjacent pixels with that value.