2014-01-07 38 views
0

我有一張圖片,我想縮小它。因此,我寫了這樣的代碼:在python中的圖像處理 - 不工作以及我認爲

def scaling_down(ima, value): 
###~Scaling down the image by a value~### 
value = int(value) 
width, height = ima.size 
mat_m = ima.load() 
width2 = (int(width) + 1)/value 
height2 = (int(height)+1)/value 
out1 = Image.new('L',(width2,height2)) 
out_the_pix = out1.load() 
for x in range(0,width,value): 
    for y in range(0,height,value): 
     out_the_pix[x/value,y/value] = mat_m[x,y] 
return out1 

這個值是我想縮放圖像的多少。 但是,當我選擇的值大於2時,出現錯誤。我需要選擇值2來接收沒有錯誤。你能幫我找到原因嗎?

+1

定義的 「錯誤」。 –

+0

這是PIL嗎?你應該修復你問題中的縮進。 – moooeeeep

+0

DRY,scikit-image有這個功能。 http://scikit-image.org/docs/dev/api/skimage.transform.html?highlight=hough#skimage.transform.downscale_local_mean – M4rtini

回答

0

out1需要更大。

from math import ceil 
width2 = int(ceil(1.0*width/value)) 
height2 = int(ceil(1.0*height/value)) 

這似乎適用於至少3 \ 4 \ 5的值。

一些代碼來說明,爲什麼原來的失敗,這裏有值= 3

>>>x = range(10) 
>>>width = len(x) 
>>>width 
10 
>>>width2 = (width + 1)/3 
>>>width2 
3 
>>>for x in range(0,width, 3): 
    .....:  print x/3 
    .....: 
0 
1 
2 
3 <-- this would give the index error. Last index would be 2. 

>>>widthLonger = (width + width%3 + 1)/3 
>>>widthLonger 
4 
+0

首先,謝謝。我得到這個錯誤: out_the_pix [x/value,y/value] = mat_m [x,y] IndexError:圖像索引超出範圍 爲什麼?有什麼問題? – user3160249

+0

在循環結束時,x/value和\或y /值最終會比您爲out1大小設置的值大。 – M4rtini

+0

但低於2? – user3160249