在Python中平滑调整大小的图像(如何像计算机科学家一样思考)

时间:2015-02-07 19:25:09

标签: python image smoothing

我坚持[[如何像计算机科学家一样思考]提供的练习](http://interactivepython.org/runestone/static/thinkcspy/MoreAboutIteration/Exercises.html):

  

在对图像进行过度缩放后,它看起来很块状。一种方式   减少图像的阻塞是用每个像素替换   它周围像素的平均值。这有效果   平滑颜色的变化。写一个需要的函数   将图像作为参数并平滑图像。你的功能应该   返回一个与旧图像相同但又平滑的新图像。

这是我的源代码:

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)

0 个答案:

没有答案