Memory Leak in python

Viewed 24

I coded a build_img_array function that creates plots in matplotlib and then saves it to a io buffer later to be converted to a pillow image object so that i can create a numpy array of the plot.

code:

import numpy as np
from matplotlib import pyplot as plt
import PIL
import io
import sys

from pympler.tracker import SummaryTracker
tracker = SummaryTracker()

def build_img_array():
  ymin_ = np.arange(0,1000)
  ymax_ = np.arange(2,1002)

  index = np.arange(0, 1000)

  fig, ax = plt.subplots(1)

  fig.set_size_inches(30, 10)
  fig.set_dpi(100)
  ax.set_facecolor('black')
  ax.set_xmargin(0.001)
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  fig.subplots_adjust(top=1, bottom=0, right=1, left=0) 

  ax.vlines(x=index, ymin=ymin_, ymax=ymax_, colors='white', lw=0.5)
  


  io_buf = io.BytesIO()
  fig.savefig(io_buf, dpi=100)
  
  io_buf.seek(0)
  img = PIL.Image.open(io_buf)
  io_buf.flush()
  io_buf.close

  fn = lambda x: 0 if x < 1 else (128 if x < 170 else 255)
  img = img.convert('L').point(fn, mode='L')

  observations_img = [np.asarray(img, dtype=np.uint8)]
  ax.cla()
  fig.clf()
  plt.close() 



for i in range(1000):
  print(i)
  build_img_array()
tracker.print_diff()

It is a simple function but for some reason when its done looping the memory use in colab spikes up to a point that my system crashes. I can find what the problem is. Dose anyone know what is the problem here?

0 Answers
Related