关于python ocr的安装和使用

关于python ocr的安装和使用
一、安装

1,首先安装Python类库

安装支持Python版本的Tesseract库:安装方式如下:

pip install pytesseract

2,安装ORC库-Tesseract

Tesseract是Python进行图像处理的库,该引擎最初由惠普公司开发,目前由Google主导。

下载网址https://code.google.com/p/tesseract-ocr/downloads/list

3,设置环境变量。

需要添加俩个环境变量

1,path中添加C:\ProgramFiles(x86)\Tesseract-OCR(安装路径)

2,新建一个TESSDATA_PREFIX变量C:\ProgramFiles(x86)\Tesseract-OCR\Tesseract

3,在pytesseract源码中将tesseract_cmd修改为:

tesseract_cmd=r’C:\ProgramFiles(x86)\Tesseract-OCR\tesseract.exe’
二、使用。

(一)简单使用

1,先导包

import pytesseract
from PIL import Image
2,输出验证码
image=Image.open('./images/tesseracttest.jpg')
text=pytesseract.image_to_string(image)
print(text)

(二)复杂使用

importpytesseract
fromPILimportImage
img=Image.open('./images/recaptcha.png')
img.show()
gray=img.convert('L')  # 灰度化
gray.show()
bw = gray.point(lambda x: 0 if x < 1 else 255,'1')
bw.show()
print(pytesseract.image_to_string(bw))

(三)网页中的具体使用

分析:首先,你要定位到页面中验证码的位置,

然后,将图片灰度化处理(提高OCR识别的精度)

最后,pytesseract.image_to_string()出图片

参考代码:

from selenium import webdriver
import pytesseract
from PIL import Image
import time
browser=webdriver.Chrome()
url=URL
browser.get(url)
html=browser.page_source
print(html)
browser.save_screenshot('./images/1.png')
img=browser.find_element_by_id('checkcode')
left=img.location['x']  # 验证码图片左上角横坐标
top=img.location['y']  # 验证码图片左上角纵坐标
right=left+img.size['width']  # 验证码图片右下角横坐标
bottom=top+img.size['height']  # 验证码图片右下角纵坐标
im=Image.open('./images/1.png')
im_crop=im.crop((left,top,right,bottom))  # 这个im_crop就是从整个页面截图中再截出来的验
证码的图片
im_crop.save('./images/2.png')
img=Image.open('./images/2.png')
img.show()
gray=img.convert('L')  #  灰度化,图片转化成灰度图
gray.show()

二值化

threshold=155
table=[]
foriinrange(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)
bw = gray.point(table,'1')
bw.show()
strcode = pytesseract.image_to_string(bw)
print(strcode)
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值