diff --git a/ultralytics/utils/__init__.py b/ultralytics/utils/__init__.py index f614eea20..9a2209725 100644 --- a/ultralytics/utils/__init__.py +++ b/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