import cv2
import fitz
import numpy as np
def get_image_from_pdf(input_path)
p = Path(input_path)
temp_dir = p.parent / "temp"
temp_dir.mkdir(exist_ok=True, parents=True)
doc: fitz.Document = fitz.open(input_path)
for page_index, page in enumerate(doc.pages()):
pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
img_save_path = str(temp_dir / f"{p.stem}-{page_index}.png")
pix.pil_save(img_save_path, dpi=(dpi, dpi))
# 从文件加载
img = cv2.imdecode(np.fromfile(img_save_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)[..., :3]
# 从pixmap内存中加载
img = cv2.imdecode(np.frombuffer(pixmap.tobytes(), dtype=np.uint8), cv2.IMREAD_UNCHANGED)[..., :3]
# 直接从pix加载
if pixmap.alpha:
img = np.frombuffer(pixmap.samples, dtype=np.uint8).reshape(pixmap.h, pixmap.w, 4)
else:
img = np.frombuffer(pixmap.samples, dtype=np.uint8).reshape(pixmap.h, pixmap.w, 3)
os.remove(img_save_path)
doc.close()
pymupdf转图片,cv从内存加载数据,np.frombuffer
于 2024-11-04 16:30:42 首次发布
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Python3.8
Conda
Python
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

被折叠的 条评论
为什么被折叠?



