欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Python 实现图片提取文字

Python 实现图片提取文字

2025/3/10 8:42:50 来源:https://blog.csdn.net/kouweizhu/article/details/145979681  浏览:    关键词:Python 实现图片提取文字

文章目录

一、效果图

二、库安装

三、使用示例

四、完整代码


一、效果图

使用的图片:

返回文字:

二、库安装

pip install easyocr opencv-python numpy  

三、使用示例

ocr = EasyOCRProcessor()
results = ocr.extract_text("test.png","output.png",confidence_threshold=0.6
)

四、完整代码

import easyocr
import cv2
import numpy as npclass EasyOCRProcessor:def __init__(self, languages=['ch_sim', 'en']):"""初始化EasyOCR处理器参数:languages: 需要识别的语言列表"""self.reader = easyocr.Reader(languages)def enhance_image(self, image):"""图像增强处理参数:image: OpenCV图像对象返回:处理后的图像"""# 亮度和对比度调整alpha = 1.2  # 对比度beta = 10  # 亮度adjusted = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)# 锐化kernel = np.array([[-1, -1, -1],[-1, 9, -1],[-1, -1, -1]])sharpened = cv2.filter2D(adjusted, -1, kernel)return sharpeneddef extract_text(self, image_path, output_path=None, confidence_threshold=0.5):"""提取图片中的文字参数:image_path: 图片路径output_path: 可选,输出处理后图片的路径confidence_threshold: 置信度阈值返回:提取的文字内容和位置信息"""try:# 读取图片image = cv2.imread(image_path)if image is None:raise ValueError("无法读取图片")# 图像增强enhanced = self.enhance_image(image)# 使用EasyOCR识别文字results = self.reader.readtext(enhanced)# 处理结果text_results = []for bbox, text, confidence in results:if confidence > confidence_threshold:text_results.append({'text': text,'confidence': confidence,'position': bbox})# 在图片上标记文字区域if output_path:points = np.array(bbox, np.int32)cv2.polylines(image, [points], True, (0, 255, 0), 2)cv2.putText(image, f"{text} ({confidence:.2f})",(int(bbox[0][0]), int(bbox[0][1]) - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)# 保存处理后的图片if output_path:cv2.imwrite(output_path, image)return text_resultsexcept Exception as e:print(f"错误: {str(e)}")return None# 使用示例
ocr = EasyOCRProcessor()
results = ocr.extract_text("test.png","output.png",confidence_threshold=0.6
)# 打印结果
if results:for result in results:print(f"文字: {result['text']}")print(f"置信度: {result['confidence']}")print(f"位置: {result['position']}")print("---")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词