准备工作:
1.使用国内源安装库pytesseract
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pytesseract
2.安装tesseract
自己下载安装包吧
from PIL import Image
import pytesseract
import os
def get_all_path():
start = r"E:\hhh\soft\中国知网验证码"
lis = os.listdir(start)
path = [start+os.sep+name for name in lis]
return path
def get_ma(path):
image = Image.open(path)
text = pytesseract.image_to_string(image)
return text
def open_code():
num = 0
all_path = get_all_path()
for path in all_path:
right = path.split("\\")[-1].replace(".jpg", "")
ma = get_ma(path)
if(right == ma):
print("正确为:{},机器识别为:{},结果正确".format(right, ma))
num += 1
else:
print("正确为:{},机器识别为:{},结果错误".format(right, ma))
print("最终成功率为%.4f" % (num/len(all_path)))
open_code()
设置阈值,转灰度图像,二值化
from PIL import Image
import pytesseract
import os
def get_all_path():
start = r"E:\hhh\soft\中国知网验证码"
lis = os.listdir(start)
path = [start+os.sep+name for name in lis]
return path
def set_threshold():
threshold = 127 #阈值
table=[]
for i in range(256):
if i<threshold:
table.append(0)
else:
table.append(1)
return table
def get_ma2(path):
image = Image.open(path)
image = image.convert("L") # 转换为灰度图像
table = set_threshold()
newImage = image.point(table,'1') #二值化
text = pytesseract.image_to_string(newImage)
return text
def open_code2():
num = 0
all_path = get_all_path()
for path in all_path:
right = path.split("\\")[-1].replace(".jpg", "")
ma = get_ma2(path)
if(right == ma):
print("正确为:{},机器识别为:{},结果正确".format(right, ma))
num += 1
else:
print("正确为:{},机器识别为:{},结果错误".format(right, ma))
print("最终成功率为%.4f" % (num/len(all_path)))
open_code2()