当前位置: 首页 > news >正文

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("---")


http://www.mrgr.cn/news/93746.html

相关文章:

  • 发现U9查询设计上的一个逻辑
  • hadoop第3课(hdfs shell常用命令)
  • 数据治理的核心路线
  • 在Vue中 使用 Web Worker
  • ESP8266 WiFi 收发器入门(第 1 部分)
  • 强化学习和最优控制 - 知识图谱
  • Spring AI学习
  • MySQL复习笔记
  • CGI程序刷新共享内存视频流到HTTP
  • moodle 开源的在线学习管理系统(LMS)部署
  • Java学习--MySQL
  • 中级网络工程师面试题参考示例(1)
  • 山东大学计算机科学与技术学院软件工程实验日志(更新中)
  • 【vitepress】如何搭建并部署自己的博客网站
  • VBA 数据库同一表的当前行与其他行的主键重复判断实现方案1
  • 【洛谷P1080国王游戏】2025-3-7
  • Java 大视界 -- 基于 Java 的大数据实时数据处理框架性能评测与选型建议(121)
  • 1.12.信息系统的分类【ES】
  • langchain系列(九)- LangGraph 子图详解
  • Django小白级开发入门