Ejemplo n.º 1
0
    def setReaderOptions(imagefile, stitchtiles=False,
                                    setflatres=True,
                                    setconcat=False,
                                    openallseries=False,
                                    showomexml=False,
                                    attach=False,
                                    autoscale=True):

        czi_options = DynamicMetadataOptions()
        czi_options.setBoolean("zeissczi.autostitch", stitchtiles)
        czi_options.setBoolean("zeissczi.attachments", attach)

        # set the option for the CZIReader
        czireader = ImportTools.setCZIReaderOptions(imagefile, czi_options, setflatres=setflatres)

        # Set the preferences in the ImageJ plugin
        # Note although these preferences are applied, they are not refreshed in the UI
        Prefs.set("bioformats.zeissczi.allow.autostitch", str(stitchtiles).lower())
        Prefs.set("bioformats.zeissczi.include.attachments", str(attach).lower())

        # set the option for the BioFormats import
        reader_options = ImporterOptions()
        reader_options.setOpenAllSeries(openallseries)
        reader_options.setShowOMEXML(showomexml)
        reader_options.setConcatenate(setconcat)
        reader_options.setAutoscale(autoscale)
        reader_options.setStitchTiles(stitchtiles)
        reader_options.setId(imagefile)

        return reader_options, czireader
def getImps(fpath):
	opt = IO()
	opt.setId(fpath)
	opt.setOpenAllSeries(True) 
	impA = BF.openImagePlus(opt)
	print "Series number: " + str(len(impA))
	#impA = BF.openImagePlus()
	return impA
Ejemplo n.º 3
0
def concatenateImagePlus(files, outfile):
    """Concatenate images contained in files and save in outfile"""

    options = ImporterOptions()
    options.setId(files[0])
    options.setVirtual(1)
    options.setOpenAllSeries(1)
    options.setQuiet(1)
    images = BF.openImagePlus(options)
    imageG = images[0]
    nrPositions = len(images)
    options.setOpenAllSeries(0)

    nslices = imageG.getNSlices()
    nframes = len(files)
    nchannels = imageG.getNChannels()
    luts = imageG.getLuts()

    for i in range(0, nrPositions):
        concatImgPlus = IJ.createHyperStack(
            "ConcatFile", imageG.getWidth(), imageG.getHeight(),
            imageG.getNChannels(), imageG.getNSlices(),
            len(files), imageG.getBitDepth())


        concatStack = ImageStack(imageG.getWidth(), imageG.getHeight())
        IJ.showStatus("Concatenating files")
        for file_ in files:
            try:
                print '...', basename(file_)
                options.setSeriesOn(i, 1)
                options.setId(file_)
                image = BF.openImagePlus(options)[0]
                imageStack = image.getImageStack()

                sliceNr = imageStack.getSize()
                for j in range(1, sliceNr+1):
                    concatStack.addSlice(imageStack.getProcessor(j))
                image.close()
                options.setSeriesOn(i, 0)
            except Exception, e:
                IJ.log("ERROR")
                IJ.log(file_ + str(e))
                raise
            IJ.showProgress(files.index(file_), len(files))

        concatImgPlus.setStack(concatStack, nchannels, nslices, nframes)
        concatImgPlus.setCalibration(image.getCalibration())
        concatImgPlus.setOpenAsHyperStack(True)
        concatImgPlus.setLuts(luts)
        concatImgPlus.close()
        IJ.saveAs(concatImgPlus, "Tiff",  outfile)
