0

Ok, so I have written a program that loads random images from an online source and then loads them one by one to my Gnome desktop on Arch Linux.

Now, I want to check their aspect ratio and only show images that are the same as my screen's aspect ratio.

I have the following functions to determine the aspect ratio:

def highest_common_factor(width,height):
    """Support function to calculate the aspect ratio of a (width:height) input.
    Stolen fron online, sometimes also reffered to as the GCD value"""
    if(height==0): 
        return width 
    else: 
        return highest_common_factor(height,width%height) 

def get_current_resolution():
    """Get current screenresolution"""

    screen_resolutions = subprocess.Popen(["xrandr"], stdout=subprocess.PIPE)
    get_current_resolution = subprocess.Popen(["grep", '*'], stdin=screen_resolutions.stdout, stdout=subprocess.PIPE)
    current_resolution = get_current_resolution.communicate()[0].decode().split()[0]
    current_width = int(current_resolution.split("x")[0])
    current_height = int(current_resolution.split("x")[1])
    return current_width, current_height

def get_aspect_ratio(resolution):
    """Determine current aspect ratio"""

    width = resolution[0]
    height = resolution[1]
    gcd = highest_common_factor(width,height)
    aspect_width = width/gcd
    aspect_height = height/gcd
    return round(aspect_width), round(aspect_height)

The problem is this

These functions work perfectly if the image has perfect dimensions, e.g. 1200:900, and I feed those into the get_aspect_ratio() function, I get a perfect result 4:3. However, if the image is less perfect and has a resolution of 1200:901, I also get an aspect ratio of 1200:901.

Mathematically speaking this is correct, but a human would easily see this is actually 4:3.

I've been thinking about how to tackle this problem but so far haven't found a working solution. Any ideas or insights are welcome!

Montmons
  • 1,416
  • 13
  • 44

1 Answers1

0

Ah, solved it! Thanks to this answer that introduced me to the fact that the ndigits paramater of round also accepts a negative value.

So I could simply do:

def get_aspect_ratio(resolution):
    """Determine current aspect ratio"""

    width = resolution[0]
    height = resolution[1]
    gcd = highest_common_factor(round(width,-1),round(height,-1))
    aspect_width = width/gcd
    aspect_height = height/gcd
    return round(aspect_width), round(aspect_height)

And now it works perfectly :)

Montmons
  • 1,416
  • 13
  • 44