OCR 识别案例
注意点:输入图像尺寸比例尽量和参与模型训练的数据集比例相似,识别效果会更好。
1、pytesseract
Pytesseract是一个Python的光学字符识别(OCR)工具,它作为Tesseract OCR引擎的封装,允许你在Python程序中直接使用Tesseract的功能。通过Pytesseract,你可以从图像文件中提取文本数据。这使得它成为处理需要从图片、截图或其他图像格式中读取文字信息任务的理想选择。
通常情况下,Pytesseract会与Pillow库一起使用,后者用于图像处理。这样组合使用可以先对图像进行必要的预处理(如转换为灰度图、二值化等),然后利用Pytesseract识别图像中的文字内容。
要使用Pytesseract,你需要首先安装Tesseract OCR引擎以及pytesseract包。可以通过pip命令pip install pytesseract
来安装Pytesseract。同时,别忘了从Tesseract的GitHub页面下载并安装Tesseract OCR引擎,并确保其正确配置在系统的环境变量中,以便pytesseract能够调用它。
sudo apt-get update
sudo apt install tesseract-ocr
from PIL import Image
import pytesseract
# 如果没有将Tesseract加入系统路径,需要指定完整路径
# linux 安装 sudo apt install
# pytesseract.pytesseract.tesseract_cmd = r'path_to_tesseract.exe'
image = Image.open('image_containing_digits.png')
text = pytesseract.image_to_string(image, config='--psm 6 digits')
dict = pytesseract.image_to_data(large_matrix, output_type=Output.DICT)
print(text)
print(dict)
2、EasyOCR
EasyOCR 是一个易于使用且功能强大的光学字符识别(OCR)Python 库,能够从图像中提取文本。它由微軟亞洲研究院(MSRA)开源,支持超过80种语言的识别,包括但不限于中文、英文、日文、韩文等。EasyOCR 的主要优点是它的易用性和高性能,即使在处理复杂背景或低质量图像时也能提供良好的识别准确率。
使用 EasyOCR 进行文字识别非常简单,只需要几行代码即可完成。首先,你需要通过 pip 安装 EasyOCR 库:
pip install easyocr
import easyocr
# ocr model path: ~/.EasyOCR/model
easyocr_tool = easyocr.Reader(['en']) # 'en'代表英文,'ch_sim'代表简体中文
# # 手动指定模型
# reader = easyocr.Reader(['en'], model_storage_directory='/path/to/your/custom/model')
img_path = 'ocr_recognition.jpg'
img = cv2.imread(img_path)
result = easyocr_tool.readtext(img)
import easyocr
reader = easyocr.Reader(['en']) # 初始化时指定语言
result = reader.readtext('image_containing_digits.png')
for (bbox, text, prob) in result:
print(f"文本: {text}, 置信度: {prob}")
3、ModelScope
modelscope项目地址
pip install modelscope
pip install modelscope[cv] -f https://modelscope.oss-cn-beijing.aliyuncs.com/releases/repo.html
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
import cv2
ocr_recognition = pipeline(Tasks.ocr_recognition, model='iic/cv_convnextTiny_ocr-recognition-general_damo')
### 使用url
img_url = 'http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/mass_img_tmp_20220922/ocr_recognition.jpg'
result = ocr_recognition(img_url)
print(result)
### 使用图像文件
### 请准备好名为'ocr_recognition.jpg'的图像文件
# img_path = 'ocr_recognition.jpg'
# img = cv2.imread(img_path)
# result = ocr_recognition(img)
# print(result)
# # result 格式是字典形式,{'text':['001']}