当前位置: 首页 > 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 np


class 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 sharpened

    def 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_results

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

相关文章:

  • 基于yolov11的西红柿番茄叶子病害检测系统python源码+onnx模型+评估指标曲线+精美GUI界面
  • WinForm模态与非模态窗体
  • 低空经济快速发展,无人机人才培养及校企实验室共建技术详解
  • Eclipse 查看 JAVA SE 23 官方API 源代码
  • 【0基础跟AI学软考高项】成本管理
  • 战争三年,乌克兰已满目疮痍
  • 数据结构第七节:AVL树(初阶)
  • 问题解决:AttributeError: ‘NoneType‘ object has no attribute ‘text‘
  • YOLO 各系列结构整理
  • 前端 | 向后端传数据,判断问题所在的调试过程
  • 爬虫案例十js逆向合肥滨湖会展中心网
  • 从预测到控制:电力RK3568边缘计算机在电网调度中的全面应用
  • 【RAG】RAG 系统的基本搭建流程(ES关键词检索示例)
  • Linux应用:文件属性
  • vtkAppendPolyData vtkMultiBlockDataGroupFilter 区别 合并数据
  • 代码贴--二叉树(链式结构)
  • 如何利用DeepSeek+OCR技术打造一款AI投标工具:自动解析招标文件并生成投标标书的工具?
  • Ubuntu无风扇工控机:解决精密仪器散热难题的利器
  • Python笔记(简单版)
  • SmolVLM2 - 将视频理解带到每个设备
  • 上千螺母引发的枪支散件案:五金厂老板的儿子被诉,律师作无罪辩护
  • 国家统计局:中美大幅降低关税有利于双方贸易增长,也有利于世界经济复苏
  • 减负举措如何助力基层干部轻装上阵?记者一线调查
  • 俄乌刚谈完美国便筹划与两国领导人通话,目的几何?
  • 浙江一教师被指殴打并威胁小学生,教育局通报涉事人被行拘
  • 卿晨璟靓等用服刑经历“引流”,专家:将犯罪问题娱乐化会消解刑罚严肃性