目前正在使用类似的方法从PDF中提取图像:
import PyPDF4
from PIL import Image
from pathlib import Path
import os
PDFFilePath = Path("somefile.pdf")
OutputFolder = "somedirectory"
pdfpage = 0
with open(PDFFilePath,'rb') as pdf_reader:
pdf_object = PyPDF4.PdfFileReader(pdf_reader)
PageFolder = Path(OutputFolder).joinpath(Path(PDFFilePath.stem + '.'+ str(pdfPage)))
if not PageFolder.exists():
os.makedirs(PageFolder)
CurrentPage = pdf_object.getPage(pdfPage)
xObject = CurrentPage['/Resources']['/XObject'].getObject()
for obj_index,obj in enumerate(xObject):
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
else:
mode = "P"
if xObject[obj]['/Filter'] == '/FlateDecode':
img = Image.frombytes(mode, size, data)
img.save(PageFolder.joinpath(Path(PDFFilePath).stem +"."+ str(pdfPage) + "."+ str(obj_index) + ".png"),'wb')
elif xObject[obj]['/Filter'] == '/DCTDecode':
img = open(PageFolder.joinpath(Path(PDFFilePath).stem +"."+ str(pdfPage) + "."+ str(obj_index)+ ".jpg"),'wb')
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/JPXDecode':
img = open(PageFolder.joinpath(Path(PDFFilePath).stem +"."+ str(pdfPage) + "."+ str(obj_index)+ ".jp2"),'wb')
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
img = open(PageFolder.joinpath(Path(PDFFilePath).stem +"."+ str(pdfPage) + "."+ str(obj_index)+ ".tiff"),'wb')
img.write(data)
img.close()
我在xObject[obj]['/Filter']
部分遇到了一堆没有“/Filter”的PDF。我试图通过枕头从data = xObject[obj].getdata()
中提取原始图像,但抛出了一个错误,它“没有足够的数据”。如果使用cv2.imdecode
,OpenCV将返回None
提供的PDF是保密的,因此我无法提供样本
一个仍然使用PyPDF4的解决方案会很好
编辑:OpenCV图像阅读器
OpenCV部分(我从代码中删除了它,如果未检测到“/Filter”,它将被删除)
cv_color_space = cv2.IMREAD_COLOR if mode == "RGB" else cv2.IMREAD_GRAYSCALE
buf = np.frombuffer(data,np.uint8)
img = cv2.imdecode(buf,cv_color_space)
cv2.imwrite("outputfile.png",img)
图像显然是.tiff图像,但没有标题。 我找到这个:https://stackoverflow.com/a/34555343/13919892
我在代码中添加了此函数:
然后将其添加到我的代码中:
我需要知道如何识别位是否需要反转,或者使用什么“CCITT组”
我将把这个标记为答案,也许只是为这个打开一个新的问题
相关问题 更多 >
编程相关推荐