Pyimagej randomly freezes when running macro in python loop

I want to use pyimagej to run an ImageJ macro on multiple images using a python loop.

However, when running the python code, it sometimes stops at random.
The ImageJ GUI remains responsive, but the code gets stuck.

After a while (more than a minute), it continues as though nothing had happened.

Adding a wait command in the ImageJ macro didn’t help.

What could be the cause?
This is quite frustrating, because no errors are displayed.

I’m using the following versions:
ImageJ 1.52p
pyimagej 0.5.0 (conda-forge)
Python 3.7.6 (conda-forge)

Any help is appreciated. Thanks!

Below are the codes, and the sample image is attached:

import imagej

def do_action():
    for i in range(100):
        macro_path = '[path to ImageJ macro folder]/ijmacro.ijm'
        img_path = '[path to tif image folder]/sample.tif'
        openInImageJ(img_path, macro_path)

def openInImageJ(img_path, macro_path):
    '''Opens image using ImageJ
    img_path: path to image file
    macro_path: path to macro file
    macro = """
    macro = macro.replace('imgPath', img_path)
    print('Reading macro...')
    macro_auto = open(macro_path, 'r').read()
    print('Running macro...')

if __name__ == '__main__':
    ij = imagej.init('[path to Fiji folder]/', headless=False)


print('Running macro');

print('Applying mean filter...');
run("Mean...", "radius=3");

//wait(1000); //doesn't help

print('Finished macro');

sample.tif (976.7 KB)