Ejemplo n.º 4
0
def run(imagefile, useBF=True,
        series=0,
        filtertype='MEDIAN',
        filterradius='5'):

    #log.log(LogLevel.INFO, 'Image Filename : ' + imagefile)
    log.info('Image Filename : ' + imagefile)

    # get basic image metainfo
    metainfo = get_metadata(imagefile, imageID=series)
    for k, v in metainfo.items():
        #log.log(LogLevel.INFO, str(k) + ' : ' + str(v))
        log.info(str(k) + ' : ' + str(v))

    if not useBF:
        # using IJ static method
        imp = IJ.openImage(imagefile)

    if useBF:
        # initialize the importer options for BioFormats
        options = ImporterOptions()
        options.setOpenAllSeries(True)
        options.setShowOMEXML(False)
        options.setConcatenate(True)
        options.setAutoscale(True)
        options.setId(imagefile)
        options.setStitchTiles(True)

        # open the ImgPlus
        imps = BF.openImagePlus(options)
        imp = imps[series]

    # apply the filter
    if filtertype != 'NONE':

        # apply filter
        #log.log(LogLevel.INFO, 'Apply Filter  : ' + filtertype)
        #log.log(LogLevel.INFO, 'Filter Radius : ' + str(filterradius))
        log.info('Apply Filter  : ' + filtertype)
        log.info('Filter Radius : ' + str(filterradius))

        # apply the filter based on the chosen type
        imp = apply_filter(imp,
                           radius=filterradius,
                           filtertype=filtertype)

    if filtertype == 'NONE':
        #log.log(LogLevel.INFO, 'No filter selected. Do nothing.')
        log.info('No filter selected. Do nothing.')

    return imp
Ejemplo n.º 5
0
def concatenateImagePlus(files, outfile):
	"""concatenate images contained in files and save in outfile"""
	'''
	if len(files) == 1:
		IJ.log(files[0] + " has only one time point! Nothing to concatenate!")
		return
	'''
	options = ImporterOptions()
	options.setId(files[0])
	options.setVirtual(1)
	options.setOpenAllSeries(1)
	options.setQuiet(1)
	images = BF.openImagePlus(options)
	imageG = images[0]
	nrPositions = len(images)
	options.setOpenAllSeries(0)

	for i in range(0, nrPositions):
		concatImgPlus = IJ.createHyperStack("ConcatFile", imageG.getWidth(), imageG.getHeight(), imageG.getNChannels(), imageG.getNSlices(), len(files), imageG.getBitDepth())
		concatStack = ImageStack(imageG.getWidth(), imageG.getHeight())
		IJ.showStatus("Concatenating files")
		for file in files:
			try:
				IJ.log("	Add file " + file)
				options.setSeriesOn(i,1)
				options.setId(file)
				image = BF.openImagePlus(options)[0]
				imageStack = image.getImageStack()
				sliceNr = imageStack.getSize()
				for j in range(1, sliceNr+1):
					concatStack.addSlice(imageStack.getProcessor(j))
				image.close()
				options.setSeriesOn(i,0)
			except:
				traceback.print_exc()
				IJ.log(file + " failed to concatenate!")
			IJ.showProgress(files.index(file), len(files))
		concatImgPlus.setStack(concatStack)
		concatImgPlus.setCalibration(image.getCalibration())
		if len(images) > 1:
			outfileP = addPositionName(i+1,outfile)
			IJ.saveAs(concatImgPlus, "Tiff",  outfileP)
		else:
			IJ.saveAs(concatImgPlus, "Tiff",  outfile)
		concatImgPlus.close()
Ejemplo n.º 6
0
def open_czi_series(file_name, series_number, rect=False):
    # see https://downloads.openmicroscopy.org/bio-formats/5.5.1/api/loci/plugins/in/ImporterOptions.html
    options = ImporterOptions()
    options.setId(file_name)
    options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE)
    # select image to open
    options.setOpenAllSeries(False)
    options.setAutoscale(False)
    options.setSeriesOn(series_number, True)
    # default is not to crop
    options.setCrop(False)
    if rect:  # crop if asked for
        options.setCrop(True)
        options.setCropRegion(series_number, Region(rect[0], rect[1], rect[2], rect[3]))
    imps = BF.openImagePlus(options)

    return imps[0]
