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'
    IJ.run(imp, "8-bit", "")

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

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

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)
imp2.show() 

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: IJ.run() 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)
zp.setMethod(ZProjector.MAX_METHOD)
zp.doProjection()
impavg = zp.getProjection()
3 Likes

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?

Edit.
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