I am trying to create a Gtk Widget using the Python GObject bindings that you can pass an OpenCV
image to that will then show it. I have created a class that is inherited from Gtk.Image
that is used to show the image. You pass the OpenCV image to this class using the show_frame
method, which then updates the Gtk.Image
so it shows that image.
I have tested this and it works fine, i.e the image is correctly shown and updated when the show_frame
method is called. However every time the image is updated, the memory
used increases, until there is not enough memory and the program
crashes.
I believe this is due to the memory that image is not being freed
correctly. I cannot however work out how to fix this. I have tried
unreferencing the gbytes
once a new frame is received but this does not help. The memory only builds up when the set_from_pixbuf
function is called. If this is commented out the memory usage stays at a constant level.
class OpenCVImageViewer(Gtk.Image):
def __init__(self):
Gtk.Image.__init__(self)
def show_frame(self, frame):
# Convert to opencv BGR to Gtk RGB
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Get details about frame in order to set up pixbuffer
height = rgb_image.shape[0]
width = rgb_image.shape[1]
nChannels = rgb_image.shape[2]
gbytes = GLib.Bytes.new(rgb_image.tostring())
pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(gbytes, GdkPixbuf.Colorspace.RGB, False,
8, width, height, width*nChannels)
# Add Gtk to main thread loop for thread safety
GLib.idle_add(self.set_from_pixbuf, pixbuf)
GLib.idle_add(self.queue_draw)
Does any one know how to free this memory?