Вот скрипт Python, который использует библиотеку Tesseract для извлечения текста из изображения с именем «images.png» в том же каталоге, что и скрипт:
import pytesseract
from PIL import Image
# Open the image
image_path = "images.png"
image = Image.open(image_path)
# Extract text using Tesseract
extracted_text = pytesseract.image_to_string(image, lang='eng')
# Print the extracted text
print(extracted_text)
Этот скрипт использует библиотеку pytesseract
, которая представляет собой оболочку Python для механизма OCR Tesseract. Перед запуском сценария вам необходимо установить библиотеку и механизм OCR Tesseract в вашей системе. Вы можете установить pytesseract
с помощью pip:
pip install pytesseract
И вам также потребуется установить механизм оптического распознавания символов Tesseract. Инструкции по установке для различных операционных систем вы можете найти здесь: https://github.com/tesseract-ocr/tesseract/wiki .
Теперь перейдем к написанию статьи в блоге. Вот несколько методов извлечения текста из изображения с использованием разных библиотек и техник:
-
Питессеракт:
import pytesseract from PIL import Image # Open the image image_path = "images.png" image = Image.open(image_path) # Extract text using Tesseract extracted_text = pytesseract.image_to_string(image, lang='eng') # Print the extracted text print(extracted_text)
-
OpenCV с Tesseract:
import cv2 import pytesseract # Load the image image_path = "images.png" image = cv2.imread(image_path) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply image preprocessing (e.g., thresholding, noise removal) using OpenCV # Extract text using Tesseract extracted_text = pytesseract.image_to_string(gray, lang='eng') # Print the extracted text print(extracted_text)
-
API Google Cloud Vision:
from google.cloud import vision # Authenticate with Google Cloud Vision API # Load the image image_path = "images.png" with open(image_path, 'rb') as image_file: content = image_file.read() # Create a client client = vision.ImageAnnotatorClient() # Create an image object image = vision.Image(content=content) # Perform text detection response = client.text_detection(image=image) texts = response.text_annotations # Extract the first block of text (assuming it contains the main content) extracted_text = texts[0].description # Print the extracted text print(extracted_text)
-
API OCR.space:
import requests # Set up the OCR.space API endpoint api_key = 'YOUR_API_KEY' api_url = 'https://api.ocr.space/parse/image' # Load the image image_path = "images.png" image_file = open(image_path, 'rb') # Make the API request response = requests.post(api_url, files={'image': image_file}, data={'apikey': api_key}) # Parse the response result = response.json() extracted_text = result['ParsedResults'][0]['ParsedText'] # Print the extracted text print(extracted_text)
Это всего лишь несколько примеров методов извлечения текста из изображения. В зависимости от ваших требований и особенностей изображений вам может потребоваться поэкспериментировать с разными подходами для достижения наилучших результатов.
Не забудьте выбрать теги, которые соответствуют содержанию и могут помочь пользователям найти статью при поиске по связанным темам.