title: Python: Obtain 'perimeter' and 'area' of similar values in a 2D NumPy array
body: <p>I couldn't find a similar question on here that gave a solution I was looking for, so I'm posting here. To expand on the title, I would like some method to calculate the 'perimeter' and 'area' of patches (with unit length and area) with similar values in a two-dimensional NumPy array.</p>
  <p>The output would contain this information on each 'patch' in the array (the array will usually just have two or three values). Perhaps a dictionary with the value of the patch as the key, and a tuple with area and perimeter as the value, something like</p>
  <pre><code>patch_info_dict = {&quot;patch1_value&quot;: (area1, perimeter1),
                     &quot;patch2_value&quot;: (area2, perimeter2),
                      ...}
  </code></pre>
  <p>For example, given these two 6x6 arrays:</p>
  <pre><code>import numpy as np
  
  arr1 = np.array([[1,1,1,1,1,1],
                   [1,1,1,1,1,1],
                   [1,1,1,1,1,1],
                   [0,0,0,0,0,0],
                   [0,0,0,0,0,0],
                   [0,0,0,0,0,0]])
  
  arr2 = np.array([[1,0,0,0,0,2],
                   [0,1,1,1,1,0],
                   [0,1,2,2,1,0],
                   [0,1,2,2,1,0],
                   [0,1,1,1,1,0],
                   [2,0,0,0,0,1]])
  </code></pre>
  <p>the information returned would be</p>
  <pre><code># for arr1
  patch_info_dict = {&quot;1&quot;: (18, 18), &quot;0&quot;: (18, 18)}
  
  # for arr2
  patch_info_dict = {&quot;1&quot;: (1, 4), &quot;1&quot;: (1, 4), &quot;2&quot;: (1, 4), &quot;2&quot;: (1, 4),
                     &quot;0&quot;: (4, 10), &quot;0&quot;: (4, 10), &quot;0&quot;: (4, 10), &quot;0&quot;: (4, 10),
                     &quot;2&quot;: (4, 8), &quot;1&quot;: (12, 24)}
  </code></pre>
  <p>As you can see, I want the perimeter to be the sum of the inner and outer perimeters (seen in the square ring of 1s in <code>arr2</code>) and elements that are diagonal from other elements of the same value are not part of the same patch.</p>
  <p>I'm having trouble starting to write this program. Some brainstorming ideas I've had include identifying constraints, such as the area of each patch must obviously add up to the <code>np.size()</code> of the entire array, but I'm not sure if that's even useful.</p>
  <p>Another idea I had was to convert this to a picture somehow, maybe using <code>plt.matshow()</code>:
  <a href="https://i.stack.imgur.com/giNHb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/giNHb.png" alt="images of arrays" /></a>
  and then using some image analysis library to analyze the picture, but I don't know enough about these types of libraries.</p>
  <p>If anyone has any pointers of even getting started or libraries/functions that might be useful, I'd appreciate the help. Thanks!</p>