Iterate through time points in a 5D tiff file (Jython)

Hello,
just a silly question: I am writing down a script for processing some time lapse videos I made. These videos are composed of several time points and for every timepoint I have a stack. What I want to do is to perform a maximum intensity projection within a certain range of the stack across time and save it as a new video where I have only one slice (the projection) per timepoint.

I wrote the code and used setT(i) to iterate across the timepoints. It does not work, though, and in the end I get a video with the max projection of the first timepoint. What am I missing?

imp = IJ.openImage(os.path.join(srcDir, f))
if imp is None:
	raise Exception ("Could not open this image: ", f)
				
# Maximum intensity Projections of channel 1
imps = ChannelSplitter.split(imp)
ch1 = imps[(nChannel-1)]
				
n = ch1.getNSlices();
L = [(j, j+20) for j in range(0, n-19, 10)]
				
for el in L:
	vs = None
	for i in range(ch1.getDimensions()[-1]):
		ch1.setT(i)
		mip = getMIP(ch1, el[0], el[1])
		if not vs:
			vs = ImageStack(imp.width, imp.height)
			vs.addSlice(mip.getProcessor())
	prefix = "MAX_C1_{}-{}_".format(str(el[0]),str(el[1]))
	fs = FileSaver(ImagePlus(prefix+f, vs))
	fs.saveAsTiff(dstDir+"/"+prefix+f)

def getMIP(astack, start, end):
	mip = ZProjector(); 
	mip.setMethod(ZProjector.MAX_METHOD);
	mip.setImage(astack);
	mip.setStartSlice(start); mip.setStopSlice(end);
	mip.doProjection();
	return mip.getProjection()

I’m not sure that ch1.setT() has any effect on which time point is considered. It looks like by default it takes the first time point.

However you can do something much simpler. ZProjector() has a method doHyperStackProjection that allows you to do the projection for the entire time series in one go (and still keep the z-range that you specified. So your getMIP function becomes:

def getMIP(astack, start, end):
	mip = ZProjector(); 
	mip.setMethod(ZProjector.MAX_METHOD);
	mip.setImage(astack);
	mip.setStartSlice(start); mip.setStopSlice(end);
	mip.doHyperStackProjection(True)
	return mip.getProjection()

and your loop is super simple:

for el in L:
	mip = getMIP(ch1, el[0], el[1])
	mip.setTitle(prefix)
	prefix = "MAX_C1_{}-{}_".format(str(el[0]),str(el[1]))
	fs = FileSaver(mip)
	fs.saveAsTiff(dstDir+"/"+prefix+f)

As a side note, when you ask for help for debugging it’s better to post the full script. Like that people don’t have to figure out which packages need to be imported, what is srcDir or f etc.

Guillaume

1 Like

Thank you a lot Guillaume, your comment totally solved my issue. Sorry for the incomplete code, I will keep this in mind for the next question I will have!

1 Like