我正在尝试使用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,该信息是否始终存储在图像中? 预先感谢
答案 0 :(得分:1)
希望这行得通:您可能需要使用另一个库,例如Pillow
:
这里是一个例子:
from PIL import Image
image = Image.open("path_to_image")
if image.mode == 'CMYK':
image = image.convert('RGB')
image.write("path_to_image.jpg")
答案 1 :(得分:1)
我使用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)