默认的tesseract库,只能识别字母和数字,不能识别中文
并且识别精度也不是很高,所以就得需要我们有更高手段,
大家可以参照 这篇文章
今天我们来说简单的
用python 的 pytesseract库
首先安装pytesseract库
pip install pytesseract -i xx镜像
导包
import pytesseract
此外我们还需要一个待识别图片code.png,以及读取图片的库pillow
安装pillow
pip install pillow
导包
try:
from PIL import Image
except ImportError:
import Image
读取图片并识别
captcha = Image.open("code3.png")
result = pytesseract.image_to_string(captcha)
print(result[:-2])
print(len(result))
这时候有可能报错,如果你没提前安装tesseract软件,这时候你需要下载tesseract并安装,并且添加环境变量,如果是用pycharm开发,需要**重启下pycharm,**因为pycharm一开始运行的时候,系统环境变量的参数就固定了
如果不行,网上有人说修改源代码的文件,例如这类
但是我不建议这么做,因为不重启pycharm的情况下,这样改了也没用,并且毕竟修改人家的源代码也不是最优雅的解决方式
我们可以通过添加临时路径来搞定这个事情
有两种方式,一种是os
import os
tesseract_path=r"F:\Program Files\Tesseract-OCR" # tesseract.exe所在的路径
os.environ["PATH"]= tesseract_path + ";" + os.environ["PATH"]
另一种通过 sys模块
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
add_path(tesseract_path)
接下来就一切ok了,只是识别结果不是让人很满意,
高级一点的操作套装为
灰度处理,二值化,去噪
直接看代码吧
# --------------------灰度处理--------------
captcha = Image.open("code.png")
result = captcha.convert('L') # 灰度处理
# result.show()
# result = pytesseract.image_to_string(captcha)
# ----------------------二值化------------------------------
def convert_img(img, threshold):
img = img.convert("L") # 处理灰度
pixels = img.load()
for x in range(img.width):
for y in range(img.height):
if pixels[x, y] > threshold:
pixels[x, y] = 255
else:
pixels[x, y] = 0
return img
result = convert_img(result, 150)
# -----------------降噪-----------
img = result
data = img.getdata()
w, h = img.size
count = 0
for x in range(1, h - 1):
for y in range(1, h - 1):
# 找出各个像素方向
mid_pixel = data[w * y + x]
if mid_pixel == 0:
top_pixel = data[w * (y - 1) + x]
left_pixel = data[w * y + (x - 1)]
down_pixel = data[w * (y + 1) + x]
right_pixel = data[w * y + (x + 1)]
if top_pixel == 0:
count += 1
if left_pixel == 0:
count += 1
if down_pixel == 0:
count += 1
if right_pixel == 0:
count += 1
if count > 4:
img.putpixel((x, y), 0)
img.show()
result = pytesseract.image_to_string(img)
print(result[:-2])
print(len(result))
在每一步操作完后,大家可以查看一下图片的处理结果,大概就能了解了
只是最终结果还是识别的不对而已o(╥﹏╥)o
我的测试图片长的样子
汉字默认是不能识别的
这个不能识别
这个识别没问题
这张是多次操作的图片,当然也没有能识别成功:
本文介绍了如何使用Python的pytesseract库进行OCR文字识别,包括安装库、处理图片以及解决tesseract软件环境变量问题。尽管识别精度有限,文章提供了灰度处理、二值化和去噪等提高识别效果的方法。
1万+

被折叠的 条评论
为什么被折叠?



