2011-03-24 30 views
0
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(),要求用户输入图像文件名,然后在窗口中显示该图像及其灰度版本。如何在Python中缩放图像?

def showScale(): 

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

Question1。我应该使用cs1graphics模块来使它工作吗?

Question2。我应该如何更改我的代码来回答我的任务?

+1

你的标题很一般同时显示。我认为你应该编辑它以更具体。 – senderle 2011-03-24 00:56:03

+0

您的灰度算法不正确。这是一个加权平均值,而不是一个平均值。 – 2011-03-24 01:12:40

+0

@ pynator:来自hkus10的所有问题看起来都像功课...... – gok 2011-03-24 09:23:37

回答

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(...