accurate image aspect ratio in python
Question: I have the following code to get the aspect ratio of an image

    
    
    img0 = color.rgb2gray(io.imread("C:\\work\\TRAIN\\SET1\\bus.jpg"))
    img0 = resize(img0, (40, 116))
    ar = 1.0 * (img0.shape[1]/img0.shape[0])
    print "aspect ratio: " 
    print ar
    

The output is `2.0`. But that's not true. For an image with width 116 and
height 40, the aspect ratio should be `116/40 = 2.9`.

Where is my calculation going wrong?


Answer: The problem in you case is that img0.shape[1] and img0.shape[0] are both
integers. You have performed integer division, and then converted it to float.
You could try:

    
    
    float(img0.shape[1]) / img0.shape[0]
    

or

    
    
    1.0 * img0.shape[1] / img0.shape[0]
    

or, my recommended method, is to add as the first line of code in the file
this import

    
    
    from __future__ import division
    

This will make "/" always perform floating point calculation, to avoid such
cases. If you want to specifically use integer division, use "//", as in 10 //
3

