-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcaptcha.py
61 lines (45 loc) · 1.66 KB
/
captcha.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
# coding=gbk
import os
import shutil
from PIL import Image
import subprocess
captcha_folder = os.path.abspath('.') + '\\captcha\\'
def preprocess(src_file, dst_file):
im = Image.open(captcha_folder + src_file)
imgry = im.convert('L')
threshold = 140
table = []
for i in range(256):
if i < threshold:
table.append(1)
else:
table.append(0)
out = imgry.point(table, '1')
width, height = out.size
print "the captcha image size = (%d, %d)" % (width, height)
out = out.crop((2, 2, width - 2, height - 2))
out.save(captcha_folder + dst_file)
print "preprocess completed, output = " + captcha_folder + dst_file
def solve(filename):
p = subprocess.Popen(['C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe', captcha_folder + filename, captcha_folder + 'result'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1)
print "**********************************************"
print p.stdout.readline(),
fp = open(captcha_folder + 'result.txt', 'r')
result = fp.read()
result = result.replace(' ', '')
result = result.rstrip('\n')
if result != '':
print "OCR result = <" + result + ">"
else:
print "OCR failed, result = <NULL>"
return result
def do_delete():
if os.path.exists(captcha_folder):
print "delete folder = " + captcha_folder.decode('gbk')
shutil.rmtree(captcha_folder)
else:
print "folder doesn't exist, no need to delete, folder = " + captcha_folder.decode('gbk')
if __name__ == '__main__':
preprocess('verifycode2.jpg', 'verifycode2_output.jpg')
solve('verifycode2_output.jpg')
# do_delete()