简介:本文为零基础学习者提供Python图像文字识别入门指南,涵盖环境搭建、核心库使用、实战案例及优化技巧,助力快速掌握OCR技术。
图像文字识别(OCR,Optical Character Recognition)是将图片中的文字转换为可编辑文本的技术,广泛应用于自动化办公、数据提取、无障碍阅读等场景。Python凭借其丰富的生态库(如Pillow、OpenCV、Tesseract、EasyOCR)和简洁的语法,成为零基础学习者入门OCR的最佳选择。本文将以“钟式入门法”为核心,分步骤讲解如何从零开始实现图像文字识别,即使没有编程基础也能轻松上手。
python --version,确认输出版本号。pip install pillowfrom PIL import Image; img = Image.open("test.png")brew install tesseractsudo apt install tesseract-ocrpip install easyocr
import pytesseractfrom PIL import Image# 指定Tesseract路径(Windows需配置)pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'# 读取图像并识别image = Image.open("example.png")text = pytesseract.image_to_string(image, lang='chi_sim') # 中文简体print(text)
lang:指定语言(如eng英文、chi_sim中文简体)。config:调整识别模式(如--psm 6假设为统一文本块)。
import easyocr# 创建reader对象,指定语言reader = easyocr.Reader(['ch_sim', 'en']) # 中文简体+英文result = reader.readtext("example.png")# 输出识别结果for detection in result:print(detection[1]) # detection[1]为识别文本
OCR前对图像进行预处理可显著提升准确率,常用方法包括:
gray_img = image.convert("L") # PIL库
threshold = 150binary_img = gray_img.point(lambda x: 0 if x < threshold else 255)
import cv2denoised_img = cv2.fastNlMeansDenoisingColored(np.array(binary_img), None, 10, 10, 7, 21)
screenshot.png。代码实现:
import pytesseractfrom PIL import Imageimg = Image.open("screenshot.png")text = pytesseract.image_to_string(img, lang='eng')print("识别结果:", text)
代码实现:
import pytesseractfrom PIL import Image, ImageOps# 裁剪发票号码区域(假设坐标为(100, 200, 300, 250))invoice = Image.open("invoice.png")number_area = invoice.crop((100, 200, 300, 250))# 预处理gray = number_area.convert("L")binary = gray.point(lambda x: 0 if x < 180 else 255)# 识别text = pytesseract.image_to_string(binary, lang='chi_sim')print("发票号码:", text.strip())
lang与图像语言一致。使用OpenCV分割文字区域:
import cv2import numpy as npimg = cv2.imread("complex_bg.png")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)_, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)for cnt in contours:x, y, w, h = cv2.boundingRect(cnt)if w > 20 and h > 10: # 过滤小区域roi = img[y:y+h, x:x+w]cv2.imwrite(f"roi_{x}_{y}.png", roi)
import osimport pytesseractfrom PIL import Imageinput_dir = "images/"output_file = "results.txt"with open(output_file, "w", encoding="utf-8") as f:for filename in os.listdir(input_dir):if filename.endswith(".png"):img_path = os.path.join(input_dir, filename)text = pytesseract.image_to_string(Image.open(img_path), lang='chi_sim')f.write(f"{filename}:\n{text}\n\n")
通过本文的“钟式入门法”,零基础学习者可以快速掌握Python图像文字识别的核心技能。从环境搭建到实战案例,再到问题解决,每一步都提供了可操作的代码和详细解释。未来,随着深度学习的发展,OCR技术将更加智能,但Python的简洁性和库的丰富性仍将使其成为入门首选。立即动手实践,开启你的OCR之旅吧!