python - 如何使用python从所有pptx文件幻灯片中提取所有图像和文本?
问题描述
我能够从 pptx 文件中读取图像,但不能读取所有图像。我无法提取幻灯片中显示的带有标题或其他文本的图像。这是我的代码,请帮助我。
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
import glob
import os
import codecs
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = '/usr/local/Cellar/tesseract/4.1.1/bin/tesseract'
from pytesseract import image_to_string
n=0
def write_image(shape):
global n
image = shape.image
# get image
image_bytes = image.blob
# assinging file name, e.g. 'image.jpg'
image_filename = fname[:-5]+'{:03d}.{}'.format(n, image.ext)
n += 1
print(image_filename)
os.chdir("directory_path/readpptx/images")
with open(image_filename, 'wb') as f:
f.write(image_bytes)
os.chdir("directory_path/readpptx")
def visitor(shape):
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
write_image(shape)
def iter_picture_shapes(prs1):
for slide in prs1.slides:
for shape in slide.shapes:
visitor(shape)
file = open("directory_path/MyFile.txt","a+")
for each_file in glob.glob("directory_path/*.pptx"):
fname = os.path.basename(each_file)
file.write("-------------------"+fname+"----------------------\n")
prs = Presentation(each_file)
print("---------------"+fname+"-------------------")
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
print(shape.text)
file.write(shape.text+"\n")
iter_picture_shapes(prs)
file.close()
上面的代码能够从没有文本或标题的 pptx 幻灯片中提取图像,但不能在具有文本或标题的幻灯片中提取图像。
解决方案
还尝试迭代幻灯片母版和幻灯片布局。如果有“背景”图像,那就是它们所在的位置。相同的for shape in slide.shapes:
机制适用于幻灯片母版和幻灯片版式;它们是Slide
具有相同形状访问语义的多态对象的变体。
我不认为您的问题与幻灯片上存在的标题或文本严格相关。也许那些特定的幻灯片使用包含一些背景图像的布局。如果您打开幻灯片并单击图像并没有选择它(给它边界框),这表明它是背景图像并且驻留在幻灯片布局或可能是幻灯片母版上。这就是徽标通常如何实现以显示在每张幻灯片上的方式。
如果其中有您感兴趣的文本和/或图像,您可能还需要考虑迭代每张幻灯片的备注幻灯片。在幻灯片备注中找到图像并不常见,但 PowerPoint 支持它。
另一种方法是遍历底层.pptx
包(作为 Zip 存档)并以这种方式提取图像。
推荐阅读
- java - 从依赖中获取资源
- python - 为什么我们不能在 python-3.x 中使用 len() 函数与 len() 函数交织在一起
- jmeter - 如何在非 GUI 模式下运行 jmeter 时获得样本吞吐量?
- scala - 是否可以使 Spark UDF 与可能为 None 的 Array 一起使用?
- php - Cakephp3.8-无记录时显示的页面较多
- istio - 从 Helm 迁移到 Istioctl
- php - 如果语句不起作用,管理员只能访问页面
- linux - java -version 显示较早版本,但已安装 java 11
- django - 使用 WebSocketCommunicator 在 Django Channels v2 测试中进行身份验证
- python - 如何过滤 Pandas DataFrame 范围内的日期?