title: How to efficiently identify "similar-HSV-to-neightbours" pixels in numpy array?
body: <p>My image (<code>np.array</code> with shape <code>[Y] [X] [RGB]</code> contains glyph-graphics, which form regions of similar-HSL pixels. e.g. (magnified):</p>
  <p><a href="https://i.stack.imgur.com/VcU5f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VcU5f.png" alt="enter image description here" /></a></p>
  <p>I'm trying to identify the HSL value of the text.</p>
  <p>Throwing all pixels into scikit's <code>kmeans</code> <em>might</em> do the trick, as it will return clusters.</p>
  <p>However I need efficiency. If I could first restrict the pixels-set to &quot;those with 8 similar-HSL neighbours&quot;, this would boost performance significantly.</p>
  <p>Something like:</p>
  <pre class="lang-py prettyprint-override"><code>hsv = cv2.cvtColor(S, cv2.COLOR_RGB2HSV)
  hues = hsv[:,:,0]
  
  THRESH = 3
  isclose = lambda hues_matrix_A, hues_matrix_B): \
      np.abs(hues_matrix_B - hues_matrix_A) &lt; THRESH
  mask = 
      is_close(hues, np.roll(hues,-1, axis=0)) &amp; 
      is_close(hues, np.roll(hues,+1, axis=0)) &amp; 
      is_close(hues, np.roll(hues,-1, axis=1)) &amp; 
      is_close(hues, np.roll(hues,+1, axis=1)) 
  </code></pre>
  <p>That does the up/down/left/right neighbours and it is already ugly. Ideally I would test against the diagonal neighbours also, but that would involve a 2-axis-<code>roll</code>:</p>
  <pre><code>top_left_neighbour = np.roll(np.roll(hues,-1, axis=1),-1, axis=0)
  </code></pre>
  <p>eek. Does there exist a tool for this job? Interface might look like this:</p>
  <pre><code>mask = proximity_mask(src=hues_matrix, kernel=np.ones((3,3)), proximity=3)
  </code></pre>
  <p>And if not, what would be an intelligent construction?</p>