Search code examples
pythonevaluationcomparison-operators

Why >= evaluation does not work Python


">=" seems does not work. When fixedx = 100 and len(img[0]) is 100, the code does not execute the printing statement and change the value of fixedx to 99

Both variables are integers. Is there any other way to do the comparison in python?

single_sm.jpg is a 100x125 jpg file. Thus, len(img) = 125, len(img[0]) = 100.

Running script below produce:

Traceback (most recent call last):

File "shrink.py", line 69, in

changed_img = shrink(pix, 0, 81, 25, 20, downsp)

File "shrink.py", line 37, in shrink

result[i,j] = img[fixedx, fixedy]

IndexError: index 100 is out of bounds for axis 1 with size 100

from PIL import Image
import numpy as np
import math

def shrink(img, x, y, size, scale, downsp):

    result = np.zeros((scale, scale, 3), dtype=np.uint8)
    scale_factor = math.floor(size/scale)
    for i in xrange(scale):
        for j in xrange(scale):

            fixedx = int(i*scale_factor+x)
            fixedy = int(j*scale_factor+y)

            if fixedx >= (len(img[0]) - 1):
                print "in this step"
                fixedx = len(img[0]) - 1
            if fixedy >= (len(img) - 1): 
                fixedy = len(img) - 1

            result[i,j] = img[fixedx, fixedy]
    return result

if __name__ == '__main__':

    img = Image.open("imgs/single_sm.jpg")
    pix = np.array(img)
    downsp = True
    changed_img = shrink(pix, 0, 81, 25, 20, downsp)
    changed_img = np.array(changed_img)
    resized = Image.fromarray(changed_img, 'RGB')
    resized.save('downsp.jpg')

Solution

  • The error says:

    IndexError: index 100 is out of bounds for axis 1 with size 100
    

    Since the axis 1 is the second dimension of array (fixedy, not fixedx), this means that the value of the array is different by what you are expecting. So the conclusion is that the array has 125x100 pixel (and in effect this is exactly what you say: len(img) = 125, len(img[0]) = 100), not 100x125.

    To confirm this, I tried your program by substituting the image with a plain array of 125x100 zeros, and it showed the same error message than yours. Then I tried it with a 100x125 array, and it worked.