png转pdf(批处理)
在使用overleaf时,如果项目太大,后期会导致一直“编译超时”等异常,充会员也无法解决。此时,若将项目中所有png或jpg图片转为pdf,可解决问题。
import os
import glob
import fitz
def png2pdf(img_path, pdf_path):
"""
img_path (str): 遍历此文件夹下文件(png图片)
pdf_path (str): 输出到此文件夹下
"""
def _frompic2pdf(img_path, pdf_path, pdf_name):
for img in sorted(glob.glob(img_path + pdf_name + '.png')):
doc = fitz.open()
imgdoc = fitz.open(img)
pdfbytes = imgdoc.convertToPDF()
imgpdf = fitz.open("pdf", pdfbytes)
doc.insertPDF(imgpdf)
doc.save(pdf_path + pdf_name + '.pdf')
doc.close()
for root, dirs, files in os.walk(img_path):
for file in files:
destfileName = os.path.splitext(file)[0]
_frompic2pdf(img_path=img_path, pdf_path=pdf_path, pdf_name=destfileName)
img_path = r'imgs/'
pdf_path = r'output/'
png2pdf(img_path, pdf_path)
GIF生成器(批处理)
import imageio
def compose_gif(img_paths, name, outfolder):
"""
img_paths (list (str)):
name (str):
outfolder (str):
"""
gif_images = []
for path in img_paths:
gif_images.append(imageio.imread(path))
imageio.mimsave(f"{outfolder}/{name}.gif",gif_images,fps=2)
- 流程逻辑部分:将每个epoch下(共12个)的N张检测图分别按顺序进行合成,最终生成N个GIF,可视化这N张图片随epoch的变化趋势。其中,原图作为起始图片。
核心逻辑:生成每个GIF的图片列表。首先,遍历epoch_1文件夹下所有jpg图片,获取所需可视化的N张图片的file_name;然后,对这N张图分别进行处理(先获取原图,再得到GIF所需的参数列表),调用GIF核心函数,依次生成。
import os
import matplotlib.pyplot as plt
from PIL import Image
def generator(epochs_int, outfolder):
"""
epochs_int (int): 11 means [1,11]
outfolder (str):
"""
def cp_coco(imglist):
coco_path=imglist[0]
plt.figure(figsize=(14,8), dpi=100)
set_plt(plt)
plt.imshow(Image.open(coco_path))
new_path=f"CPR_ori/{coco_path[coco_path.rfind('/')+1:]}"
imglist[0]=new_path
plt.savefig(new_path)
plt.clf()
def merge_path(fname, dirs):
imglist=[]
for i,d in enumerate(dirs):
if i == 0:
coco=fname[fname.rfind('_')+1:]
imglist.append(os.path.join(d, coco))
else:
imglist.append(os.path.join(d, fname))
return imglist
if epochs_int <1:
return
folders= ['../../data/coco/images/']
for idx in range(1, epochs_int+1):
folders.append(f"CPR_e{idx}")
for f in os.listdir(folders[1]):
if f.endswith('.jpg'):
imgs=merge_path(f, folders)
cp_coco(imgs)
compose_gif(imgs, f[:-4], outfolder)
generator(12, 'gif/')
|