8个最强大的OCR工具与服务
我探索了各种 OCR 工具和服务,并根据它们的特点(例如价格、准确性和实施工作量)将它们分为三个不同的类别:生成式AI、视觉AI和开源库。

在快节奏的 IT 世界中,光学字符识别 (OCR) 已成为从图像中提取文本的不可或缺的工具。但是,当这些图像质量低下、模糊或不完美时会发生什么?这正是我在当前工作中面临的挑战,它促使我深入研究 OCR 工具和服务的世界以寻找解决方案。
我探索了各种 OCR 工具和服务,并根据它们的特点(例如价格、准确性和实施工作量)将它们分为三个不同的类别:
- 生成式AI:在这里,我研究了 Gemini 和 OpenAI 等尖端解决方案,它们利用生成模型的强大功能来解决复杂的 OCR 任务。
- 视觉 AI:此类别专注于专门的计算机视觉服务,旨在精确处理基于图像的挑战并从图像中提取特征。
- 开源库:对于那些希望构建内部解决方案的人,我评估了可用的最佳开源工具,平衡了灵活性和控制力。
在整个研究过程中,我针对一组低质量图像测试了这些工具,以评估它们在实际场景中的表现。我强烈建议你创建图像数据集,以确保它最能满足你的特定需求和目标。
如果你对详细信息感到好奇,可以在此处找到用于本研究的完整代码。我用来测试解决方案的图像可在此处获得,基准测试代码可在此处访问。
1、OpenAI - 生成式AI
在我探索 OCR 工具的过程中,一种有趣的方法是利用 ChatGPT 和定制提示从图像中提取文本。
from openai import OpenAI # pip install openai
from base64 import b64encode
# Generate APIKey https://platform.openai.com/api-keys
OPENAI_API_KEY = ""
image_path = "image.jpg"
with open(image_path, "rb") as image_file:
base64_image = b64encode(image_file.read()).decode("utf-8")
client = OpenAI(api_key=OPENAI_API_KEY)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "OCR this image. Do not include any markdown or code formatting.",
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
},
},
],
}
],
)
print(response.choices[0].message.content)
许多 OpenAI 模型现在都具有视觉功能,允许它们将图像作为输入进行处理并回答有关它们的问题。
2、Gemini - 生成式AI
Gemini 的多模态功能使其能够处理视觉数据以及上下文提示,使其对于具有挑战性的 OCR 任务特别有效。
from PIL import Image # pip install Pillow
import google.generativeai as genai # pip install google.generativeai
# Generate APIkey - https://aistudio.google.com/apikey
GEMINI_API_KEY = ""
image_path = "image.jpg" # Put here your image path
model_name="gemini-1.5-flash"
genai.configure(api_key=GEMINI_API_KEY)
image_file = Image.open(image_path)
model = genai.GenerativeModel(model_name=model_name)
prompt = "OCR this image. Do not include any markdown or code formatting."
response = model.generate_content([prompt, image_file])
print(response.text)
通过制作有针对性的提示,例如指定语言、布局,甚至是内容的预期结构。
3、Google Cloud - Vision AI
Google Cloud Vision AI 是一款强大的 OCR 任务工具,尤其是在处理低质量图像时。其文本检测功能旨在应对各种挑战,从倾斜角度到不同的光照条件。
import os
from google.cloud import vision # pip install google-cloud-vision
# Put here your credentials json file
# https://developers.google.com/workspace/guides/create-credentials?hl=en
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = ""
client = vision.ImageAnnotatorClient()
with open("image.jpg", "rb") as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.text_detection(image=image)
for annotation in response.text_annotations:
print("Detected Text:", annotation.description)
凭借其先进的机器学习模型,Vision AI 可以准确地从照片、扫描文档甚至杂乱的产品包装中识别和提取文本。
4、Azure - Vision AI
Azure Vision AI 是一款功能强大的工具,可用于从图像中提取文本,提供强大的 OCR 功能,可处理各种场景。
# pip install azure-ai-vision-imageanalysis
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
from azure.core.credentials import AzureKeyCredential
# Generate APIkey - https://azure.microsoft.com/en-us/products/ai-services/ai-vision
AZURE_VISION_API_KEY = ""
image_path = "image.jpg"
with open(image_path, "rb") as f:
image_data = f.read()
# You need to create an Azure Computer Vision AI services
# https://portal.azure.com/
region = "eastus"
endpoint = "https://<instance name>.cognitiveservices.azure.com/"
client = ImageAnalysisClient(
endpoint=endpoint,
credential=AzureKeyCredential(AZURE_VISION_API_KEY),
region=region,
)
response = client.analyze(
image_data,
visual_features=[VisualFeatures.READ],
)
if response.read is not None:
for line in response.read.blocks[0].lines:
print("Detected Text:", line.text)
其先进的算法可以处理不同质量水平的图像,从清晰、光线充足的照片到低质量、嘈杂的输入。
5、Tesseract - 开源库
Tesseract 是一个强大且多功能的选项,它是免费的开源库,可供个人和商业使用。获得更好结果的关键是预处理,例如二值化(转换为黑白)、降噪和对比度调整可以显著改善 OCR 结果。
import pytesseract # pip install pytesseract
import cv2 # pip install opencv-contrib-python
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply dinarization converting the image to black-and-white.
_, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Tesseract allows you to specify the language of the text and configure settings
# like page segmentation mode (PSM). For low-quality images,
# using --psm 6 (assume a single uniform block of text)
# or --psm 11 (sparse text) can yield better results.
config = "-l por --oem 1 --psm 11"
text = pytesseract.image_to_string(image, config=config)
print(text)
虽然 Tesseract 功能强大,但并不完美。它可能难以处理高度扭曲的文本或复杂的布局。在这种情况下,将 Tesseract 与其他预处理技术甚至自定义训练相结合可以帮助弥补差距。
6、EasyOCR - 开源库
在从低质量图像中提取文本方面,EasyOCR 是一款功能强大、既易于访问又有效的开源工具。EasyOCR 基于 PyTorch 构建,支持 80 多种语言,旨在处理具有挑战性的现实场景,包括模糊、倾斜或嘈杂的图像。
import easyocr # !pip install easyocr
reader = easyocr.Reader(['pt'])
results = reader.readtext('image.jpg')
for (bbox, text, confidence) in results:
print(f"Detected text: {text} (Confidence: {confidence:.2f})")
EasyOCR 带有预先训练的模型,可立即使用,非常适合快速部署且准确度高。
7、Surya - 开源库
得益于其先进的预处理技术,Surya OCR 在处理嘈杂、扭曲或低分辨率图像方面表现出色。
from PIL import Image # pip install Pillow
# pip install surya-ocr
from surya.recognition import RecognitionPredictor
from surya.detection import DetectionPredictor
image_path = "image.jpg"
image = Image.open(image_path)
langs = ["pt"]
recognition_predictor = RecognitionPredictor()
detection_predictor = DetectionPredictor()
predictions = recognition_predictor([image], [langs], detection_predictor)
for prediction in predictions:
for line in prediction.text_lines:
print(line.text)
它支持多种语言和脚本,使其适用于各种用例。Surya 利用先进的机器学习模型准确识别和提取文本,即使在次优条件下也是如此。
8、DocTR - 开源库
在从低质量图像中提取文本方面,DocTR(文档文本识别)脱颖而出,成为强大的开源解决方案。DocTR 建立在 TensorFlow 和 PyTorch 等深度学习框架之上,在文档理解任务中提供最先进的性能。它配备了预训练模型,能够识别多种语言和不同图像条件下的文本。
from doctr.io import DocumentFile # !pip install "python-doctr[torch]"
from doctr.models import ocr_predictor
images_path = "image.jpg"
doc = DocumentFile.from_images(images_path)
model = ocr_predictor(det_arch="db_resnet50", reco_arch="crnn_vgg16_bn", pretrained=True)
result = model(doc)
for page in result.pages:
for block in page.blocks:
for line in block.lines:
texts = [word.value for word in line.words]
print(texts)
DocTR 的独特之处在于其两步流程:
- 文本检测:它首先识别图像中的文本区域,即使在复杂的布局中也是如此。
- 文本识别:然后利用在不同数据集上训练的深度学习模型,解读这些区域内的文本。
这种双重方法确保了强大的性能,特别是对于低质量图像,传统的传统的 OCR 工具经常会遇到困难。
8、结束语
我使用各种 OCR 工具和服务的经历既有启发性又很实用,让我深入了解了不同方法的优势和局限性。
我的数据集包括产品包装的照片,具有多个文本方向、不同的字体和颜色,这带来了挑战。
Google Cloud 和 Azure 的 Vision AI 服务在从低质量图像中提取文本方面表现出色。这些是解决这个问题的最佳工具。
Gemini 在处理复杂的 OCR 任务方面表现出色。这些工具与精心制作的提示搭配使用时特别有效。
在开源方面,DocTR 提供了最好的结果,对于那些愿意投入时间的人来说,这类工具可能是一种经济高效且用途广泛的替代方案。
这些结果基于我的数据集;但是,不同的数据集可能会产生不同的结果,尤其是在开源工具方面。
对于那些有兴趣进一步探索的人,完整的代码、一些测试图像和基准测试细节可以在这个 GitHub 存储库中查看。
原文链接:OCR Tools — My Latest Study: Solving Real-World Problems with Low-Quality Images
汇智网翻译整理,转载请标明出处