forked from hastagAB/Awesome-Python-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature.py
90 lines (65 loc) · 2.24 KB
/
signature.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
# ===============================================================
# Author: Rodolfo Ferro Pérez
# Email: [email protected]
# Twitter: @FerroRodolfo
#
# Script: Process signatures to remove background.
#
# ABOUT COPYING OR USING PARTIAL INFORMATION:
# This script was originally created by Rodolfo Ferro. Any
# explicit usage of this script or its contents is granted
# according to the license provided and its conditions.
# ===============================================================
from PIL import Image, ImageOps
import argparse
inFile = ''
outFile = ''
def binarize(img, threshold=127):
"""Utility function to binarize an image."""
for i in range(img.size[0]):
for j in range(img.size[1]):
if img.getpixel((i, j)) > threshold:
img.putpixel((i, j), 255)
else:
img.putpixel((i, j), 0)
return img
def make_transparent(img):
"""Utility function to make transparent background from image."""
img = img.convert("RGBA")
data = img.getdata()
transparent = []
for item in data:
if item[:3] == (255, 255, 255):
transparent.append((255, 255, 255, 0))
else:
transparent.append(item)
img.putdata(transparent)
return img
def main(inFile, outFile, threshold=190):
"""Main function to process image."""
img = Image.open(inFile).convert('L')
img = binarize(img, threshold=threshold)
img = make_transparent(img)
img.save(outFile)
return True
def parser():
"""Argument parser function."""
# Construct the argument parser:
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input",
required=True,
type=str,
default="result.png",
help="Input image.")
ap.add_argument("-o", "--output",
type=str,
default="result.png",
help="Output image.")
ap.add_argument("-th", "--threshold",
type=int,
default=127)
args = vars(ap.parse_args())
return args['input'], args['output'], args['threshold']
if __name__ == "__main__":
inFile, outFile, threshold = parser()
main(inFile, outFile, threshold=threshold)