【问题标题】:Extracting Powerpoint background images using python-pptx使用 python-pptx 提取 Powerpoint 背景图像
【发布时间】:2022-11-09 00:31:31
【问题描述】:

我有几个 powerpoint 需要以编程方式洗牌并从中提取图像。然后需要将图像转换为 OpenCV 格式以供以后处理/分析。我已经成功地为 pptx 中的图像完成了此操作,使用:

for slide in presentation:
    for shape in slide.shapes
        if 'Picture' in shape.name:
            pic_list.append(shape)

用于提取,并且:

img = cv2.imdecode(np.frombuffer(page[i].image.blob, np.uint8), cv2.IMREAD_COLOR)

用于 python-pptx 图片到 OpenCV 的转换。但是,我在以类似方式提取和操作背景时遇到了很多麻烦。

slide.background

提取一个“_Background”对象就足够了,但是我还没有找到一个很好的方法来将它转换成类似于Pictures的OpenCV对象。有谁知道如何做到这一点?我正在使用 python-pptx 进行提取,但如果无法使用该软件包,则不会对其他软件包不利。

【问题讨论】:

  • “opencv 对象”?你想要numpy 数组或 PIL Image 对象。这些是python中最常见的图像表示。
  • 是的,它是 OpenCV 中使用的 BGR 格式的 numpy 数组。这不是真正的问题,提取背景以便将它们转换为图像类型——任何类型的——用于下游分析是问题所在。
  • 所以这是一个python-pptx 的问题。 their api docs 没有提及 Background 对象,尽管它显然存在......你应该在他们的 github 上提交一个错误。
  • 与 python-pptx 相比,它更像是一个一般性的“有什么方法可以提取背景并将它们转换为 Python 中的图像格式”。我目前正在研究 Aspose.Slides 作为一种潜在的解决方案,如果它有效,我将发布它。

标签: python powerpoint python-pptx


【解决方案1】:

经过相当多的工作,我发现了如何做到这一点——也就是说,你没有。据我所知,没有办法直接使用 python-pptx 或 Aspose 提取背景。 Powerpoint——事实证明,它是一个可以用 7zip 解压缩的档案——将其背景分解为 ppt/media(图片)、ppt/slideLayouts 和 ppt/slideMasters(文本、格式),它们是仅由 Powerpoint 渲染器拼凑而成。这意味着要提取显示的背景,您基本上需要运行 Powerpoint 并在删除文本/图片/等后为幻灯片拍照。从前台。

我不需要这样做,因为我只需要从背景中提取文本。这可以通过在 <a:t> 标记处使用 BeautifulSoup 检查 slideLayouts 和 slideMasters XML 来完成。执行此操作的代码非常简单:

import zipfile
with zipfile.ZipFile(pptx_path, 'r') as zip_ref:
    zip_ref.extractall(extraction_directory)

这会将 .pptx 提取到其组件文件中。

from glob import glob
layouts = glob(os.path.join(extr_dir, 'pptslideLayouts*.xml'))
masters = glob(os.path.join(extr_dir, 'pptslideMasters*.xml'))
files = layouts + masters

这将为您提供幻灯片布局/母版的路径。

from bs4 import BeautifulSoup    
text_list = []
    for file in files:
        with open(file) as f:
            data = f.read()
        bs_data = BeautifulSoup(data, "xml")
        bs_a_t = bs_data.find_all('a:t')
        for a_t in bs_a_t:
            text_list.append(str(a_t.contents[0]))

这将为您提供 XML 中的实际文本。

希望这对将来的其他人有用。

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多