Removing Background with Python

I am trying to write a script that will eventually process a lot of Avis, do some simple image processing, track a bunch of stuff with trackmate. However, I am stuck at the image processing, particularly using the image calculator. I have all the files I want to process in a list called osdir. Ill try to only paste the relevant code here:

from ij import IJ
from ij.plugin import ImageCalculator as ic
from ij.plugin import AVI_Reader
import os

dir_input = dir/to/folder
osdir = [  ]

for filename in osdir:   
    fullpath = os.path.join(dir_input, filename)

    print fullpath
    imp = AVI_Reader().openVirtual(fullpath)

    print 'Transforming into 8bit', "8-bit", "")

    print 'Creating Z Projection for Background Removal'
    impavg =, "Z Project...", "start=1 stop=440 projection=[Average Intensity]")

    print 'Subtracking Background from Stack'
    ic().run("Subtract Stack", imp,impavg)

However, this does not spit out an error but also I cannot see the result of the subtraction. Further more, if I change the script to

imp2 = ic().run("Subtract Stack create Stack", imp, impavg) 

I get this error: AttributeError: ‘NoneType’ object has no attribute ‘show’

I am a bit at a loss and not sure how to fix it.

The problem is already in this line: is static void, so it will never return any object.

If you want to retrieve the result of your z projection, use the ZProjector API:

from ij.plugin import ZProjector

zp = ZProjector(imp)
impavg = zp.getProjection()

Interesting, I will try that.
However, I do get a result for the Z-projection with my previous code, but maybe its buggy. I will report back

This works well, thank you Jan.
Only problem now is that it only subtracts the first frame, not the entire stack, do you have an idea on how to fix that?

I guess I have to iterate over each frame or make the z-projection have the same amount of frames as the original stack.

1 Like