MatPLotLib

Memory Leaks

Sometimes MatPlotLib ends up leaking memory and filling the RAM with garbage, to mitigate this effect, first of all import matplotlib in this order:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import gc

Now, wherever you create images inside loops, do the following cleanup:

fig.savefig(f"<path to image file>{<some integer counter>:03d}.png")
fig.clf()
plt.close(fig)
gc.collect()

gc.collect() triggers the garbage collector to free the memory that was wasted during the processing of the image.