Matplotlib 线程;关闭特定图形实例
Matplotlib threading; closing a specific figure instance
问题的要点是:
我有一个线程池,用于为机器学习训练生成图像。我将所有已注释的图像提供给池,并从中生成图像。 (有效)
然后我添加一个可视化步骤,即生成人类可以理解的漂亮图像。为此,我使用 matplotlib。 (有效)
然后我想将此作为池中的附加步骤执行,但我的代码崩溃了。问题似乎是紧密而明确的声明:
import matplotlib.pyplot as plt
[code for visualisation]
plt.savefig(f, bbox_inches='tight', pad_inches=0)
plt.cla()
plt.close()
plt.switch_backend(backend_org)
当一个线程到达最后一行时,所有其他 plt
崩溃,因此在 Matlab 中,可以指定一个变量名称,以便 close()
或其他函数仅在具体形象。我没能在 matplotlib 中找到类似的概念,但它存在吗?
解决方案
只是为了展示面向对象的代码。
fig = plt.figure()
fig.subplots_adjust(left=0, right=1, top=1, bottom=0,
wspace=0, hspace=0)
ax = fig.add_subplot(1, 1, 1)
ax.margins(0, 0)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
label_viz = label2rgb(label, img, n_labels=len(label_names)) #generate labels
ax.imshow(label_viz)
ax.axis('off')
plt_handlers = []
plt_titles = []
for label_value, label_name in enumerate(label_names):
[...]
#generate legend
ax.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
f = io.BytesIO()
fig.savefig(f, bbox_inches='tight', pad_inches=0)
#ax.cla() #resulting in crashes across the thread
plt.close(fig)
我认为您不应该使用基于状态的 pyplot 方法,而应该使用面向对象的版本,您可以在其中处理 axes.Axes
的实例。否则不同过程中的不同情节会混淆。简短示例:
fig, ax = plt.subplots()
ax.plot(...)
fig.savefig(...)
问题的要点是:
我有一个线程池,用于为机器学习训练生成图像。我将所有已注释的图像提供给池,并从中生成图像。 (有效)
然后我添加一个可视化步骤,即生成人类可以理解的漂亮图像。为此,我使用 matplotlib。 (有效)
然后我想将此作为池中的附加步骤执行,但我的代码崩溃了。问题似乎是紧密而明确的声明:
import matplotlib.pyplot as plt
[code for visualisation]
plt.savefig(f, bbox_inches='tight', pad_inches=0)
plt.cla()
plt.close()
plt.switch_backend(backend_org)
当一个线程到达最后一行时,所有其他 plt
崩溃,因此在 Matlab 中,可以指定一个变量名称,以便 close()
或其他函数仅在具体形象。我没能在 matplotlib 中找到类似的概念,但它存在吗?
解决方案
只是为了展示面向对象的代码。
fig = plt.figure()
fig.subplots_adjust(left=0, right=1, top=1, bottom=0,
wspace=0, hspace=0)
ax = fig.add_subplot(1, 1, 1)
ax.margins(0, 0)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
label_viz = label2rgb(label, img, n_labels=len(label_names)) #generate labels
ax.imshow(label_viz)
ax.axis('off')
plt_handlers = []
plt_titles = []
for label_value, label_name in enumerate(label_names):
[...]
#generate legend
ax.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
f = io.BytesIO()
fig.savefig(f, bbox_inches='tight', pad_inches=0)
#ax.cla() #resulting in crashes across the thread
plt.close(fig)
我认为您不应该使用基于状态的 pyplot 方法,而应该使用面向对象的版本,您可以在其中处理 axes.Axes
的实例。否则不同过程中的不同情节会混淆。简短示例:
fig, ax = plt.subplots()
ax.plot(...)
fig.savefig(...)