1.使用tesseract-ocr
最早由HP公司研发的一个开源文字识别项目,项目地址为:https://github.com/tesseract-ocr/tesseract/wiki
①本次在win7_64位系统上安装,可使用以下链接:
主程序:
https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-setup-4.0.0-alpha.20180109.exe
语言包:
https://github.com/tesseract-ocr/tessdata/blob/master/chi_sim.traineddata
若更新,可参照下列图片找到链接:

②下载完主程序和语言包后,直接点击安装,全程默认下一步即可。安装完成后,将安装地址加入系统路径,默认安装地址为:C:\Program Files (x86)\Tesseract-OCR;
③打开CMD命令,然后输入tesseract -v
,如果显示版本号,则主程序安装完成。

④将语言包放在以下文件夹中:
C:\Program Files (x86)\Tesseract-OCR\tessdata
⑤新建系统变量:
变量名是TESSDATA_PREFIX
,变量值是C:\Program Files (x86)\Tesseract-OCR\tessdata;

变量生效可能需要重启,想快速搞定,可以直接输入SET TESSDATA_PREFIX=C:\Program Files (x86)\Tesseract-OCR\tessdata
⑥设置完成,可以找个范例试试,这里讲需要识别的内容设置为123.jpg,放在C:\Program Files (x86)\Tesseract-OCR
处,并打开cmd命令,输入:
tesseract.exe 123.jpg 1 -l chi_sim

若出现上述截图,运行成功,可以看到文件夹下生成了一个1.txt文件,记载着识别效果。


总的来说,数字和英文识别率较高,但是中文的识别率较低。
⑦接下来安装pytesseract,依赖于PIL或Pillow。


安装好后就可以试验一下了:
from PIL import Image
import pytesseract
img = Image.open('code2.png') #打开图片,目前图片放在与tesseract同样的目录下
img = img.convert('L') #使用convert方法转换成灰度图像,识别率更高。也可以省略
print(pytesseract.image_to_string(img)) #转换成字符串输出
img.show() #可以把处理后的图片显示出来


⑧结果嘛,最后一个5被识别成“S”,其他都还是正确的。
那是否没有办法了呢?或许我们可以试试二值化处理。
from PIL import Image
import pytesseract
img = Image.open(r'C:\Program Files (x86)\Tesseract-OCR\code2.png')
img = img.convert('L')
#img.show()
print(pytesseract.image_to_string(img))
#二值化处理
threshold = 150 #定义临界值
table = []
for i in range(256):
if i < threshold:
table.append(0) #小于临界值的,都定义为0
else:
table.append(1) #大于临界值的,都定义为1
out = img.point(table,"1") #图像模式为"L"时,point方法对应的第二个参数设为”1“。第一个参数table被规定为一个拥有256个值的列表。
out.show()
print(pytesseract.image_to_string(out))
结果竟然成功了。


不过,Tesseract仅对容易区分、没有干扰的取现或字符有较好效果,复杂情况下的识别率还有待提高。
网友评论