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:

test.py

import imagej

def do_action():
    
    for i in range(100):
    
        print(i)
        
        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
    
    Parameters:
    img_path: path to image file
    macro_path: path to macro file
    
    '''
    
    macro = """
    open("imgPath");
    """
    
    macro = macro.replace('imgPath', img_path)

    ij.py.run_macro(macro)
    
    print('Reading macro...')
    
    macro_auto = open(macro_path, 'r').read()
    
    print('Running macro...')
    
    ij.py.run_macro(macro_auto)


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

ijmacro.ijm

print('Running macro');

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

//print('Waiting...');
//wait(1000); //doesn't help

print('Finished macro');

sample.tif (976.7 KB)