Created
December 4, 2019 23:54
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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