-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocrop
executable file
·44 lines (33 loc) · 1.32 KB
/
autocrop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python3
import argparse
from PIL import Image, ImageColor
helpmsg = "Automatically crop border from image"
parser = argparse.ArgumentParser(description=helpmsg)
parser.add_argument('--color', '-c', type=ImageColor.getrgb,
default=[255]*3, help="color to remove around subject")
parser.add_argument('--verbose', '-v', action='store_true')
parser.add_argument('filename', nargs='+', help="Images to crop")
args = parser.parse_args()
import numpy as np
import os
color3 = np.array(args.color, dtype=np.uint8)
for filename in args.filename:
im = Image.open(filename)
im = im.convert(mode='RGB')
pixels = np.asarray(im)
imshape = pixels.shape[:2]
subject = (pixels != color3).all(axis=-1)
left = subject.any(axis=0).argmax()
up = subject.any(axis=1).argmax()
subject = np.flip(subject) # flips all axes
right = imshape[1] - subject.any(axis=0).argmax()
down = imshape[0] - subject.any(axis=1).argmax()
if args.verbose:
print(f'upper left corner: {left}, {up}')
print(f'lower right corner: {right}, {down}')
print(f'image dims (HxW): {down-up} x {right-left}')
pixels = pixels[up:down,left:right,:]
im = Image.fromarray(pixels, mode="RGB")
basename = os.path.splitext(filename)[0]
outname = basename + '_cropped.png'
im.save(outname)