tesseract代码识别图片
一、安装库:
在python代码中操作tesserect。需要安装一个库,叫做pytesseract。通过pip的方式安装:
pip install pytesseract
并且读取图片,需要供助一个第三方库叫做PIL。通过pip list看下是否安装。如果没有安装,通过pip的方式安装:
pip install PIL
二、使用示例
使用pytesseract将图片上的文字转换为文本文字的示例代码如下:
1、识别英文
# encoding: utf-8
# 导入pytesseract库
import pytesseract
# 导入Image库
from PIL import Image
# 确定tesseract.exe所在的路径
pytesseract.pytesseract.tesseract_cmd = r"p:\ProgramApp\TesseractOCR\tesseract.exe"
# 打开图片
image = Image.opon('a. png')
# 调用image_to_string将图片转为文字
text = pytesseract.image_to_string(image)
print(text)
2、识别中文
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r"p:\ProgramApp\TesseractOCR\tesseract.exe"
image = Image.opon('c. png')
text = pytesseract.image_to_string(image, lang='chi_sim')
print(text)
三、实例
用pytesseract处理拉勾网图形验证码。
import pytesseract
from pytesseract import request
from PIL import Image
import time
def main():
pytesseract.pytesseract.tesseract_cmd = r'D:\ProgramApp\TesseractOCR\tesseract.exe'
url = '验证码的网址链接'
while True:
request.urlretrieve(url, 'captcha.png')
image = Image.open('captcha.png')
text = pytesseract.image_to_string(image)
print(text)
time.sleep(2)
if __name__ == "__main__":
main()