Python中块图像的简单平滑

2024-09-28 20:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图帮助某人解决一个关于如何像计算机科学家一样思考的实践问题。我读过其他人也有同样的问题,但是没有一个答案是有用的,因为他们使用了我们还没有学到的东西。您将根据代码了解我们的级别。但基本上,它应该是for循环和if语句的组合,以平滑块状图像。这里是实践问题:

After you have scaled an image too much it may look 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 (or blurring) out the changes in color. Write a function smooth(imageFile) that takes an image and returns a new image of the same size as the original but with the colors smoothed. To smooth a pixel at location (c, r) you would need to average the color components of nine values located as follows: ...

这是我们到目前为止的功能。。。它有点模糊了图像,但没有达到我认为问题所在的程度,因为它说这是错误的:

def smooth(imageFile):
    w = imageFile.getWidth()
    h = imageFile.getHeight()
    newImg = image.EmptyImage(w, h)

    for col in range(1, w-1):
        for row in range(1, h-1):
            pix = imageFile.getPixel(col, row)
            top = imageFile.getPixel(col, row-1)
            tr = imageFile.getPixel(col+1, row-1)
            r = imageFile.getPixel(col+1, row)
            br = imageFile.getPixel(col+1, row+1)
            bot = imageFile.getPixel(col, row+1)
            bl = imageFile.getPixel(col-1, row+1)
            l = imageFile.getPixel(col-1, row)
            tl = imageFile.getPixel(col-1, row-1)
            
            for x in range(-1, 1):
                for y in range(-1, 1):
                    if (-1 < x < w) and (-1 < y < h):
                        red = int((pix.getRed() + top.getRed() + tr.getRed() + r.getRed() + br.getRed() + bot.getRed() + bl.getRed() + l.getRed() + tl.getRed()) // 9)
                        green = int((pix.getGreen() + top.getGreen() + tr.getGreen() + r.getGreen() + br.getGreen() + bot.getGreen() + bl.getGreen() + l.getGreen() + tl.getGreen()) // 9)
                        blue = int((pix.getBlue() + top.getBlue() + tr.getBlue() + r.getBlue() + br.getBlue() + bot.getBlue() + bl.getBlue() + l.getBlue() + tl.getBlue()) // 9)
   
                        new_pix = image.Pixel(red, green, blue)
                        newImg.setPixel(col, row, new_pix)

    return newImg

def main():
    width = 100
    height = 50
    win = image.ImageWin(width*2, height)
    img = makeBlockImage(width, height, 10, 10, 1)
    img.draw(win)

    newimg = smooth(img)
    newimg.draw(win, width, 0)
    win.exitonclick()

if __name__ == "__main__":
    main()

请帮助并提供最基本的解决方案(如中所示,不要使用花哨的函数或任何东西……请使用for和if,就像您在代码中看到的那样)。提前谢谢你


Tags: oftheinimageforifcolrow