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

Suv*_*K S 5 python pdf-extraction pymupdf

我试图看看是否可以使用文本的背景和前景色识别 PDF 内表格中可能的表格标题。通过 PyMuPDF 文本提取,我能够获得前景色。想知道是否有办法也获得背景颜色。

我正在使用 pymupdf 1.16.2 和 python 3.7 我已经检查了文档,但只能找到一种颜色字段,该颜色字段与文本颜色而不是背景颜色相关

如果有人知道如何使用 pyMuPDF 或其他软件包获取背景颜色,请告诉我

Yoh*_* L. 8

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

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
Run Code Online (Sandbox Code Playgroud)