title: Smoothing resized images in Python (How to Think Like a Computer Scientist)
body: <p>I am stuck on this exercise provided by ["How To Think Like A Computer Scientist"] (<a href="http://interactivepython.org/runestone/static/thinkcspy/MoreAboutIteration/Exercises.html" rel="nofollow">http://interactivepython.org/runestone/static/thinkcspy/MoreAboutIteration/Exercises.html</a>):</p>
  
  <blockquote>
    <p>After you have scaled an image too much it looks blocky. One way of
    reducing the blockiness of the image is to replace each pixel with the
    average values of the pixels around it. This has the effect of
    smoothing out the changes in color. Write a function that takes an
    image as a parameter and smooths the image. Your function should
    return a new image that is the same as the old but smoothed.</p>
  </blockquote>
  
  <p>Here's my source code:</p>
  
  <pre><code>def smooth(img):
  for i in range(img.getWidth()):
      for j in range(img.getHeight()):
          #first step: get surrounding pixels
          #top pixel
          ptopcenter = img.getPixel(i,j-1)
          ptopleft = img.getPixel(i-1,j-1)
          ptopright = img.getPixel(i+1,j-1)
  
          #center pixel
          pcent = img.getPixel(i,j)
          pcentleft = img.getPixel(i-1,j)
          pcentright = img.getPixel(i+1,j)
  
          #bottom pixel
          pbotcenter = img.getPixel(i,j+1)
          pbotleft = img.getPixel(i-1,j+1)
          pbotright = img.getPixel(i+1,j+1)
  
          #second step: average pixels
          p1Red = ptopcenter.getRed()
          p1Blue = ptopcenter.getBlue()
          p1Green = ptopcenter.getGreen()
  
          p2Red = ptopcenter.getRed()
          p2Blue = ptopcenter.getBlue()
          p2Green = ptopcenter.getGreen()
  
          p3Red = ptopright.getRed()
          p3Blue = ptopright.getRed()
          p3Green = ptopright.getRed()
  
          p4Red = pcentleft.getRed()
          p4Blue = pcentleft.getBlue()
          p4Green = pcentleft.getGreen()
  
          p5Red = pcentright.getRed()
          p5Blue = pcentright.getBlue()
          p5Green = pcentright.getGreen()
  
          p6Red = pbotleft.getRed()
          p6Blue = pbotleft.getBlue()
          p6Green = pbotleft.getGreen()
  
          p7Red = pbotcenter.getRed()
          p7Blue = pbotcenter.getBlue()
          p7Green = pbotcenter.getGreen()
  
          p8Red = pbotright.getRed()
          p8Blue = pbotright.getBlue()
          p8Green = pbotright.getGreen()
  
          #average all the colors
          pavgRed = (p1Red + p2Red + p3Red + p4Red + p5Red + p6Red + p7Red + p8Red)/8
          pavgBlue = (p1Blue + p2Blue + p3Blue + p4Blue + p5Blue + p6Blue + p7Blue + p8Blue)/8
          pavgGreen = (p1Green + p2Green + p3Green + p4Green + p5Green + p6Green + p7Green + p8Green)/8
  
          pcent.setRed(pavgRed)
          pcent.setGreen(pavgGreen)
          pcent.setBlue(pavgBlue)
  </code></pre>