我正在尝试使用 PyPDF2 从 pdf 中提取图像,但是当我的代码获取它时,图像与其实际外观非常不同,请看下面的示例:
但它应该是这样的:
这是我正在使用的pdf:
https://www.hbp.com/resources/SAMPLE%20PDF.pdf
这是我的代码:
pdf_filename = "SAMPLE.pdf"
pdf_file = open(pdf_filename, 'rb')
cond_scan_reader = PyPDF2.PdfFileReader(pdf_file)
page = cond_scan_reader.getPage(0)
xObject = page['/Resources']['/XObject'].getObject()
i = 0
for obj in xObject:
# print(xObject[obj])
if xObject[obj]['/Subtype'] == '/Image':
if xObject[obj]['/Filter'] == '/DCTDecode':
data = xObject[obj]._data
img = open("{}".format(i) + ".jpg", "wb")
img.write(data)
img.close()
i += 1
因为我需要将图像保持在它的颜色模式,如果它是 CMYK,我不能将它转换为 RBG,因为我需要这些信息。
另外,我试图从我从 pdf 获得的图像中获取 dpi,该信息是否始终存储在图像中?
提前致谢
最佳答案
我用过 pdfreader从您的示例中提取图像。
图像使用 ICCBased 色彩空间,N=4,Intent 值为 RelativeColorimetric。这意味着“最接近”的 PDF 色彩空间是 DeviceCMYK。
您所需要的只是将图像转换为 RGB 并反转颜色。
这是代码:
from pdfreader import SimplePDFViewer
import PIL.ImageOps
fd = open("SAMPLE PDF.pdf", "rb")
viewer = SimplePDFViewer(fd)
viewer.render()
img = viewer.canvas.images['Im0']
# this displays ICCBased 4 RelativeColorimetric
print(img.ColorSpace[0], img.ColorSpace[1].N, img.Intent)
pil_image = img.to_Pillow()
pil_image = pil_image.convert("RGB")
inverted = PIL.ImageOps.invert(pil_image)
inverted.save("sample.png")
阅读有关 PDF 对象的更多信息:图像 (sec. 8.9.5) , InlineImage (sec. 8.9.7)
关于python - 在python中从PDF中提取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59289702/