Skip to content

Instantly share code, notes, and snippets.

Embed
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::
$ find_bounding_box.py *.jpg
836x680+64+0
$ 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.append(x)
y0.append(y)
x1.append(w+x)
y1.append(h+y)
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)
sys.exit(1)
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
You can’t perform that action at this time.