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.º 2
0
def run_headless(filename, channel, target_folder = None, frames = None):
	
	importOpt = ImporterOptions()
	importOpt.setId(filename)
	importOpt.setVirtual(1)
	try:
		imp = BF.openImagePlus(importOpt)[0]
	except IOError, err:
		IJ.showMessage("Not able to open " + filename + " " +str(err))
def run(debug=False):
    srcDir = DirectoryChooser("Batch Splitter: Chose Source Dir").getDirectory()
    # print srcDir
    # print type(srcDir)
    if srcDir is None:
        return

    sumf = open(os.path.join(srcDir, 'summary.z.txt'), 'w')
    # fn = r'e:\Data\data\zby\imaging\20140627.imaging.alignment.z\526-4eGH146GC3-mCherry001.nd2'
    # # fn = r'e:\Data\data\zby\imaging\20140627.imaging.alignment.z\526-4eGH146GC3-mCherry011.nd2'
    # outfn = r'e:\Data\data\zby\imaging\20140627.imaging.alignment.z\526-4eGH146GC3-mCherry001.txt'

    zString = ["Z position for position, plane #01", "Z position for position, plane #001", "Z position for position #1, plane #1", "dZStep", "dZLow", "dZPos", "dZHigh"]

    for fn in os.listdir(srcDir):
        # Skip non-ND2 files
        if not fn.endswith(".nd2"):
            continue

        # get input and output filenames
        fullfn = os.path.join(srcDir, fn)
        outfn = os.path.splitext(fn)[0] + ".z.txt"
        fulloutfn = os.path.join(srcDir, outfn)
        # if os.path.exists(fulloutfn):
        #     print "Skipped, already exists: ", outfn
        #     continue

        print "Reading ", fn
        sumf.write(fn)
        sumf.write('\n')
        op = ImporterOptions()
        op.setId(fullfn)
        process = ImportProcess(op)
        process.execute()
        meta = process.getOriginalMetadata()

        print "Writing", fulloutfn
        # if debug:
            # print meta.getMetadataString('\t')
            # f.write('\n')
        f = open(fulloutfn, 'w')
        for k in meta.keySet():
            if debug and 'Z' in k:
                line = ''.join([k, '\t', str(meta[k])])
                f.write(line)
                f.write('\n')
            if k in zString:
                line = ''.join([k, '\t', str(meta[k])])
                f.write(line)
                f.write('\n')
                sumf.write(line)
                sumf.write('\n')                
        f.close()
        sumf.write('\n')
    sumf.close()
    print 'done.'
Ejemplo n.º 4
0
def createOutputData( jobs ):
    """ Reads out the meta data.
    """
    failedImages = []
    nJobs = len( jobs )
    for n, j in enumerate( jobs ):
        print( "Job " + str(n+1) + "/" + str( nJobs ) )
        # load every image
        metadata = []
        nImages = len( j.sourceImages )
        nChannels = -1
        for m, img in enumerate( j.sourceImages ):
            print( "\tReading image " + str(m+1) + "/" + str( nImages ) )
            imgPath = os.path.join( j.sourcePath, img )
            options = ImporterOptions()
            options.setId( imgPath )
            options.setSplitChannels( False )
            options.setWindowless( True )
            options.setVirtual( True )
            imps = BF.openImagePlus( options )
            if len(imps) == 0:
                failedImages.append( imgPath )
                print("t\tCould not load image: " + imgPath)
                continue
            # get the meta data
            data = imps[0]
            if nChannels == -1:
                nChannels = data.getNChannels() 
            imgInfo = Info();
            info = imgInfo.getImageInfo( data, data.getChannelProcessor() )
            metadata.append( imgPath )
            metadata.append( info )
        j.outputData = '\n\n>>> next source file >>>\n\n'.join( metadata )
        j.numChannels = nChannels
def open_from_lif_series(fpath, i):
  options = ImporterOptions()
  options.setId(fpath)
  options.clearSeries()
  options.setSeriesOn(i, True)
  imps = BF.openImagePlus(options)
  return imps[0]
Ejemplo n.º 6
0
def iterateLif(filename,impProcessor):
    """
    Iterate over all series in a LIF file and process them.
    Arguments:
    filename: LIF filename
    impProcessor: processor object, implements method process(ImagePlus).
    """

    opts = ImporterOptions()
    opts.setId(filename)
    opts.setUngroupFiles(True)

    # set up import process
    process = ImportProcess(opts)
    process.execute()
    nseries = process.getSeriesCount()

    # reader belonging to the import process
    reader = process.getReader()

    # reader external to the import process
    impReader = ImagePlusReader(process)
    for i in range(0, nseries):
        print "iterateLif: %d/%d %s" % (i+1, nseries, process.getSeriesLabel(i))

        # activate series (same as checkbox in GUI)
        opts.setSeriesOn(i,True)

        # point import process reader to this series
        reader.setSeries(i)

        # read and process all images in series
        imps = impReader.openImagePlus()
        for imp in imps:
            imp.setTitle("%s_%d_%d" % (imp.getTitle(),i+1,nseries))
            print "iterateLif: " + imp.getTitle()
            try:
                impProcessor.process(imp)
            finally:
                imp.close()

        # deactivate series (otherwise next iteration will have +1 active series)
        opts.setSeriesOn(i, False)