Ejemplo n.º 7
0
def trans_to_tif(file_list, overwrite = False):
    if file_list is not None:
        for path in file_list:
            opts = ImporterOptions()
            opts.setId(path)
            opts.setVirtual(True)
            opts.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
            opts.setOpenAllSeries(True)

            process = ImportProcess(opts)

            try:
                process.execute()
            except:
                pass
            else:
                process.execute()

            try:
                imps = ImagePlusReader(process).openImagePlus()
            except:
                IJ.log(path + "\n" + "This file was not properly processed")
                pass

            else:
                dir_name = os.path.dirname(path)
                file_name = os.path.basename(os.path.splitext(path)[0])
                save_dir = os.path.join(dir_name, file_name)
                if not os.path.exists(save_dir):
                    os.makedirs(save_dir)

                imps = ImagePlusReader(process).openImagePlus()
                for i, imp in enumerate(imps):
                    save_path = os.path.join(save_dir, file_name + "_pos{}.tif".format(i + 1))

                    if not os.path.exists(save_path):
                        IJ.saveAsTiff(imp, save_path)
                        IJ.freeMemory()
                    else:
                        if overwrite:
                            IJ.saveAsTiff(imp, save_path)
                            IJ.freeMemory()
                        else:
                            pass
Ejemplo n.º 8
0
    def readbf(imagefile, metainfo,
               setflatres=False,
               readpylevel=0,
               setconcat=False,
               openallseries=True,
               showomexml=False,
               autoscale=True,
               stitchtiles=True):

        # initialize the importer options
        options = ImporterOptions()
        options.setOpenAllSeries(openallseries)
        options.setShowOMEXML(showomexml)
        options.setConcatenate(setconcat)
        options.setAutoscale(autoscale)
        options.setId(imagefile)
        options.setStitchTiles(stitchtiles)

        # in case of concat=True all series set number of series = 1
        # and set pyramidlevel = 0 (1st level) since there will be only one
        # unless setflatres = True --> read pyramid levels

        series = metainfo['SeriesCount_BF']
        if setconcat and setflatres:
            series = 1
            readpylevel = 0

        metainfo['Pyramid Level Output'] = readpylevel

        # open the ImgPlus
        imps = BF.openImagePlus(options)

        # read image data using the specified pyramid level
        imp, slices, width, height, pylevel = ImageTools.getImageSeries(imps, series=readpylevel)

        metainfo['Output Slices'] = slices
        metainfo['Output SizeX'] = width
        metainfo['Output SizeY'] = height

        return imp, metainfo
Ejemplo n.º 9
0
def run(imagefile, useBF=True, series=0):

    log.info('Image Filename : ' + imagefile)

    if not useBF:
        # using IJ static method
        imp = IJ.openImage(imagefile)

    if useBF:

        # initialize the importer options
        options = ImporterOptions()
        options.setOpenAllSeries(True)
        options.setShowOMEXML(False)
        options.setConcatenate(True)
        options.setAutoscale(True)
        options.setId(imagefile)

        # open the ImgPlus
        imps = BF.openImagePlus(options)
        imp = imps[series]

    # apply the filter
    if FILTERTYPE != 'NONE':

        # apply filter
        log.info('Apply Filter  : ' + FILTERTYPE)
        log.info('Filter Radius : ' + str(FILTER_RADIUS))

        # apply the filter based on the choosen type
        imp = apply_filter(imp,
                           radius=FILTER_RADIUS,
                           filtertype=FILTERTYPE)

    if FILTERTYPE == 'NONE':
        log.info('No filter selected. Do nothing.')

    return imp
Ejemplo n.º 10
0
def open_fli(filepth):
	# load the dataset
	options = ImporterOptions()
	options.setId(filepth)
	options.setOpenAllSeries(1)
	imps = BF.openImagePlus(options)
	for imp in imps:
		title = imp.getTitle()
		if title.find("Background Image")==-1:
			img = imp
			imp.close()
		else:
			bkg = imp
			imp.close()
	ic =  ImageCalculator()
	img2 = ic.run("Subtract create 32-bit stack",img,bkg)
	#copy the metadata
	props = img.getProperties()
	for prop in props:
		img2.setProperty(prop,props.getProperty(prop))
	img.close()
	bkg.close()
	return img2
