Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve Image Quality when rotating with PIL

Basically I'm trying to be able to rotate images via user interface, however I've noticed that the image quality severely decreases upon each rotation. Does anyone know how to fix that? Also when the image is rotated it crops off parts of the image each time.

here are some pictures of before and after: http://imgur.com/a/QESKs

And here's the code:

def onRotate(self):
    tanTheta = float(hh)/float(ww) 
    theta = math.atan(tanTheta) * 57.2957795 # convert to degrees
    if theta > 0:
        angle = (90 - theta) * -1
        clockwise = True
    elif theta < 0:
        angle = (270 - theta) * -1
        clockwise = False
    else:
        tkMessageBox('Angle not okay', 'Try again!')
    rotated_small = photo_small.rotate(angle) 
    rotated_small.save('small_rotate.jpg')
    self.load_imgfile('small_rotate.jpg')
like image 368
loonyuni Avatar asked Jul 23 '13 22:07

loonyuni


3 Answers

rotated_small = photo_small.rotate(angle, resample=Image.BICUBIC, expand=True)

This tells it to use the highest quality interpolation algorithm that it has available, and to expand the image to encompass the full rotated size instead of cropping. The documentation does not say what color the background will be filled with.

like image 102
Mark Ransom Avatar answered Oct 19 '22 00:10

Mark Ransom


An image is a grid of pixels. If you rotate it (and angle isn't a multiple of 90) the rotated grid must be rematched to a new non-rotated grid to display the image. Some loss can't be avoided in this process.

Only option would be to keep the unrotated image somewhere and sum up the angles of multiple rotations and always build the rotated image from the initial unrotated one.

like image 31
Michael Butscher Avatar answered Oct 19 '22 01:10

Michael Butscher


If you are rotating jpegs at 90 degree increments you want to use JPEGTran, which will do lossless rotation:

  • https://jpegtran-cffi.readthedocs.io/en/latest/#api-reference
  • https://pypi.org/project/jpegtran-cffi/

See rotate() and exif_autotransform(). A CLI may be easier:

  • sudo apt install libjpeg-turbo-progs
like image 1
Gringo Suave Avatar answered Oct 19 '22 01:10

Gringo Suave