Rotate and crop with aspect ratio (imagemagick + python)

Started by a1ex, August 29, 2013, 08:05:54 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

a1ex

I was looking for a easy way to rotate a bunch of images with some small angle, and crop them to the same aspect ratio, in batch mode. Since I couldn't find one, I wrote a little script to do that.


#!/usr/bin/python

# Rotate images and crop with aspect ratio (just like Gimp's "crop with aspect")
# (C) 2013 a1ex. License: GPL.

# Usage: python rotate_with_aspect.py input.jpg output.jpg angle

# The aspect ratio is hardcoded in fix_roll (default 3:2)

from __future__ import division
import sys, os
from math import *

def rot(x, y, ang):
    c = cos(ang * pi / 180)
    s = sin(ang * pi / 180)
    return c*x - s*y, s*x + c*y

def fix_roll(pic, roll, out):

    w0 = w = 3000
    h0 = h = 2000

    if roll > 45:
        w0,h0 = h0,w0
        w,h = h,w
        roll = -90 + roll
    if roll < -45:
        w0,h0 = h0,w0
        w,h = h,w
        roll = 90 + roll
   
    w1,h1 = rot(w, h, -roll)
    w2,h2 = rot(w, -h, -roll)
    w = max(abs(w1),abs(w2))
    h = max(abs(h1),abs(h2))

    crop_x = 100 * w0 / w;
    crop_y = 100 * h0 / h;
   
    s = 1
    for x in range(-w0, w0):
        wx,hx = rot(x, h0, abs(roll))
        wx,hx = abs(wx),abs(hx)
        s = min(s, max(wx/w0, hx/h0))

    for y in range(-h0, h0):
        wy,hy = rot(w0, y, abs(roll))
        wy,hy = abs(wy),abs(hy)
        s = min(s, max(wy/w0, hy/h0))

    s *= 1.001
    crop_x *= s
    crop_y *= s
   
    cmd = "convert %s -gravity Center -rotate %g -crop %g%%x%g%% %s" % (pic, -roll, crop_x, crop_y, out);
    os.system(cmd)

try:
    jpg = sys.argv[1]
    out = sys.argv[2]
    ang = float(sys.argv[3])
except:
    print "Usage: python rotate_with_aspect.py input.jpg output.jpg angle"

fix_roll(jpg, ang, out)


Note: the aspect ratio is hardcoded to 3:2 (well, 3000:2000). You can change it as you wish.

If I've reinvented the wheel, please point me in the right direction ;)

maxotics

Very interesting!  Hope you don't mind if I pick your brain on a similar subject.

I've noticed that if I sharpen TIFFs in Faststone (or any image software I would think), and compile those images into a video it seems better than if I sharpen in Vegas Studio.  Right now, I'm sharpening in ffmpeg.  But I've wondered if imagemagick could do the sharpening better and perhaps do noise reduction, etc.  My problem is that there doesn't seem to be a good GUI to imagemagick where I could play with the image to my liking and then use those settings in batch. 

I'd like a process, using open-source/freeware if possible

1. Open TIFF in image editor,
2. Make improvement that fit my camera, lens, shooting style.
3. Use those settings in batch mode (right now I'm using VBscript + raw2dng, dcraw, ffmpeg).

Thanks in advance for your thought!