Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Calculate the minimal bounding box of a series of images.
#!/usr/bin/env python
"""Calculate the minimal bounding box of a series of images.
Example usage::
$ *.jpg
$ mogrify -crop 836x680+64+0 *.jpg
Requires the `identify` command which is part of ImageMagick.
from __future__ import print_function
import re
import subprocess
import sys
_bbox_match = re.compile(r'^(\d+)x(\d+)\+(\d+)\+(\d+)$').match
def bounding_box(fname):
"""Calculate the bounding box of a file."""
box = subprocess.check_output(['identify', '-format', '%@', fname])
w, h, x, y = map(int, _bbox_match(box).groups())
return w, h, x, y
def minimal_bounding_box(fnames):
"""Calculate the minimal bounding box of a sequence of files."""
x0 = []
y0 = []
x1 = []
y1 = []
for fname in fnames:
w, h, x, y = bounding_box(fname)
x0 = min(x0)
x1 = max(x1)
y0 = min(y0)
y1 = max(y1)
x = x0
w = x1-x0
y = y0
h = y1-y0
return w, h, x, y
if __name__ == "__main__":
if len(sys.argv) == 1:
print("Usage: %s <FILE...>" % sys.argv[0], file=sys.stderr)
w, h, x, y = minimal_bounding_box(sys.argv[1:])
print('%dx%d+%d+%d' % (w, h, x, y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment