繁体   English   中英

使用 Matplotlib 生成数百万个 png 文件的最快方法是什么?

[英]What's the fastest way to generate millions of png files using Matplotlib?

对于深度学习项目,我需要为数据集中的每个项目合成图。 这意味着生成 250 万个图,每个图为 224x224 像素。

到目前为止,我能做的最好的就是这个,在我的电脑上运行需要 2.7 秒:

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib.pyplot as plt

for i in range(100):
    fig = plt.Figure(frameon=False, facecolor="white", figsize=(4, 4))
    ax = fig.add_subplot(111)
    ax.axis('off')
    ax.plot([1, 2, 3, 4, 5, 6, 7, 8], [2, 4, 6, 8, 8, 6, 4, 3])
    canvas = FigureCanvas(fig)
    canvas.print_figure(str(i), dpi=56)

生成的图像(来自这个可重现的示例)如下所示:

在此处输入图像描述

真实图像使用更多数据(200 行),但这对速度几乎没有影响。

以上面的速度,我需要大约 18 个小时来生成我所有的地块? 有什么聪明的方法可以加快速度吗?

根据来自 AKX 的评论,Pillow 有一个 function ImageDraw.line()可以更快地执行此任务:

from PIL import Image, ImageDraw
from itertools import chain
scale = 224
pad = 5
scale_pad = scale - pad * 2
for i in range(200):
    im = Image.new('RGB', (scale, scale), (255, 255, 255)) 
    draw = ImageDraw.Draw(im) 
    x = [1, 2, 3, 4, 5, 6, 7, 8]
    y = [2, 4, 6, 8, 8, 6, 4, 3]
    x = [pad + (i - min(x)) / (max(x) - min(x)) * scale_pad for i in x]
    y = [pad + (i - min(y)) / (max(y) - min(y)) * scale_pad  for i in y]

    draw.line(list(chain.from_iterable(zip(x, y))), fill=(0, 0, 0), width=4)
    im.save(f"{i}.png")

这比 Matplotlib 的执行速度快大约 6 倍,这意味着我的任务应该只需要大约 3 个小时而不是 18 个小时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM