本篇就在Python中读取pdf图片较上篇读取excel的略微复杂,相信小伙们已经准备好迎接今天的挑战,接下来一起看看吧:1.倒入相关库
1 2 3 4 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei";" >import fitz
import time
import re
import os<br></span></p>
|
2.具体实现
为了方便和其他模块组合,我直接写了个函数完成这个功能,实现如下:
(1)使用正则表达式查找PDF中的图片
1 2 3 4 5 6 7 8 9 10 11 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei";" >def pdf2pic(path, pic_path):
'' '
# 从pdf中提取图片
:param path: pdf的路径
:param pic_path: 图片保存的路径
:return:
' ''
t0 = time.clock()
# 使用正则表达式来查找图片
checkXO = r "/Type(?= */XObject)"
checkIM = r "/Subtype(?= */Image)" <br></span></p>
|
(2)打印PDF的相关信息
1 2 3 4 5 6 7 8 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei";" > # 打开pdf
doc = fitz.open(path)
# 图片计数
imgcount = 0
lenXREF = doc._getXrefLength()
# 打印PDF的信息
print( "文件名:{}, 页数: {}, 对象: {}" .format(path, len(doc), lenXREF - 1))<br></span></p>
|
(3)遍历PDF中的对象,遇到是图像才进行下一步,不然就continue
并且我们将文件的名字命名为word所在的路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei";" > # 遍历每一个对象
for i in range(1, lenXREF):
# 定义对象字符串
text = doc.getObjectString(i)
isXObject = re.search(checkXO, text)
# 使用正则表达式查看是否是图片
isImage = re.search(checkIM, text)
# 如果不是对象也不是图片,则continue
if not isXObject or not isImage:
continue
imgcount += 1
# 根据索引生成图像
pix = fitz.Pixmap(doc, i)
# 根据pdf的路径生成图片的名称
new_name = path.replace( '\\' , '_' ) + "_img{}.png" .format(imgcount)
new_name = new_name.replace( ':' , '' )<br></span></p>
|
(4)将图像存为png格式
1 2 3 4 5 6 7 8 9 10 11 12 13 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei";" > # 如果pix.n<5,可以直接存为PNG
if pix.n < 5:
pix.writePNG(os.path.join(pic_path, new_name))
# 否则先转换CMYK
else :
pix0 = fitz.Pixmap(fitz.csRGB, pix)
pix0.writePNG(os.path.join(pic_path, new_name))
pix0 = None
# 释放资源
pix = None
t1 = time.clock()
print( "运行时间:{}s" .format(t1 - t0))
print( "提取了{}张图片" .format(imgcount))<br></span></p>
|
(5)输入pdf路径,即可运行
1 2 3 4 5 6 7 8 9 10 11 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei";" > if __name__== '__main__' :
# pdf路径
path = r 'E:\dogcat\提取图片\计算机视觉算法工程师.pdf'
pic_path = r 'E:\dogcat\提取图片\测试'
# 创建保存图片的文件夹
if os.path.exists(pic_path):
print( "文件夹已存在,请重新创建新文件夹!" )
raise SystemExit
else :
os.mkdir(pic_path)
m = pdf2pic(path, pic_path)<br></span></p>
|
3.结果预览
(1)程序结果:

(2)原本的pdf:

(3)提取出来的图片
到这里,三种不同软件用Python读取图片的方法全部讲完了,大家可以根据需要自由选择。
更多Python学习推荐:PyThon学习网教学中心。
(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)