title: element-wise count along axis of values in numpy array
body: <p>How can I get an element-wise count of each element's number of occurrences in a numpy array, along a given axis? By "element-wise," I mean each value of the array should be converted to the number of times it appears.</p>
  
  <p>Simple 2D input:</p>
  
  <pre><code>[[1, 1, 1],
   [2, 2, 2],
   [3, 4, 5]]
  </code></pre>
  
  <p>Should output:</p>
  
  <pre><code>[[3, 3, 3],
   [3, 3, 3],
   [1, 1, 1]]
  </code></pre>
  
  <p>The solution also needs to work relative to a given axis. For example, if my input array <code>a</code> has shape <code>(4, 2, 3, 3)</code>, which I think of as "a 4x2 matrix of 3x3 matrices," running <code>solution(a)</code> should spit out a <code>(4, 2, 3, 3)</code> solution of the form above, where each <code>3x3</code> "submatrix" contains counts of the corresponding elements relative to that submatrix alone, rather than the entire numpy array at large.</p>
  
  <p>More complex example: suppose I take the example input above <code>a</code> and call <code>skimage.util.shape.view_as_windows(a, (2, 2))</code>. This gives me array <code>b</code> of shape <code>(2, 2, 2, 2)</code>:</p>
  
  <pre><code>[[[[1 1]
     [2 2]]
  
    [[1 1]
     [2 2]]]
  
  
   [[[2 2]
     [3 4]]
  
    [[2 2]
     [4 5]]]]
  </code></pre>
  
  <p>Then <code>solution(b)</code> should output:</p>
  
  <pre><code>[[[[2 2]
     [2 2]]
  
    [[2 2]
     [2 2]]]
  
  
   [[[2 2]
     [1 1]]
  
    [[2 2]
     [1 1]]]]
  </code></pre>
  
  <p>So even though the value 1 occurs 3 times in <code>a</code> and 4 times in <code>b</code>, it only occurs twice in each <code>2x2</code> window.</p>