-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocrop.py
executable file
·176 lines (151 loc) · 5.83 KB
/
autocrop.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/python2
# -*- coding: utf-8 -*-
from collections import defaultdict
from PIL import Image
from PIL import ImageChops
from PIL import ImageFilter
from utils import makeSrcDst, imageFilter
def getBackgroundColor(im, edge=None):
if edge is None:
edge = 5
width, height = im.size
left = im.crop((0, edge, edge, height - edge))
right = im.crop((width - edge, edge, width, height - edge))
top = im.crop((0, 0, width, edge))
bottom = im.crop((0, height - edge, width, height))
colors = defaultdict(lambda: 0)
for img in (left, right, top, bottom):
w, h = img.size
for i in range(w):
for j in range(h):
c = img.getpixel((i, j))
colors[c] += 1
colors_reversed = [(count, color) for (color, count) in colors.items()]
background_color = max(colors_reversed)[1]
return background_color
def clearPixels(im, width_range, height_range, c=0):
for i in range(*width_range):
for j in range(*height_range):
im.putpixel((i, j), c)
return im
def getbbox(im, max_error=0.01, threshold=15, suppress=30, max_edge_per=0.1, ratio=''):
im = im.filter(ImageFilter.GaussianBlur())
im = im.filter(ImageFilter.FIND_EDGES)
im = im.filter(ImageFilter.MedianFilter(3))
# im.show()
width, height = im.size
continue_failed = 0
left_edge = int(height * max_edge_per)
right_edge = height - 1 - int(height * max_edge_per)
top_edge = int(width * max_edge_per)
bottom_edge = width - 1 - int(width * max_edge_per)
edges = []
for start, end, step in (
(0, left_edge, 1),
(height - 1, right_edge, -1),
):
continue_failed = 0
for i in range(start, end, step):
count = 0
for j in range(width):
c = im.getpixel((j, i))
if c <= threshold:
count += 1
error = 1.0 - 1.0 * count / width
if error >= max_error:
if continue_failed >= suppress:
break
continue_failed += 1
else:
continue_failed = 0
t = i - continue_failed * step
edges.append(t)
im = clearPixels(im, (0, width), (start, t, step))
for start, end, step in (
(0, top_edge, 1),
(width - 1, bottom_edge, -1),
):
continue_failed = 0
for i in range(start, end, step):
count = 0
for j in range(height):
c = im.getpixel((i, j))
if c <= threshold:
count += 1
error = 1.0 - 1.0 * count / height
if error >= max_error:
if continue_failed >= suppress:
break
continue_failed += 1
else:
continue_failed = 0
t = i - continue_failed * step
edges.append(t)
im = clearPixels(im, (start, t, step), (0, height))
top, bottom, left, right = edges
if ratio:
w, h = map(int, ratio.split('x'))
w_cut, h_cut = right - left, bottom - top
if w_cut * h > w * h_cut:
h_dst = min(int(round(1.0 * w_cut * h / w)), height)
delta = h_dst - h_cut
cut = min(top, delta // 2)
top -= cut
bottom += min(delta - cut, height - bottom)
else:
w_dst = min(int(round(1.0 * h_cut * w / h)), width)
delta = w_dst - w_cut
cut = min(left, delta // 2)
left -= cut
right += min(delta - cut, width - right)
return (left, top, right, bottom)
def autoCrop(image, **options):
gray = image.convert('L')
background_color = getBackgroundColor(gray, options.get('edge', None))
if 'edge' in options:
del options['edge']
bg = Image.new("L", gray.size, background_color)
diff = ImageChops.difference(gray, bg)
bbox = getbbox(diff, **options)
# print(image.size, bbox)
image = image.crop(bbox)
return image
def main(source, destination, **options):
show = options['show'] or destination == '-'
edge = options['edge']
del options['show']
for source, destination in makeSrcDst(source, destination,
src_filter=imageFilter,
ignore_dst='-'):
im = Image.open(source)
im.load()
im = autoCrop(im, **options)
if show:
im.show()
if destination != '-':
im.save(destination)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Auto detect white space and crop image')
parser.add_argument('source', type=str, # nargs='+',
help='input image file/directory')
parser.add_argument('destination', type=str,
help='output image file/directory')
parser.add_argument('--edge', type=int, default=5,
help='get background color from edge')
parser.add_argument('--threshold', type=int, default=15,
help='color diff threshold')
parser.add_argument('--suppress', type=int, default=30,
help='error suppress counter')
parser.add_argument('--max-error', type=float, default=0.01,
help='error detect sensitivity')
parser.add_argument('--ratio', type=str, default='',
help='target screen ratio, eg.: 758x1024')
parser.add_argument('--max-edge-per', type=float, default=0.1,
help='max ratio for page cut')
parser.add_argument('-s', '--show', action='store_true',
help='show output')
args = parser.parse_args()
main(**vars(args))