Python中用于从图像中提取文本的8大OCR库
在Python中,有许多库可以用于从图像中提取文本,这些库通常被称为光学字符识别(OCR)工具。以下是其中的8个最常见的OCR库:
- Tesseract
- Google Vision
- Cuneiform
- Gnostic
- Pyocr
- Pytesseract
- Tesseract.js
- Tesseract OCR for iOS
解决方案和实例代码:
Tesseract
Tesseract是一个开源的OCR库,它可以通过多种语言进行训练,以识别不同语言的文本。它可以处理各种图像文件格式,包括jpg、png、gif、pdf和epdf。
from PIL import Image
import pytesseract
def ocr_image(image_path):
img = Image.open(image_path)
text = pytesseract.image_to_string(img)
return text
print(ocr_image('path_to_your_image.jpg'))
Google Vision
Google Vision API是一种云服务,可以分析图像,以识别其内容,包括人脸和地标。它还可以识别文本,并以编程方式提供对识别的文本的访问。
from google.cloud import vision
import io
def detect_text(path):
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
print('\nTexts:')
for text in texts:
print('\n"{}"'.format(text.description.strip()))
vertices = (['({},{})'.format(vertex.x, vertex.y) for vertex in text.bounding_poly.vertices])
print('bounds: {}'.format(','.join(vertices)))
detect_text('path_to_your_image.jpg')
Cuneiform
Cuneiform是一个开源OCR库,可以识别80多种语言的文本。它可以处理各种图像文件格式,包括jpg、png、gif、pdf和epdf。
from cuneiform import Cuneiform
def ocr_image(image_path):
cform = Cuneiform()
with open(image_path, 'rb') as image_file:
data = image_file.read()
return cform.convert_file(data)
print(ocr_image('path_to_your_image.jpg'))
Gnostic
Gnostic是一个用于处理图像和文本数据的Python库。它可以帮助开发者更容易地处理和分析从图像中提取的文本。
from gnostic import Image
def ocr_image(image_path):
with Image.open(image_path) as img:
text = img.text(clean=True, x_tolerance=10)
return text
print(ocr_image('path_to_your_image.jpg'))
Pyocr
Pyocr是Python的OCR工具。它可以用于在Python中读取扫描件。
import sys
import pyocr
import pyocr.builders
def ocr_image(image_path):
tools = pyocr.get_available_tools()
if len(tools) == 0:
print("No OCR tool found")
sys.exit(1)
tool = tools[0]
txt = tool.image_to_string(
pyocr.open_image(image_path),
lang='eng',
builder=pyocr.builders.TextBuilder()
)
r
评论已关闭