Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep image alignment when cropping in Python?

I'm trying to crop and resize images in Python, and I want them to be in a fixed format afterwards (47x62 Pixels). However, if the original image is in landscape, my algorithm doesn't work, there are blank areas.

import Image, sys

MAXSIZEX = 47
MAXSIZEY = 62

im = Image.open(sys.argv[1])
(width, height) = im.size

ratio = 1. * MAXSIZEX / MAXSIZEY

im = im.crop((0, 0, int(width*ratio), int(height*ratio)))
im = im.resize((MAXSIZEX, MAXSIZEY), Image.ANTIALIAS)

im.save(sys.argv[2])

I want the resized image to be fully 47x62 - there should be no empty area visible.

like image 559
Erik Sebastian Bovee Avatar asked Nov 12 '22 21:11

Erik Sebastian Bovee


1 Answers

You should first check if MAXSIZEX is greater then the width or the MAXSIZEY is greater than the height. If they are first rescale the image and then do the cropping:

MAXSIZEX = 64
MAXSIZEY = 42
width, height = im.size

xrat = width / float(MAXSIZEX)
yrat = height / float(MAXSIZEY)

if xrat < 1 or yrat < 1:
    rat = min(xrat, yrat)
    im = im.resize((int(width / rat), int(height / rat)))
res = im.crop((0, 0, MAXSIZEX, MAXSIZEY))
res.show()
like image 171
Viktor Kerkez Avatar answered Nov 14 '22 21:11

Viktor Kerkez