title: How to smooth an image with a 3x3 kernel
body: <p>I am trying to smooth an image, by looping through its pixels, calculating the average of a 3x3 patch and then applying the average to all 9 pixels in this patch.</p>
  
  <p>Code:</p>
  
  <pre><code>    import matplotlib.pyplot as plt
      import numpy as np
      import cv2 as cv
      from PIL import Image
  
  
      # 1. Load Image
      name = 'ebay.png'
      img = cv.imread(name) #import image
  
      h, w = img.shape[:2]
  
  
      # 2. Smooth with kernel size 3
  
      for y in range(0, w, 3):
          for x in range(0, h, 3):     
              px1 = img[x][y] #0/0
              px2 = img[x][y+1] #0/1
              px3 = img[x][y+2] #0/2
              px4 = img[x+1][y] #1/0
              px5 = img[x+1][y+1] #1/1
              px6 = img[x+1][y+2] #1/2
              px7 = img[x+2][y] #2/0
              px8 = img[x+2][y+1] #2/1
              px9 = img[x+2][y+2] #2/2
  
              average = np.average(px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9)    
  
              img[x][y] =  average  #0/0
              img[x][y+1] = average   #0/1
              img[x][y+2] = average   #0/2
              img[x+1][y] = average   #1/0
              img[x+1][y+1] = average   #1/1
              img[x+1][y+2] = average  #1/2
              img[x+2][y] = average  #2/0
              img[x+2][y+1] = average   #2/1
              img[x+2][y+2] = average  #2/2
  
  # 3. Transform the resulting image into pgm format and save result        
  
  new_image = Image.fromarray(img)
  new_image.save('new.png')
  
  # 4. Show image
  
  new_image.show()
  
  However this just makes my new image just very pixely and not smooth at all. 
  </code></pre>
  
  <p>I am assuming that I am doing something wrong here:</p>
  
  <pre><code>average = np.average(px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9)
  </code></pre>
  
  <p>since, when I am using just px5 as an average the new image looks much better (but still not very smoothy). Please see image below:</p>
  
  <p>Original Image:
  <a href="https://i.stack.imgur.com/mqYG3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mqYG3.png" alt="Original Image"></a></p>
  
  <p>What my code is doing right now:
  <a href="https://i.stack.imgur.com/CQAvq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CQAvq.png" alt="What my code is doing right now..."></a></p>
  
  <p>Result when I am using px5 as average:
  <a href="https://i.stack.imgur.com/VfSnW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VfSnW.png" alt="Result when I am using px5 as average"></a></p>
  
  <p>Result when adding all px's and dividing by 9:
  <a href="https://i.stack.imgur.com/oFLDB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oFLDB.jpg" alt="enter image description here"></a></p>