Ejemplo n.º 7
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.º 8
0
def processMovie(root, files, outfile):
    """Concatenate images and write ome.tiff file.
    If image contains already multiple time points just copy the image"""

    files.sort()

    options = ImporterOptions()
    options.setId(files[0])
    options.setVirtual(1)

    image = BF.openImagePlus(options)
    image = image[0]
    if image.getNFrames() > 1:
        msg = ("%s Contains multiple time points. Can only concatenate"
               " single time points!" %files[0])
        raise RuntimeError(msg)
        image.close()

    reader = ImageReader()
    reader.setMetadataStore(MetadataTools.createOMEXMLMetadata())
    reader.setId(files[0])
    timeInfo = []
    omeOut = reader.getMetadataStore()
    omeOut = setUpXml(omeOut, image, files)
    reader.close()
    image.close()
    itime = 0

    for fileName in files:
        omeMeta = MetadataTools.createOMEXMLMetadata()
        reader.setMetadataStore(omeMeta)
        reader.setId(fileName)
        timeInfo.append(getTimePoint(reader, omeMeta))

        nrImages = reader.getImageCount()
        for i in range(0, reader.getImageCount()):
            try:
                dT = round(timeInfo[files.index(fileName)]-timeInfo[0],2)
            except:
                dT = (timeInfo[files.index(fileName)]-timeInfo[0]).seconds
            omeOut.setPlaneDeltaT(dT, 0, i + itime*nrImages)
            omeOut.setPlanePositionX(omeOut.getPlanePositionX(0,i), 0, i + itime*nrImages)
            omeOut.setPlanePositionY(omeOut.getPlanePositionY(0,i), 0, i + itime*nrImages)
            omeOut.setPlanePositionZ(omeOut.getPlanePositionZ(0,i), 0, i + itime*nrImages)
            omeOut.setPlaneTheC(omeOut.getPlaneTheC(0,i), 0, i + itime*nrImages)
            omeOut.setPlaneTheT(omeOut.getPlaneTheT(0,i), 0, i + itime*nrImages)
            omeOut.setPlaneTheZ(omeOut.getPlaneTheZ(0,i), 0, i + itime*nrImages)
        itime = itime + 1
        reader.close()

        IJ.showProgress(files.index(fileName), len(files))

    try:
        omeOut.setPixelsTimeIncrement(float(dT/(len(files)-1)), 0)
    except:
        omeOut.setPixelsTimeIncrement(0, 0)

    if len(files) <= 1:
        raise RuntimeError('Found only one file. Nothing to concatenate')

    outfile = concatenateImagePlus(files, outfile)
    filein = RandomAccessInputStream(outfile)
    fileout = RandomAccessOutputStream(outfile)
    saver = TiffSaver(fileout, outfile)
    saver.overwriteComment(filein, omeOut.dumpXML())
    fileout.close()
    filein.close()
from ij import IJ
from ij.io import DirectoryChooser
import os
from loci.plugins import BF
from loci.plugins.in import ImporterOptions

inputFolder = DirectoryChooser('Set input directory.').getDirectory()
outputFolder = DirectoryChooser('Set output directory.').getDirectory()
for filename in os.listdir(inputFolder):
	if '.zvi' in filename:
		
		id = inputFolder +'/'+ filename;
		options = ImporterOptions();
		options.setId(id);
		options.setAutoscale(True);
		options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE);
		
		image = BF.openImagePlus(options)[0];
		nameWithoutExt = os.path.splitext(filename)[0]
		# Export the image
		save_path =  outputFolder +'/' + nameWithoutExt + '.ome.tif'
		IJ.run(image, "Bio-Formats Exporter", "save=" + save_path + " compression=Uncompressed");
		image.close()
def openCroppedImageUsingBF(filepath,x,y,xw,yw,zs,ze, crop):
  # read in and display ImagePlus(es) with arguments
  options = ImporterOptions()
  options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE)
  if crop:
    options.setCrop(True)
    options.setCropRegion(0, Region(x,y,xw,yw))
    options.setTBegin(0, zs)
    options.setTEnd(0, ze)
  options.setId(filepath)
  imps = BF.openImagePlus(options)
  return imps[0]
Ejemplo n.º 11
0
import sys
from ij import IJ as ij
from ij.plugin.frame import RoiManager
from ij.gui import Roi, PolygonRoi 

from loci.plugins import BF
from loci.common import Region
from loci.plugins.in import ImporterOptions
from loci.formats import ImageReader, ImageWriter
from loci.formats import MetadataTools
from ome.xml.meta import OMEXMLMetadata

file = "%s"

options = ImporterOptions()
options.setId(file)
imps = BF.openImagePlus(options)

reader = ImageReader()
omeMeta = MetadataTools.createOMEXMLMetadata()
reader.setMetadataStore(omeMeta)
reader.setId(file)

roiCount = omeMeta.getROICount()

if roiCount > 1:
    sys.exit(0)

omeMetaStr =  omeMeta.dumpXML()
shape = omeMeta.getShapeType(0,0)
Ejemplo n.º 12
0
# from https://gist.githubusercontent.com/ctrueden/6282856/raw/6641abc2ae0fd13c6390ef3880fbeee6188edfef/bio-formats.py
# read in and display ImagePlus object(s)
from loci.plugins import BF
file = "/Users/curtis/data/tubhiswt4D.ome.tif"
imps = BF.openImagePlus(file)
for imp in imps:
    imp.show()

# read in and display ImagePlus(es) with arguments
from loci.common import Region
from loci.plugins.in import ImporterOptions
options = ImporterOptions()
options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE)
options.setCrop(True)
options.setCropRegion(0, Region(15, 25, 50, 70))
options.setId(file)
imps = BF.openImagePlus(options)
for imp in imps:
    imp.show()

# parse metadata
from loci.formats import ImageReader
from loci.formats import MetadataTools
reader = ImageReader()
omeMeta = MetadataTools.createOMEXMLMetadata()
reader.setMetadataStore(omeMeta)
reader.setId(file)
seriesCount = reader.getSeriesCount()
reader.close()

# print out series count from two different places (they should always match!)