smoothing a resized image in Python
Question: I'm working my way through [How to Think Like a Computer
Scientist](http://interactivepython.org/runestone/static/thinkcspy/toc.html#),
and I've gotten stuck on the following exercise:

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.

The tutorial provides a truncated image module, but I am supposed to be able
to solve this without using PIL. This is what I have so far:

    
    
    import image
    #image provided in tutorial
    img = image.Image("luther.jpg")
    win = image.ImageWin()
    factor = 0
    
    #resize the image
    def resize(img, factor):
    W = img.getWidth()
    H = img.getHeight()
    
    newW = int(W * factor)
    newH = int(H * factor)
    
    newImage = image.EmptyImage(newW, newH)
    
    for col in range(newW):
        for row in range (newH):
            p = img.getPixel(col, row)
            newImage.setPixel(col * factor, row * factor, p)
    
    newImage.draw(win)
    img = newImage
    return img
    #smooth out the image   
    def smooth(img):
        newImage = image.EmptyImage(img.getWidth(), img.getHeight())
        for col in range(img.getWidth()):
            for row in range(img.getHeight()):
                p1 = img.getPixel(col, row)
                p2 = img.getPixel(col+1, row)
                red1 = p1.getRed()
                red2 = p2.getRed()
                green1 = p1.getGreen()
                green2 = p2.getGreen()
                blue1 = p1.getBlue()
                blue2 = p2.getBlue()
                newRed = (red1 + red2)/2
                newGreen = (green1 + green2)/2
                newBlue = (blue1 + blue2)/2
                newPixel = image.Pixel(newRed, newGreen, newBlue)
                newImage.setPixel(col, row, newPixel)
        newImage.draw(win)
    

When I call the function, I get "Error: local variable red2 referenced before
assignment." I have gone line-by-line with print statements; this error
message is not returned until I try to create newPixel. Any help would be much
appreciated.


Answer: Can you print red2, if then, what is the output? You probably get None for
red2. Please post the rest of your code, so we can see if something is wrong
with img

