首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在PyMuPDF中获取文本的背景色

如何在PyMuPDF中获取文本的背景色
EN

Stack Overflow用户
提问于 2019-09-26 06:30:06
回答 1查看 842关注 0票数 4

我尝试查看是否可以使用文本的背景和前景颜色来识别PDF中表格中可能的表头。使用PyMuPDF文本提取,我能够获得前景颜色。想知道有没有办法也能得到背景颜色。

我正在使用pymupdf 1.16.2和python 3.7。我查看了文档,但发现只有一个颜色字段,它与文本颜色而不是背景颜色相关联

如果有人知道如何使用pyMuPDF获得背景颜色,或者可能是其他软件包,请让我知道

EN

回答 1

Stack Overflow用户

发布于 2020-01-15 13:43:32

我需要一个类似的函数,但在PyMuPDF中找不到它,所以我编写了一个函数来获取包含文本的左上角bbox中像素的颜色。

代码语言:javascript
运行
AI代码解释
复制
def getText2(page: fitz.Page, zoom_f=3) -> dict:
    """
    Function similar to fitz.Page.getText("dict"). But the returned dict
    also contains a key "bg_color" with color tuple as value for each block in "blocks".
    """
    # Retrieves the content of the page
    all_words = page.getText("dict")

    # Transform page into PIL.Image
    mat = fitz.Matrix(zoom_f, zoom_f)
    pixmap = page.getPixmap(mat)
    img = Image.open(io.BytesIO(pixmap.getPNGData()))
    img_border = fitz.Rect(0, 0, img.width, img.height)
    for block in all_words['blocks']:
        # Retrieve only text block (type 0)
        if block['type'] == 0:
            rect = fitz.Rect(*tuple(xy * zoom_f for xy in block['bbox']))
            if img_border.contains(rect):
                color = img.getpixel((rect.x0, rect.y0))
                block['bg_color'] = tuple(c/255 for c in color)
    return all_words
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58110777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档