title: numpy masked smoothing algorithm
body: <p>I have a smoothing algorithm that I implemented that basically applies a kernel: </p>
  
  <pre><code> [0 1 0;
    1 4 1;
    0 1 0]/8
  </code></pre>
  
  <p>to a matrix (image) and then corrects the edges and corners, equivalent to setting the kernel as</p>
  
  <pre><code> [0 1 0;
    0 5 1;
    0 1 0]/8
  </code></pre>
  
  <p>for a left edge, and</p>
  
  <pre><code> [0 0 0; 
    0 6 1; 
    0 1 0]/8
  </code></pre>
  
  <p>for a top-left corner. </p>
  
  <p>My goal now is to apply a smoothing that only applies to a masked part of that image. For example (refer to images below), if I had a square image of a disk, where the disk would have values of 128+-10 (+-10 is a noise effect), and the background is black (value of 0), the normal smoothing algorithm applied infinite times should give a square image with a constant pixel intensity. For the masked smoothing algorithm I would like to mask the disk such that the algorithm applied infinite times should give a uniform disk at 128 and a black (0) background. In other words, only the disk was smoothed.</p>
  
  <p>The main thing that I'm trying to avoid is that the background "bleeds" into the disk, making the edges of the disk fuzzy. I'm also willing to change the smoothing algorithm to something different (eg. average of 3x3 pixels) that would allow for a more efficient approach.</p>
  
  <p><a href="https://i.stack.imgur.com/FN36fb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FN36fb.png" alt="NoisyOriginal"></a>( Noisy Original )</p>
  
  <p><a href="https://i.stack.imgur.com/WKLFcb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WKLFcb.png" alt="Standard Smooth"></a> (After the normal smooth)</p>
  
  <p><a href="https://i.stack.imgur.com/fD05Vb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fD05Vb.png" alt="MakedSmooth"></a>( After the masked smooth )</p>
  
  <p>Here is my code for normal smooth:</p>
  
  <pre><code>def SmoothImage(Matrix,N=1):
      '''Smooths a Matrix with kernel [0 1 0; 1 4 1; 0 1 0]/8'''
      A=Matrix.copy()
      for i in range(N):
          s=A.shape[0]-1
          B=A*4.0
          B[-s:,:]+=A[:s,:]
          B[0,:]+=A[0,:]
          B[:,-s:]+=A[:,:s]
          B[:,0]+=A[:,0]
  
          B[:s,:]+=A[-s:,:]
          B[-1,:]+=A[-1,:]
          B[:,:s]+=A[:,-s:]
          B[:,-1]+=A[:,-1]
          B*=1/8
          A=B
      return A
  </code></pre>