51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 6224|回复: 0
打印 上一主题 下一主题

[转贴] 告别复制粘贴,Python 轻松实现 PDF 转文本!

[复制链接]
  • TA的每日心情
    无聊
    14 小时前
  • 签到天数: 944 天

    连续签到: 3 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2021-9-27 10:09:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    1测试积点
    对很多人来说,将 PDF 转换为可编辑的文本是个刚需,却苦于没有简单方法。在本文介绍的项目中,来自 K1 Digital 的高级机器学习工程师 Lucas Soares,尝试使用 OCR(光学字符识别)自动转录 pdf 幻灯片,转录效果还不错。
      传统的讲座通常伴随着一组 pdf 幻灯片。一般来说,想要对此类讲座做笔记,需要从 pdf 复制、粘贴很多内容。
      最近,来自 K1 Digital 的高级机器学习工程师 Lucas Soares 一直在尝试通过使用 OCR(光学字符识别)自动转录 pdf 幻灯片,以便直接在 markdown 文件中操作它们的内容,从而避免手动复制和粘贴 pdf 内容,实现这一过程的自动化。
      为什么不使用传统的 pdf 转文本工具呢?
      Lucas Soares 发现传统工具往往会带来更多的问题,需要花时间解决。他曾经尝试使用传统的 Python软件包,但是遇到了很多问题(例如必须使用复杂的正则表达式模式解析最终输出等),因此决定尝试使用目标检测和 OCR 来解决。
      基本过程可分为以下步骤:
      · 将 pdf 转换为图片;
      · 检测和识别图像中的文本;
      · 展示示例输出。
      基于深度学习的 OCR 将 pdf 转录为文本
      将 pdf 转换为图像
      Soares 使用的 pdf 幻灯片来自于 David Silver 的增强学习(参见以下 pdf 幻灯片地址)。使用「pdf2image」包将每张幻灯片转换为 png 图像格式。
    pdf 幻灯片示例。地址:https://www.davidsilver.uk/wp-co ... 020/03/intro_RL.pdf
      代码如下:
    1. from pdf2image import convert_from_path  
    2.   from pdf2image.exceptions import (  
    3.    PDFInfoNotInstalledError,  
    4.    PDFPageCountError,  
    5.    PDFSyntaxError  
    6.   )  
    7.   pdf_path = "path/to/file/intro_RL_Lecture1.pdf"  
    8.   images = convert_from_path(pdf_path)  
    9.   for i, image in enumerate(images):  
    10.       fname = "image" + str(i) + ".png"  
    11.       image.save(fname, "PNG")
    复制代码
    经过处理后,所有的 pdf 幻灯片都转换成 png 格式的图像:


    检测和识别图像中的文本
      为了检测和识别 png 图像中的文本,Soares 使用 ocr.pytorch 库中的文本检测器。按照说明下载模型并将模型保存在 checkpoints 文件夹中。
      ocr.pytorch 库地址:https://github.com/courao/ocr.pytorch
      代码如下:
    1.  # adapted from this source: https://github.com/courao/ocr.pytorch  
    2.   %load_ext autoreload  
    3.   %autoreload 2  
    4.   import os  
    5.   from ocr import ocr
    6.   import time  
    7.   import shutil  
    8.   import numpy as np  
    9.   import pathlib  
    10.   from PIL import Image  
    11.   from glob import glob  
    12.   import matplotlib.pyplot as plt  
    13.   import seaborn as sns  
    14.   sns.set()  
    15.   import pytesseract  
    16.   def single_pic_proc(image_file):  
    17.       image = np.array(Image.open(image_file).convert('RGB'))  
    18.       result, image_framed = ocr(image)  
    19.       return result,image_framed  
    20.   image_files = glob('./input_images/*.*')  
    21.   result_dir = './output_images_with_boxes/'  
    22.   # If the output folder exists we will remove it and redo it.  
    23.   if os.path.exists(result_dir):  
    24.       shutil.rmtree(result_dir)  
    25.   os.mkdir(result_dir)
    26.   for image_file in sorted(image_files):  
    27.       result, image_framed = single_pic_proc(image_file) # detecting and recognizing the text  
    28.       filename = pathlib.Path(image_file).name
    29.       output_file = os.path.join(result_dir, image_file.split('/')[-1])  
    30.       txt_file = os.path.join(result_dir, image_file.split('/')[-1].split('.')[0]+'.txt')  
    31.       txt_f = open(txt_file, 'w')  
    32.       Image.fromarray(image_framed).save(output_file)  
    33.       for key in result:  
    34.           txt_f.write(result[key][1]+'\n')  
    35.       txt_f.close()
    复制代码
    设置输入和输出文件夹,接着遍历所有输入图像(转换后的 pdf 幻灯片),然后通过 single_pic_proc() 函数运行 OCR 模块中的检测和识别模型,最后将输出保存到输出文件夹。
      其中检测继承(inherit)了 Pytorch CTPN 模型,识别继承了 Pytorch CRNN 模型,两者都存在于 OCR 模块中。
      示例输出
      代码如下:
    1. import cv2 as cv  
    2.   output_dir = pathlib.Path("./output_images_with_boxes")  
    3.   # image = cv.imread(str(np.random.choice(list(output_dir.iterdir()),1)[0]))  
    4.   image = cv.imread(f"{output_dir}/image7.png")  
    5.   size_reshaped = (int(image.shape[1]),int(image.shape[0]))  
    6.   image = cv.resize(image, size_reshaped)
    7.   cv.imshow("image", image)  
    8.   cv.waitKey(0)  
    9.   cv.destroyAllWindows()
    复制代码
    下图左为原始 pdf 幻灯片,图右为转录后的输出文本,转录后的准确率非常高。

    1. filename = f"{output_dir}/image7.txt"  
    2.   with open(filename, "r") as text:  
    3.       for line in text.readlines():  
    4.           print(line.strip("\n"))
    复制代码
    通过上述方法,最终你可以得到一个非常强大的工具来转录各种文档,从检测和识别手写笔记到检测和识别照片中的随机文本。拥有自己的 OCR 工具来处理一些文本内容,这比依赖外部软件来转录文档要好的多。




    附件: 您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-8 23:12 , Processed in 0.064856 second(s), 22 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表