OCR pour Documents Scannés et Images
Extrayez le texte des PDF scannés et des images en utilisant Tesseract, AWS Textract et les techniques OCR modernes.
- Auteur
- Équipe de Recherche Ailog
- Date de publication
- Temps de lecture
- 9 min de lecture
- Niveau
- intermediate
- Étape du pipeline RAG
- Parsing
Quand l'OCR est nécessaire
Les PDF numériques ont du texte extractible. Les documents scannés non - ce ne sont que des images.
L'OCR convertit : • Contrats scannés • Livres anciens • Reçus • Captures d'écran • Notes manuscrites
Tesseract (Gratuit, Open-Source)
``python from PIL import Image import pytesseract
def ocr_image(image_path): image = Image.open(image_path) text = pytesseract.image_to_string(image, lang='eng') return text
Avec scores de confiance data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT) for i, word in enumerate(data['text']): confidence = data['conf'][i] if confidence > 60: Filtrer faible confiance print(word) `
Prétraitement pour meilleure précision
`python import cv2 import numpy as np
def preprocess_image(image_path): img = cv2.imread(image_path)
Convertir en niveaux de gris gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Supprimer le bruit denoised = cv2.fastNlMeansDenoising(gray)
Seuillage (binarisation) _, binary = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return binary
Utiliser l'image prétraitée preprocessed = preprocess_image('scan.jpg') text = pytesseract.image_to_string(preprocessed) `
AWS Textract (Commercial, Meilleure qualité)
`python import boto3
textract = boto3.client('textract', region_name='us-east-1')
def extract_with_textract(image_path): with open(image_path, 'rb') as f: image_bytes = f.read()
response = textract.detect_document_text( Document={'Bytes': image_bytes} )
text = "" for block in response['Blocks']: if block['BlockType'] == 'LINE': text += block['Text'] + '\n'
return text
Pour tableaux et formulaires response = textract.analyze_document( Document={'Bytes': image_bytes}, FeatureTypes=['TABLES', 'FORMS'] ) `
Google Cloud Vision
`python from google.cloud import vision
client = vision.ImageAnnotatorClient()
def ocr_with_google(image_path): with open(image_path, 'rb') as f: content = f.read()
image = vision.Image(content=content) response = client.document_text_detection(image=image)
return response.full_text_annotation.text `
Reconnaissance d'écriture manuscrite
`python EasyOCR pour l'écriture manuscrite import easyocr
reader = easyocr.Reader(['en']) result = reader.readtext('handwritten.jpg', detail=0) text = ' '.join(result) `
OCR multilingue
`python Tesseract avec plusieurs langues text = pytesseract.image_to_string( image, lang='eng+fra+deu' Anglais + Français + Allemand )
EasyOCR (meilleur pour les langues asiatiques) reader = easyocr.Reader(['en', 'zh', 'ja', 'ko']) results = reader.readtext('multilingual.jpg') ``
L'OCR ouvre le contenu scanné pour le RAG. Essentiel pour les documents juridiques, médicaux et historiques.