Size of compressed image

Dear All,

I want to take compressed snapshot (VGA/RGB565) with M7 every 3s to send it on UART at 115200bauds.
To be sure to have best quality / size ratio, i triy to detect the best Q factor / file size ratio.

Here is a code :

import sensor, image, pyb, time, gc

red_led=pyb.LED(1)
red_led.off()

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.VGA)
sensor.skip_frames(time=200)

maxSize = 26000
maxQuality = 80
minQuality = 50
stepQuatiy = 5
clock=time.clock()

while(True):
   print("---------START----------")
   trialnb = 0
   quality = maxQuality
   size = maxSize + 1
   clock.reset()
   clock.tick()
   print('Memory 1: ' + str(gc.mem_alloc()) + ' Free: ' + str(gc.mem_free()) + ' Alloc: ' + str(gc.mem_alloc()) )
   img=sensor.snapshot()
   print('Memory 2: ' + str(gc.mem_alloc()) + ' Free: ' + str(gc.mem_free()) + ' Alloc: ' + str(gc.mem_alloc()) )

   while size > maxSize :
      try:
         trialnb = trialnb + 1
         size = img.compressed(quality).size()
         if size > maxSize :
            if quality - stepQuatiy > minQuality :
               print(" NOK %s - %d : %d " % (trialnb, quality, size) )
               quality = quality - stepQuatiy
            else :
               print(" END NOK %s - %d : %d " % (trialnb, quality, size) )
         else :
            print(" OK %s - %d : %d " % (trialnb, quality, size) )
            print( "duree:", clock.avg() )
      except MemoryError:
         print('Memory 3: ' + str(gc.mem_alloc()) + ' Free: ' + str(gc.mem_free()) + ' Alloc: ' + str(gc.mem_alloc()) )
         if quality - stepQuatiy > minQuality :
            quality = quality - stepQuatiy
      except:
         print('Used: ' + str(gc.mem_alloc()) + ' Free: ' + str(gc.mem_free()) + ' Alloc: ' + str(gc.mem_alloc()) )
         raise

There is some memory exceptions if you dont print memory allocation before and after taking snapshot.

Is there another way to do this ?
Thanks,

That’s basically what we do ourselves for streaming the image to the IDE: https://github.com/openmv/openmv/blob/master/src/omv/framebuffer.c#L40