我尝试查看是否可以使用文本的背景和前景颜色来识别PDF中表格中可能的表头。使用PyMuPDF文本提取,我能够获得前景颜色。想知道有没有办法也能得到背景颜色。
我正在使用pymupdf 1.16.2和python 3.7。我查看了文档,但发现只有一个颜色字段,它与文本颜色而不是背景颜色相关联
如果有人知道如何使用pyMuPDF获得背景颜色,或者可能是其他软件包,请让我知道
发布于 2020-01-15 13:43:32
我需要一个类似的函数,但在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
https://stackoverflow.com/questions/58110777
复制