Ejemplo n.º 11
0
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..."

    # Use BioFormats reader directly to determine dataset dimensions without
    # reading every single image. The series count (num_images) is the one value
    # we can't easily get any other way, but we might as well grab the others
    # while we have the reader available.
    bfreader = ImageReader()
    bfreader.id = str(filename)
    num_images = bfreader.seriesCount
    num_channels = bfreader.sizeC
    width = bfreader.sizeX
    height = bfreader.sizeY
    bfreader.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 "==========================="

        options = ImporterOptions()
        options.id = str(filename)
        options.setOpenAllSeries(True)
        # concatenate=True gives us a single stack rather than a list of
        # separate images.
        options.setConcatenate(True)
        # Limit the reader to the channel we're currently working on. This loop
        # is mainly why we need to know num_images before opening anything.
        for i in range(num_images):
            options.setCBegin(i, channel)
            options.setCEnd(i, channel)
        # openImagePlus returns a list of images, but we expect just one (a
        # stack).
        input_image = BF.openImagePlus(options)[0]

        # 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!"
Ejemplo n.º 12
0
def imageprojector(channels, timelist_unsorted, dirs):
	""" Projects .lif timepoints and saves in a common directory,
	    as well as channel separated directories. """
	
	# Defines in path
	path = str(Experiment)

	# BF Importer
	options = ImporterOptions()
	
	try:
		options.setId(path)
	except Exception(e):
		print str(e)
		
	options.setOpenAllSeries(True)
	options.setSplitTimepoints(True)
	options.setSplitChannels(True)
	imps = BF.openImagePlus(options)

	timelist = [x for item in timelist_unsorted for x in repeat(item, channels)]
	timelist, imps = zip(*sorted(zip(timelist, imps)))

	
	counter_C0 = -1
	counter_C1 = -1
	counter_C2 = -1
	# Opens all images, splits channels, z-projects and saves to disk
	for imp in (imps):
		# Projection, Sum Intensity
   		project = ZProjector()
		project.setMethod(ZProjector.SUM_METHOD)
		project.setImage(imp)
		project.doProjection()
		impout = project.getProjection()
		projection = impout.getTitle()

		try:
			# Saves channels to disk, 
			# add more channels here if desired, 
			# remember to define new counters.
			if "C=0" in projection:
				counter_C0 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C0).zfill(3) + "C0"))
                
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C0"],
				          "Scan" + str(counter_C0).zfill(3) + "C0"))		
			
			elif "C=1" in projection:
				counter_C1 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C1).zfill(3) + "C1"))
                         
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C1"],
				          "Scan" + str(counter_C1).zfill(3) + "C1"))

			elif "C=2" in projection:
				counter_C2 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C2).zfill(3) + "C2"))
                         
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C2"],
				          "Scan" + str(counter_C2).zfill(3) + "C2"))
		
		except IOException:
			print "Directory does not exist"
			raise

	IJ.log("Images projected and saved to disk")
Ejemplo n.º 13
0
	for m in masks:
	    m.close()
	mergedmask.setTitle(imagetitle + "-"+str(index)+"-mask.tif")
	outputfile = path.join(outdir, mergedmask.getTitle())
	IJ.saveAs(mergedmask, "TIFF", outputfile)

	 
# Main code
inputdir = str(inputdir) # convert from File object to String
outputdir = str(outputdir) # convert from File object to String
if not path.isdir(inputdir):
    print inputdir, " does not exist or is not a directory."
else:
	size = 10000
	imp_options = ImporterOptions()
	imp_options.setOpenAllSeries(True)
	imp_options.setConcatenate(True)
	if not path.isdir(outputdir):
	    # create output directory if it does not exist
		os.makedirs(outputdir)
	filenames = os.listdir(inputdir) # get list of files to process
	imagefiles = [f for f in filenames if f.split(".")[-1] in ['tif','tiff','nd2']]
	# close existing Summary window

	rtframe = WindowManager.getFrame("Summary")
	if rtframe is not None:
		rtframe.close()
	
	for img_file in imagefiles:
	    # execute the following block for each file
		fullpath = path.join(inputdir, img_file)
Ejemplo n.º 14
0
print stages
print folder
print basename
for c in channels:
	for s in stages:
		print basename+"_w"+c+channels[c]+"_s"+s+".stk"
