ubuntu图片文字识别
仅限个人学习所用
第一次用博客写东西,有点不习惯,如果我的代码存在什么错误,欢迎留言,互相探讨。
安装我不详细讲,只说我踩的坑
1.安装完pillow-> tesseract -> pytesseract 后,一定要记得下载自己需要的需要包
2.tesseract自带有一个"eng"的包,如果需要转中文,可以到"https://github.com/tesseract-ocr/tessdata" [上述地址为转载地址]进行下载,我自己下了一个"chi_sim_vert.traineddata"转中文的训练包
3.打开终端,cd到你下载的文件下,将该文件移动到"/usr/share/tesseract-ocr/4.00/tessdata"文件夹下,命令 : “sudo mv aze.traineddata /usr/share/tesseract-ocr/4.00/tessdata”
看源码
from PIL import Image
import pytesseract
class CharaterRecognition(object):
def __init__(self, image_file, threshold=127):
self.img = image_file
print(self.img)
self.threshold = threshold
# 二值化图像
def _erzhihua(self):
# 读取图片
img = Image.open(self.img)
# 二值化处理[非黑即白]
image = img.convert('L')
# 进行二分定值[转化为两种结果:0/1]
table = []
for i in range(256):
if i < self.threshold:
table.append(0)
else:
table.append(1)
return image.point(table, '1')
# 图片文字获取
def get_character(self):
"""
返回图片识别出的文字
:return:
"""
result_img = CharaterRecognition._erzhihua(self)
# 图片展示
result_img.show()
# 图片内容
content = ''
try:
# 识别图片,获取文字
# print("开始识别图片",'测试调节用!!!')
content = pytesseract.image_to_string(result_img, lang='chi_sim')
except Exception as e:
print("传入格式不对,或者传入的不是图片")
return content
cha = CharaterRecognition(‘c1.jpg’)
text = cha.get_character()
print(text)