简体   繁体   中英

image processing in python - not working as well as I thought

I have a picture that I want to scale it down. Therefore, I wrote this code:

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

The value is how much I want to scale the image down. However, when I choose the value to be bigger than 2, I got errors. I need to choose the value 2 to receive no errors. Can you help me find why?

out1 need to be bigger.

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

This seemed to work with value of 3\\4\\5 atleast.

Some code to show why the original failed, Here with value = 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM