如何在Python中缩放图片?

0 投票
2 回答
1701 浏览
提问于 2025-04-16 14:18
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 个回答

-1

虽然这可能有点多余,具体要看你的最终目标是什么。不过,用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(...
4

如果你在使用 PIL 这个库,

你可以用这行代码来打开一张图片并把它转换成灰度图:greyscaleIm = Image.open(filename).convert("L")

想了解更多,可以访问这个链接:http://effbot.org/imagingbook/introduction.htm

撰写回答