2011-03-24 32 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(...