"""

######################### Pre-process image files
# load all series from nd file, optionally create MIP, save merged channel files
# "raw" stitching (with tmp-renamed nd) only if not multichannel and not doMIP or not zstack
if (zstack and doMIP) or multichannel:
	print "Resaving intermediate files"
	options = ImporterOptions()
	options.setId(ndPath)
	options.setOpenAllSeries(True)
	# TODO get number of series and loop over each series instead of opening all at once
	imps = BF.openImagePlus(options)
	pixelWidth = imps[0].getCalibration().pixelWidth
	pixelHeight = imps[0].getCalibration().pixelHeight
	fileNamePattern = basename + "_s{i}.tif"
	for imp in imps:
		m4 = re.match('.+Stage(\d+).+', imp.getTitle())
		savePath = folder + basename + "_s" + m4.group(1) + ".tif"
		if doMIP:
			mip = getMIP(imp)
			imp.close()
			print "Saving MIP as", savePath
			IJ.saveAs(mip, "Tiff", savePath);
			mip.close()
		else:
Ejemplo n.º 15
0
# @File(label="Input file") input
# @File(label="Output folder") output

# Splits multi-point CZI files into multiple TIFFs using Bio-Formats.
#
# Stefan Helfrich (University of Konstaz), 05/09/2016

from ij import IJ
from loci.plugins import BF
from loci.plugins.in import ImporterOptions
import os

srcPath = input.getAbsolutePath()

# using LOCI BioFormats  
settings = ImporterOptions()
settings.setId(srcPath)
settings.setOpenAllSeries(True)
settings.setVirtual(True)
settings.setWindowless(True)

imps = BF.openImagePlus(settings)

for i in range(0, len(imps)):
	currentImp = imps[i]
	filename = os.path.split(srcPath)[1]
	filenameWithoutExtension = os.path.splitext(filename)[0]
	IJ.saveAs(currentImp, "TIFF", output.getAbsolutePath() + "/" + filenameWithoutExtension + "-" + str(i) + ".tif")
Ejemplo n.º 16
0
def bfopenall(path):
	options = ImporterOptions();
	options.setId(path);
	options.setOpenAllSeries(True);
	return BF.openImagePlus(options);
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..."

    options = ImporterOptions()
    options.setId(str(filename))
    options.setOpenAllSeries(True)
    options.setConcatenate(True)
    options.setSplitChannels(True)
    imps = BF.openImagePlus(options)

    num_channels = len(imps)
    w = imps[0].getWidth()
    h = imps[0].getHeight()
    ff_imp = IJ.createImage("Flat-field", w, h, num_channels, 32);
    df_imp = IJ.createImage("Dark-field", w, h, num_channels, 32);

    basic = Basic()
    Basic_noOfSlices = Basic.getDeclaredField('noOfSlices')
    Basic_noOfSlices.setAccessible(True)

    for channel, imp in enumerate(imps):
        title = imp.getTitle()
        print "Processing:", title
        x, y, c, z, t = imp.getDimensions()
        assert z == 1 and c == 1
        imp.setDimensions(1, t, 1)

        WindowManager.setTempCurrentImage(imp)
        Basic_noOfSlices.setInt(basic, t)
        basic.exec(
            imp, None, None,
            "Estimate shading profiles", "Estimate both flat-field and dark-field",
            lambda_estimate, lambda_flat, lambda_dark,
            "Ignore", "Compute shading only"
        )
        ff_channel = WindowManager.getImage('Flat-field:' + title)
        ff_channel.copy()
        ff_imp.setSlice(channel + 1)
        ff_imp.paste()
        ff_channel.close()

        df_channel = WindowManager.getImage('Dark-field:' + title)
        df_channel.copy()
        df_imp.setSlice(channel + 1)
        df_imp.paste()
        df_channel.close()

        imp.close()

    # Setting the active slice back to 1 seems to fix an issue where
    # the last slice was empty in the saved TIFFs. Not sure why.
    ff_imp.setSlice(1)
    df_imp.setSlice(1)

    ff_filename = '%s/%s-ffp-basic.tif' % (output_dir, experiment_name)
    IJ.saveAsTiff(ff_imp, ff_filename)
    ff_imp.show()
    ff_imp.close()

    df_filename = '%s/%s-dfp-basic.tif' % (output_dir, experiment_name)
    IJ.saveAsTiff(df_imp, df_filename)
    df_imp.show()
    df_imp.close()

    print "Done!"