0
点赞
收藏
分享

微信扫一扫

pdf 转化为jpg python 批量转化

君心浅语 2022-02-24 阅读 120
python

做这个比赛
https://tianchi.aliyun.com/competition/entrance/531945/introduction
缺少真实的文本数据集,从网上搜了一下,基本都是实际场景OCR的那种

在这里插入图片描述

而我需要的是这样的,主要是找文本的那种:
请添加图片描述
请添加图片描述

直接爬取照片的话,又怕部分水印影响我的数据分布…
手动趴下来,半个小时整下来30张

算了,直接拿PDF转化为jpg,都是真实的照片

直接拿去改吧:

from pdf2image import convert_from_path
import time
import os
import sys



def getDirPdf(path):
    # 获取一个路径下的所有 pdf
    res = []
    for cur_dir, _, files in os.walk(path):
        for file in files:
            if file.endswith(".pdf"):
                pdf = os.path.join(cur_dir, file)
                res.append(pdf)
    return res
# getDirPdf(r"C:\Users\xx\Desktop\数值分析")


def pdflist2pdfslist(pdf_list):
    
    # 预处理pdf的list的
    # 如果是个目录则, 把里边的pdf拿出来, 添加到新列表
    # 如果是个pdf文件, 则直接添加到新列表
    
    res = []
    for path in pdf_list:
        if os.path.exists(path):
            if os.path.isdir(path):
                res += getDirPdf(path)
            if path.endswith(".pdf"):
                res.append(path)
        else:
            print("目录 %s 不存在"%path)
            sys.exit(0)

    return res

pdf_dir = [
    # r'C:\Users\zihao\Desktop\数值分析\Ch1.pdf',
    r"C:\Users\zihao\Downloads\Documents"
    ]

all_path = pdflist2pdfslist(pdf_dir)
for path in all_path:
    # Store Pdf with convert_from_path function
    images = convert_from_path(path) # 这个东西返回一个 List, 元素是 PIL.PpmImagePlugin.PpmImageFile
    name = os.path.basename(path).split(".")[0]
    for i in range(len(images)):
        # Save pages as images in the pdf
        images[i].save(name+'_page'+ str(i) +'.jpg', 'JPEG')

Reference

https://www.geeksforgeeks.org/convert-pdf-to-image-using-python/

举报

相关推荐

0 条评论