Skip to content

Instantly share code, notes, and snippets.

@stefanv
Created December 4, 2019 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanv/add7b27742b4fc83e58147a2a86a6746 to your computer and use it in GitHub Desktop.
Save stefanv/add7b27742b4fc83e58147a2a86a6746 to your computer and use it in GitHub Desktop.
Auto-crop jpeg image without recompressing (requires Python 3 with scikit-image, and jpegtran)
#!/usr/bin/env python
import subprocess
import sys
from skimage import io, filters
import numpy as np
filename = sys.argv[1]
base, ext = filename.rsplit('.', 1)
outfile = f'{base} cropped.{ext}'
if not (filename.endswith('.jpg') or filename.endswith('.jpeg')):
print("Can only losslessly crop JPEG images")
image = io.imread(filename).sum(axis=2)
coords = np.array(np.nonzero(image != image.max())).T
top_left = coords.min(axis=0)
bottom_right = coords.max(axis=0)
height = bottom_right[0] - top_left[0]
width = bottom_right[1] - top_left[1]
y, x = top_left
subprocess.run([
'jpegtran', '-outfile', outfile,
'-crop', f'{width}x{height}+{x}+{y}',
filename
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment