在python中复制较小的图片

时间:2013-10-16 15:46:14

标签: python image

我正在尝试编写一个函数来接收图片,将其缩小两倍并将该图片放入空白画布。我觉得我输入正确,但它一直给我错误:

getPixel(picture,x,y): y (= 480) is less than 0 or bigger than the height (= 479)

错误是:

Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.

这是我的代码:

def makeSmaller(Picture):
    pic = Picture
    width = getWidth(pic)
    height = getHeight(pic)
    canvas = makeEmptyPicture(width /2 , height /2)
    sourceX = getWidth(canvas)
    for x in range (0, getWidth(canvas)- 1):
        sourceY = getHeight(canvas)
        for y in range (0, getHeight(canvas)- 1):
            color = getColor(getPixel(pic, sourceX, sourceY))
            setColor(getPixel(canvas, x, y), color)
            sourceY = sourceY + 2
    sourceX = sourceX + 2
    show(pic)

1 个答案:

答案 0 :(得分:1)

我认为你需要:

color = getColor(getPixel(pic, sourceX-1, sourceY-1))

这样你就不会出界了。现在发生的事情是你正试图访问一个不存在的像素,因为你有:

sourceY = getHeight(canvas)    #sourceY = 480

但像素的索引编号为0到479。


我认为你所需要的就是这样的。你做了很多不必要的事情。

def makeSmaller(pic):

    #setup the canvas to draw to
    width = getWidth(pic)
    height = getHeight(pic)
    canvas = makeEmptyPicture(width /2 , height /2)

    #loop through all pixels of the canvas
    for x in range (0, getWidth(canvas)- 1):
        for y in range (0, getHeight(canvas)- 1):

            #grab the appropriate pixel from the original picture ( *2 )
            color = getColor(getPixel(pic, x * 2, y * 2))

            #assign that color the corresponding pixel on the canvas
            setColor(getPixel(canvas, x, y), color)

    show(pic)