问题描述
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。我尝试通过 Pillow 从 data = xObject[obj].getdata()
中提取原始图像,但抛出“没有足够数据”的错误。如果使用 None
cv2.imdecode
所提供的 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
我将此函数添加到我的代码中:
import struct
def tiff_header_for_CCITT(width,height,img_size,CCITT_group=4):
tiff_header_struct = '<' + '2s' + 'h' + 'l' + 'h' + 'hhll' * 8 + 'h'
return struct.pack(tiff_header_struct,b'II',# Byte order indication: Little indian
42,# Version number (always 42)
8,# Offset to first IFD
8,# Number of tags in IFD
256,4,1,width,# ImageWidth,LONG,width
257,# ImageLength,lenght
258,3,# BitsPerSample,SHORT,1
259,CCITT_group,# Compression,4 = CCITT Group 4 fax encoding
262,# Threshholding,0 = WhiteIsZero
273,struct.calcsize(tiff_header_struct),# StripOffsets,len of header
278,# RowsPerStrip,lenght
279,# StripByteCounts,size of image
0 # last IFD
)
然后将此添加到我的代码中:
if not '/Filter' in xObject[obj]:
tiff_header = tiff_header_for_CCITT(size[0],size[1],len(data),1) # Using the group "1" because it works for some reason
inv_data = bytes((~bit + 256 for bit in data)) # for some reason the bits are inverted?
tiff_data = tiff_header + inv_data # Add the header to the inverted data
# Write the tiff file
img = open(PageFolder.joinpath(Path(PDFFilePath).stem +"."+ str(pdfPage) + "."+ str(obj_index)+ ".tiff"),'wb')
img.write(tiff_data)
img.close()
continue
我需要知道如何确定位是否需要反转或使用什么“CCITT Group”。
我会将其标记为答案,也许只是为此提出一个新问题。