def regBf(fn=None, imp=None, refId=None): """ Register a time series stack to a specified reference slice, from a file (imported by BioFormat) or a stack ImagePlus. Returns a registered ImagePlus. The stack must have only 1 z layer. refId is in the format of [int channel, int slice, int frame] If no refId is supplied, will use the first slice [1,1,1] Note: since TurboReg is used for registeration, there will be temporary opened image windows. """ ## Prepare the right ImagePlus if imp is None: if fn is None: od = OpenDialog("Choose a file", None) filename = od.getFileName() if filename is None: print "User canceled the dialog!" return else: directory = od.getDirectory() filepath = directory + filename print "Selected file path:", filepath else: if os.path.exists(fn) and os.path.isfile(fn): filepath = fn else: print "File does not exist!" return imps = BF.openImagePlus(filepath) imp = imps[0] if imp is None: print "Cannot load file!" return else: if fn is not None: print "File or ImagePlus? Cannot load both." return width = imp.getWidth() height = imp.getHeight() # C nChannels = imp.getNChannels() # Z nSlices = imp.getNSlices() # T nFrames = imp.getNFrames() # pixel size calibration = imp.getCalibration() # Only supoort one z layer if nSlices != 1: print "Only support 1 slice at Z dimension." return # set registration reference slice if refId is None: refC = 1 refZ = 1 refT = 1 else: refC = refId[0] refZ = refId[1] refT = refId[2] if (refC not in range(1, nChannels + 1) or refZ not in range(1, nSlices + 1) or refT not in range(1, nFrames + 1)): print "Invalid reference image!" return stack = imp.getImageStack() registeredStack = ImageStack(width, height, nChannels * nFrames * nSlices) # setup windows, these are needed by TurboReg tmpip = FloatProcessor(width, height) refWin = ImageWindow(ImagePlus("ref", tmpip)) bounds = refWin.getBounds() # refWin.setVisible(False) toRegWin = ImageWindow(ImagePlus("toReg", tmpip)) toRegWin.setLocation(bounds.width + bounds.x, bounds.y) # toRegWin.setVisible(False) toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip)) toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y) # toTransformWin.setVisible(False) # get reference image refImp = ImagePlus("ref", stack.getProcessor(imp.getStackIndex(refC, refZ, refT))) refWin.setImage(refImp) tr = TurboReg_() for t in xrange(1, nFrames + 1): IJ.showProgress(t - 1, nFrames) # print "t ", t # do TurboReg on reference channel toRegId = imp.getStackIndex(refC, refZ, t) toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId)) toRegWin.setImage(toRegImp) regArg = "-align " +\ "-window " + toRegImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-window " + refImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-rigidBody " +\ str(width / 2) + " " + str(height / 2) + " " +\ str(width / 2) + " " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(regArg) registeredImp = tr.getTransformedImage() sourcePoints = tr.getSourcePoints() targetPoints = tr.getTargetPoints() registeredStack.setProcessor(registeredImp.getProcessor(), toRegId) # toRegImp.flush() # apply transformation on other channels for c in xrange(1, nChannels + 1): # print "c ", c if c == refC: continue toTransformId = imp.getStackIndex(c, 1, t) toTransformImp = ImagePlus("toTransform", stack.getProcessor(toTransformId)) toTransformWin.setImage(toTransformImp) transformArg = "-transform " +\ "-window " + toTransformImp.getTitle() + " " +\ str(width) + " " + str(height) + " " +\ "-rigidBody " +\ str(sourcePoints[0][0]) + " " +\ str(sourcePoints[0][1]) + " " +\ str(targetPoints[0][0]) + " " +\ str(targetPoints[0][1]) + " " +\ str(sourcePoints[1][0]) + " " +\ str(sourcePoints[1][1]) + " " +\ str(targetPoints[1][0]) + " " +\ str(targetPoints[1][1]) + " " +\ str(sourcePoints[2][0]) + " " +\ str(sourcePoints[2][1]) + " " +\ str(targetPoints[2][0]) + " " +\ str(targetPoints[2][1]) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(transformArg) registeredStack.setProcessor( tr.getTransformedImage().getProcessor(), toTransformId) # toTransformImp.flush() sourcePoints = None targetPoints = None IJ.showProgress(t, nFrames) IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames)) refWin.close() toRegWin.close() toTransformWin.close() imp2 = ImagePlus("reg_" + imp.getTitle(), registeredStack) imp2.setCalibration(imp.getCalibration().copy()) imp2.setDimensions(nChannels, nSlices, nFrames) # print "type ", imp.getType() # print "type ", imp2.getType() # print nChannels, " ", nSlices, " ", nFrames # print registeredStack.getSize() for key in imp.getProperties().stringPropertyNames(): imp2.setProperty(key, imp.getProperty(key)) # comp = CompositeImage(imp2, CompositeImage.COLOR) # comp.show() # imp2 = imp.clone() # imp2.setStack(registeredStack) # imp2.setTitle("reg"+imp.getTitle()) # imp2.show() # imp.show() return imp2
refpath = os.path.join(refdir, reffn) refImp = IJ.openImage(refpath) width = refImp.width height = refImp.height roim = RoiManager() roim.runCommand("open", roipath) roiArray = roim.getRoisAsArray() nRoi = len(roiArray) roim.close() bwStack = ImageStack(width, height, nRoi) for i in xrange(1, nRoi+1): bwStack.setProcessor(FloatProcessor(width, height, zeros('f', width * height), None), i) for i in xrange(1, nRoi+1): roi = roiArray[i-1] fp = bwStack.getProcessor(i) fp.setValue(1.0) fp.fill(roi) roiImp = ImagePlus("roi", bwStack) outfn = "roi_" + os.path.splitext(roifn)[0] + ".tif" outpath = os.path.join(roidir, outfn) if os.path.exists(outpath): print "Skipped, already exists: ", outfn else: IJ.saveAsTiff(roiImp, outpath)
refpath = os.path.join(refdir, reffn) refImp = IJ.openImage(refpath) width = refImp.width height = refImp.height roim = RoiManager() roim.runCommand("open", roipath) roiArray = roim.getRoisAsArray() nRoi = len(roiArray) roim.close() bwStack = ImageStack(width, height, nRoi) for i in xrange(1, nRoi + 1): bwStack.setProcessor( FloatProcessor(width, height, zeros('f', width * height), None), i) for i in xrange(1, nRoi + 1): roi = roiArray[i - 1] fp = bwStack.getProcessor(i) fp.setValue(1.0) fp.fill(roi) roiImp = ImagePlus("roi", bwStack) outfn = "roi_" + os.path.splitext(roifn)[0] + ".tif" outpath = os.path.join(roidir, outfn) if os.path.exists(outpath): print "Skipped, already exists: ", outfn else: IJ.saveAsTiff(roiImp, outpath)
def main(): Interpreter.batchMode = True if (lambda_flat == 0) ^ (lambda_dark == 0): print ("ERROR: Both of lambda_flat and lambda_dark must be zero," " or both non-zero.") return lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual" #import pdb; pdb.set_trace() print "Loading images..." filenames = enumerate_filenames(pattern) num_channels = len(filenames) num_images = len(filenames[0]) image = Opener().openImage(filenames[0][0]) width = image.width height = image.height image.close() # The internal initialization of the BaSiC code fails when we invoke it via # scripting, unless we explicitly set a the private 'noOfSlices' field. # Since it's private, we need to use Java reflection to access it. Basic_noOfSlices = Basic.getDeclaredField('noOfSlices') Basic_noOfSlices.setAccessible(True) basic = Basic() Basic_noOfSlices.setInt(basic, num_images) # Pre-allocate the output profile images, since we have all the dimensions. ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32); df_image = IJ.createImage("Dark-field", width, height, num_channels, 32); print("\n\n") # BaSiC works on one channel at a time, so we only read the images from one # channel at a time to limit memory usage. for channel in range(num_channels): print "Processing channel %d/%d..." % (channel + 1, num_channels) print "===========================" stack = ImageStack(width, height, num_images) opener = Opener() for i, filename in enumerate(filenames[channel]): print "Loading image %d/%d" % (i + 1, num_images) image = opener.openImage(filename) stack.setProcessor(image.getProcessor(), i + 1) input_image = ImagePlus("input", stack) # BaSiC seems to require the input image is actually the ImageJ # "current" image, otherwise it prints an error and aborts. WindowManager.setTempCurrentImage(input_image) basic.exec( input_image, None, None, "Estimate shading profiles", "Estimate both flat-field and dark-field", lambda_estimate, lambda_flat, lambda_dark, "Ignore", "Compute shading only" ) input_image.close() # Copy the pixels from the BaSiC-generated profile images to the # corresponding channel of our output images. ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title) ff_image.slice = channel + 1 ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0) ff_channel.close() df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title) df_image.slice = channel + 1 df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0) df_channel.close() print("\n\n") template = '%s/%s-%%s.tif' % (output_dir, experiment_name) ff_filename = template % 'ffp' IJ.saveAsTiff(ff_image, ff_filename) ff_image.close() df_filename = template % 'dfp' IJ.saveAsTiff(df_image, df_filename) df_image.close() print "Done!"
def main(): Interpreter.batchMode = True if (lambda_flat == 0) ^ (lambda_dark == 0): print ("ERROR: Both of lambda_flat and lambda_dark must be zero," " or both non-zero.") return lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual" print "Loading images..." filenames = enumerate_filenames(pattern) if len(filenames) == 0: return # This is the number of channels inferred from the filenames. The number # of channels in an individual image file will be determined below. num_channels = len(filenames) num_images = len(filenames[0]) image = Opener().openImage(filenames[0][0]) if image.getNDimensions() > 3: print "ERROR: Can't handle images with more than 3 dimensions." (width, height, channels, slices, frames) = image.getDimensions() # The third dimension could be any of these three, but the other two are # guaranteed to be equal to 1 since we know NDimensions is <= 3. image_channels = max((channels, slices, frames)) image.close() if num_channels > 1 and image_channels > 1: print ( "ERROR: Can only handle single-channel images with {channel} in" " the pattern, or multi-channel images without {channel}. The" " filename patterns imply %d channels and the images themselves" " have %d channels." % (num_channels, image_channels) ) return if image_channels == 1: multi_channel = False else: print ( "Detected multi-channel image files with %d channels" % image_channels ) multi_channel = True num_channels = image_channels # Clone the filename list across all channels. We will handle reading # the individual image planes for each channel below. filenames = filenames * num_channels # The internal initialization of the BaSiC code fails when we invoke it via # scripting, unless we explicitly set a the private 'noOfSlices' field. # Since it's private, we need to use Java reflection to access it. Basic_noOfSlices = Basic.getDeclaredField('noOfSlices') Basic_noOfSlices.setAccessible(True) basic = Basic() Basic_noOfSlices.setInt(basic, num_images) # Pre-allocate the output profile images, since we have all the dimensions. ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32); df_image = IJ.createImage("Dark-field", width, height, num_channels, 32); print("\n\n") # BaSiC works on one channel at a time, so we only read the images from one # channel at a time to limit memory usage. for channel in range(num_channels): print "Processing channel %d/%d..." % (channel + 1, num_channels) print "===========================" stack = ImageStack(width, height, num_images) opener = Opener() for i, filename in enumerate(filenames[channel]): print "Loading image %d/%d" % (i + 1, num_images) # For multi-channel images the channel determines the plane to read. args = [channel + 1] if multi_channel else [] image = opener.openImage(filename, *args) stack.setProcessor(image.getProcessor(), i + 1) input_image = ImagePlus("input", stack) # BaSiC seems to require the input image is actually the ImageJ # "current" image, otherwise it prints an error and aborts. WindowManager.setTempCurrentImage(input_image) basic.exec( input_image, None, None, "Estimate shading profiles", "Estimate both flat-field and dark-field", lambda_estimate, lambda_flat, lambda_dark, "Ignore", "Compute shading only" ) input_image.close() # Copy the pixels from the BaSiC-generated profile images to the # corresponding channel of our output images. ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title) ff_image.slice = channel + 1 ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0) ff_channel.close() df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title) df_image.slice = channel + 1 df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0) df_channel.close() print("\n\n") template = '%s/%s-%%s.tif' % (output_dir, experiment_name) ff_filename = template % 'ffp' IJ.saveAsTiff(ff_image, ff_filename) ff_image.close() df_filename = template % 'dfp' IJ.saveAsTiff(df_image, df_filename) df_image.close() print "Done!"
def regBf(fn=None, imp=None, refId=None): """ Register a time series stack to a specified reference slice, from a file (imported by BioFormat) or a stack ImagePlus. Returns a registered ImagePlus. The stack must have only 1 z layer. refId is in the format of [int channel, int slice, int frame] If no refId is supplied, will use the first slice [1,1,1] Note: since TurboReg is used for registeration, there will be temporary opened image windows. """ ## Prepare the right ImagePlus if imp is None: if fn is None: od = OpenDialog("Choose a file", None) filename = od.getFileName() if filename is None: print "User canceled the dialog!" return else: directory = od.getDirectory() filepath = directory + filename print "Selected file path:", filepath else: if os.path.exists(fn) and os.path.isfile(fn): filepath = fn else: print "File does not exist!" return imps = BF.openImagePlus(filepath) imp = imps[0] if imp is None: print "Cannot load file!" return else: if fn is not None: print "File or ImagePlus? Cannot load both." return width = imp.getWidth() height = imp.getHeight() # C nChannels = imp.getNChannels() # Z nSlices = imp.getNSlices() # T nFrames = imp.getNFrames() # pixel size calibration = imp.getCalibration() # Only supoort one z layer if nSlices != 1: print "Only support 1 slice at Z dimension." return # set registration reference slice if refId is None: refC = 1 refZ = 1 refT = 1 else: refC = refId[0] refZ = refId[1] refT = refId[2] if (refC not in range(1, nChannels+1) or refZ not in range(1, nSlices+1) or refT not in range(1, nFrames+1) ): print "Invalid reference image!" return stack = imp.getImageStack() registeredStack = ImageStack(width, height, nChannels*nFrames*nSlices) # setup windows, these are needed by TurboReg tmpip = FloatProcessor(width, height) refWin = ImageWindow(ImagePlus("ref", tmpip)) bounds = refWin.getBounds() # refWin.setVisible(False) toRegWin = ImageWindow(ImagePlus("toReg", tmpip)) toRegWin.setLocation(bounds.width + bounds.x, bounds.y) # toRegWin.setVisible(False) toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip)) toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y) # toTransformWin.setVisible(False) # get reference image refImp = ImagePlus("ref", stack.getProcessor(imp.getStackIndex(refC, refZ, refT))) refWin.setImage(refImp) tr = TurboReg_() for t in xrange(1, nFrames+1): IJ.showProgress(t-1, nFrames) # print "t ", t # do TurboReg on reference channel toRegId = imp.getStackIndex(refC, refZ, t) toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId)) toRegWin.setImage(toRegImp) regArg = "-align " +\ "-window " + toRegImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-window " + refImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-rigidBody " +\ str(width / 2) + " " + str(height / 2) + " " +\ str(width / 2) + " " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(regArg) registeredImp = tr.getTransformedImage() sourcePoints = tr.getSourcePoints() targetPoints = tr.getTargetPoints() registeredStack.setProcessor(registeredImp.getProcessor(), toRegId) # toRegImp.flush() # apply transformation on other channels for c in xrange(1, nChannels+1): # print "c ", c if c == refC: continue toTransformId = imp.getStackIndex(c, 1, t) toTransformImp = ImagePlus("toTransform", stack.getProcessor(toTransformId)) toTransformWin.setImage(toTransformImp) transformArg = "-transform " +\ "-window " + toTransformImp.getTitle() + " " +\ str(width) + " " + str(height) + " " +\ "-rigidBody " +\ str(sourcePoints[0][0]) + " " +\ str(sourcePoints[0][1]) + " " +\ str(targetPoints[0][0]) + " " +\ str(targetPoints[0][1]) + " " +\ str(sourcePoints[1][0]) + " " +\ str(sourcePoints[1][1]) + " " +\ str(targetPoints[1][0]) + " " +\ str(targetPoints[1][1]) + " " +\ str(sourcePoints[2][0]) + " " +\ str(sourcePoints[2][1]) + " " +\ str(targetPoints[2][0]) + " " +\ str(targetPoints[2][1]) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(transformArg) registeredStack.setProcessor(tr.getTransformedImage().getProcessor(), toTransformId) # toTransformImp.flush() sourcePoints = None targetPoints = None IJ.showProgress(t, nFrames) IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames)) refWin.close() toRegWin.close() toTransformWin.close() imp2 = ImagePlus("reg_"+imp.getTitle(), registeredStack) imp2.setCalibration(imp.getCalibration().copy()) imp2.setDimensions(nChannels, nSlices, nFrames) # print "type ", imp.getType() # print "type ", imp2.getType() # print nChannels, " ", nSlices, " ", nFrames # print registeredStack.getSize() for key in imp.getProperties().stringPropertyNames(): imp2.setProperty(key, imp.getProperty(key)) # comp = CompositeImage(imp2, CompositeImage.COLOR) # comp.show() # imp2 = imp.clone() # imp2.setStack(registeredStack) # imp2.setTitle("reg"+imp.getTitle()) # imp2.show() # imp.show() return imp2