2013-07-07 65 views
1

我正在編寫程序來更改圖片各個部分的顏色。在這種情況下,圖像的頂部和底部三分之一。程序不識別y值<總高度的三分之一

我可以改變底部三分之一,但由於某種原因,程序無法識別if (y<h/3)我試着把一個實際的數字代替這個,並且改變了我編碼顏色變化的方式。

有人可以指出我可能犯的錯誤(可能很明顯)。

def changeByThirds(pic): 
    w= getWidth (pic) 
    h = getHeight(pic) 

    newPic = makeEmptyPicture(w,h) 
    for x in range (0,w): 
    for y in range (0,h): 
     pxl = getPixel(pic, x, y) 

     if (y<h/3): 
     newPxl= getPixel (newPic, x, y) 
     color = makeColor(getRed(pxl)*0.1, getGreen(pxl), getBlue(pxl)) 
     setColor (newPxl, color) 

     if (y>(h*2/3)): 
     newPxl= getPixel (newPic, x, y) 
     color = makeColor(getRed(pxl), getGreen(pxl), 0) 
     setColor (newPxl, color) 

     else: 
     newPxl = getPixel (newPic, x, y) 
     color = getColor(pxl) 
     setColor (newPxl, color) 

    return (newPic) 

def do(): 
    file = pickAFile() 
    pic = makePicture(file) 
    newPic = changeByThirds(pic) 
    writePictureTo(newPic, r"D:\FOLDER\0pic3.jpg") 
    explore (newPic) 

回答

2

您需要使用elif,不if,在你的第二塊:

if (y<h/3): 
    ... 

    elif (y>(h*2/3)): #<-- change if to elif 
    ... 

    else: 
    ... 

否則,最終else得到執行,即使y < h/3

+1

它不繞過第一個「if」。那個'如果'塊被執行了。但是,它遇到第二個'if..else'語句,它將'y>(h * 2/3)'評估爲False,所以它也**執行'else'塊。這些陳述覆蓋了第一個「if」塊所做的工作。 – unutbu

+0

我知道學習會令人沮喪,但只要不斷嘗試。我們學到的最好的教訓來自犯錯誤。 – unutbu