How to find all pairs of neighboring values in matrix?
<p>For an image represented as a matrix, what is an efficient way to find all unique pairs of elements that touch within a 3x3 square?</p>

<pre><code>Let A=
    1 1 2 2 3 3 3
    1 1 1 1 2 4 4
    1 1 2 2 5 5 5
</code></pre>

<p>Then we would return</p>

<pre><code>(1,2),(1,3),(1,5),(2,3),(2,4),(2,5),(3,4),(4,5)
</code></pre>

<p>You may use <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> to achieve this. Below is the sample code:</p>

<pre><code>a = [[1, 1, 2, 2, 3, 3, 3,],
     [1, 1, 1, 1, 2, 4, 4,],
     [1, 1, 2, 2, 5, 5, 5,],
    ]

# Extract boundry values to list
boundary_vals = a[0] + a[-1] + [sub_list[0] for sub_list in a[1:-1]] + [sub_list[-1] for sub_list in a[1:-1]]

# Unique set of values
unique_vals = set(boundary_vals)

# Calculate combinations
from itertools import combinations
my_values = list(combinations(unique_vals, 2))
</code></pre>

<p>Here, <code>my_values</code> is a <code>list</code> of <code>tuple</code>s having value as:</p>

<pre><code>[(1, 2), (1, 3), (1, 4), (1, 5), 
 (2, 3), (2, 4), (2, 5), 
 (3, 4), (3, 5), 
 (4, 5)]
</code></pre>

<p><strong>Explanation</strong>:</p>

<p>For calculating the boundary values:</p>

<pre><code># 1st list
&gt;&gt;&gt; a[0]
[1, 1, 2, 2, 3, 3, 3]

# Last list
&gt;&gt;&gt; a[-1]
[1, 1, 2, 2, 5, 5, 5]

# all the 0th elements of sub-lists excluding 1st and last list
&gt;&gt;&gt; [sub_list[0] for sub_list in a[1:-1]]
[1]

# all the last elements of sub-lists excluding 1st and last list
&gt;&gt;&gt; [sub_list[-1] for sub_list in a[1:-1]]
[4]
</code></pre>

<p>Adding all the above list, will give the boundary elements.</p>

python image-processing matrix