Ensure matplotlib backend gets reset with plt_settings (#15759)

Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
pull/15754/head
Robert Schroll 3 months ago committed by GitHub
parent 8bb776fbc3
commit a89b316f27
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 17
      ultralytics/utils/__init__.py

@ -219,16 +219,19 @@ def plt_settings(rcparams=None, backend="Agg"):
def wrapper(*args, **kwargs):
"""Sets rc parameters and backend, calls the original function, and restores the settings."""
original_backend = plt.get_backend()
if backend.lower() != original_backend.lower():
switch = backend.lower() != original_backend.lower()
if switch:
plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
plt.switch_backend(backend)
with plt.rc_context(rcparams):
result = func(*args, **kwargs)
if backend != original_backend:
plt.close("all")
plt.switch_backend(original_backend)
# Plot with backend and always revert to original backend
try:
with plt.rc_context(rcparams):
result = func(*args, **kwargs)
finally:
if switch:
plt.close("all")
plt.switch_backend(original_backend)
return result
return wrapper

Loading…
Cancel
Save