1.导入相关库
1
2
3
4
|
import fitz import time import re import os |
2.具体实现
为了方便和其他模块组合,我直接写了个函数完成这个功能,实现如下:
2.1.使用正则表达式查找PDF中的图片
1
2
3
4
5
6
7
8
9
10
11
|
def pdf2pic(path, pic_path): ''' # 从pdf中提取图片 :param path: pdf的路径 :param pic_path: 图片保存的路径 :return: ''' t0 = time.clock() # 使用正则表达式来查找图片 checkXO = r "/Type(?= */XObject)" checkIM = r "/Subtype(?= */Image)" |
2.2.打印PDF的相关信息
1
2
3
4
5
6
7
8
|
# 打开pdf doc = fitz. open (path) # 图片计数 imgcount = 0 lenXREF = doc._getXrefLength() # 打印PDF的信息 print ( "文件名:{}, 页数: {}, 对象: {}" . format (path, len (doc), lenXREF - 1 )) |
2.3.遍历PDF中的对象,遇到是图像才进行下一步,不然就continue
并且我们将文件的名字命名为word所在的路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# 遍历每一个对象 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( ':' , '') |
2.4.将图像存为png格式
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# 如果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)) |
2.5.输入pdf路径,即可运行
1
2
3
4
5
6
7
8
9
10
11
|
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) |
3.结果预览
3.1.程序结果
3.2.原本的pdf
3.3.提取出来的图片
到此这篇关于Python提取PDF中的图片的实现示例的文章就介绍到这了,更多相关Python提取PDF图片内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_15969343/article/details/81673302