如何在Python中缩放图像?

时间:2011-03-24 00:47:12

标签: python

def scaleImage(image):
    """
    A function that takes an image and makes each pixel grayscale:
    the red, blue, green components are the average of the respective
    components in each original pixel.
    """

    pix = image.getPixels()

    # How can I condense the following loop?

    newimage = Image()
    for pixel in pix:
        newpixel = ((int(pixel[0]) + int(pixel[1]) + int(pixel[2]))/3,
                    (int(pixel[0]) + int(pixel[1]) + int(pixel[2]))/3,
                    (int(pixel[0]) + int(pixel[1]) + int(pixel[2]))/3,
                     int(pixel[3]))
        newimage.setPixels(newpixel)

    return newimage

我的任务是编写一个函数showScale(),询问用户图像文件名,然后在窗口中显示该图像及其灰度版本。

def showScale():

    filename = raw_input("The name of the image file? ")
    picture = Image.open(filename)
    newpicture = Image.open(scaleImage(picture))
    newpicture.show()

问题1。我应该使用cs1graphics模块使其工作吗?

问题2。我该如何更改代码以回答我的任务?

2 个答案:

答案 0 :(得分:3)

如果您使用PIL

greyscaleIm = Image.open(filename).convert("L")

http://effbot.org/imagingbook/introduction.htm

答案 1 :(得分:0)

虽然根据你的最终目标可能会有些过分。也可以使用opencv。

img = cv.LoadImage(image)
gray = cv.cvCreateImage ((img.width, img.height), 8, 1)
cv.cvCvtColor(img, gray, cv.CV_BGR2GRAY)

然后用

显示
cv.NamedWindow(...
cv.ShowImage(...