是否有任何 native 支持从 PDF 中抓取图像或在 Python 中创建某种对象,该对象可以包含 pdf 中的图像,然后可以通过 OpenCV 访问?我看过一些脚本将 PDF 的图像转储到我的目录中,但我的目标更多是访问 PDF,而不是将 PDF 中的数据(即图像)转储到我可以访问的某种对象中使用 OpenCV。我自己的探索没有产生任何结果,所以我想我会问。
基于@Ghilas BELHADJ 的示例添加了使用 PyMuPDF 的示例
import fitz
import cv2
import numpy as np
from tkinter import Tk
from tkinter.filedialog import askopenfilename
class AccessPDF:
def __init__(self):
self.filepath = ""
self.doc = None
def openPDF(self):
Tk().withdraw()
self.filepath = askopenfilename()
self.doc = fitz.open(self.filepath)
def pixel2np(self,pix):
im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
im = np.ascontiguousarray(im[..., [2, 1, 0]]) # rgb to bgr
return im
def displayKey(self):
pixobj = self.doc.getPagePixmap(0, alpha=False)
im = self.pixel2np(pixobj)
cv2.imwrite("testimg.png",im)
cv2.imshow("Key" im)
最佳答案
编辑:我根据@Dan Mašek 的评论对代码进行了修改
您可以使用 PyMuPDF
实现此目的(将 PDF 嵌入图像 加载到 OpenCV
中,而无需在磁盘上写入中间对象)和 Numpy
.
在这个例子中,我使用 this pdf file .
import fitz
import cv2
import numpy as np
def pix2np(pix):
im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
im = np.ascontiguousarray(im[..., [2, 1, 0]]) # rgb to bgr
return im
doc = fitz.open('NGM_2018_Media_Kit.pdf')
# entire page
# pix = doc.getPagePixmap(0, alpha=False)
# first page , 5th image, xref element
pix = fitz.Pixmap(doc, doc.getPageImageList(0)[4][0])
im = pix2np(pix)
cv2.putText(im, 'Azul fellawen', (100, 100),
cv2.FONT_HERSHEY_SIMPLEX, 1.,
(18, 156, 243), 2, cv2.LINE_AA)
cv2.imwrite('sample_0.png', im)
关于python-3.x - Python 和 OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53059007/