python中的图像处理 - 不像我想的那样工作

时间:2014-01-07 16:51:19

标签: python image-processing

我有一张照片,我想缩小它。因此,我写了这段代码:

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 :(得分: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