Ejemplo n.º 1
0
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.º 2
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.º 3
0
def open_msr(input_file):
    options = ImporterOptions()
    options.setId(input_file)
    #options.clearSeries()
    for s in [3,4,5]:
        options.setSeriesOn(s, True)
    imps = BF.openImagePlus(options)

    imp1 = imps[1]
    imp2 = imps[0]
    imp3 = imps[2] 
    
    return imp1, imp2, imp3
Ejemplo n.º 4
0
def open_czi(filepath,series):
    from loci.plugins import BF
    from loci.plugins.in import ImporterOptions
    from loci.common import Region
    options = ImporterOptions()
    options.setId( filepath )
    options.setSeriesOn(series-1,True)
    imp = BF.openImagePlus(options)[0]

    cal=imp.getCalibration()

    cal.pixelWidth  = cal.pixelWidth*2 **(series)
    cal.pixelHeight = cal.pixelHeight*2**(series)
    return imp    
Ejemplo n.º 5
0
def open_msr(input_file):
    IJ.log("Reading images from {}".format(input_file))
    options = ImporterOptions()
    options.setId(input_file)
    #options.clearSeries()
    for s in [2,3,4,5]:
        options.setSeriesOn(s, True)
    imps = BF.openImagePlus(options)

    if len(imps) == 4:
        imp1 = imps[2]
        imp2 = imps[1]
        imp3 = imps[3] 
    elif len(imps) == 2:
        IJ.log(" -- Only two channels found. Replicating first as third.")
        imp1 = imps[1]
        imp2 = imps[0]
        imp3 = imps[0]
    else:
        raise RuntimeError("unknown channels")


    widths  = set([imp1.width, imp2.width, imp3.width])
    heights = set([imp1.height, imp2.height, imp3.height])

    if len(widths) > 1 or len(heights) > 1:
        new_width = max(widths)
        new_height = max(heights)

        IJ.log(" -- Resolution of images does not match. Resampling to highest resolution: {} x {}".format(new_width, new_height))
        
        cal = imp1.getCalibration()
        
        imp1 = imp1.resize(new_width, new_height, "bilinear")
        imp2 = imp2.resize(new_width, new_height, "bilinear")
        imp3 = imp3.resize(new_width, new_height, "bilinear")

        imp1.setCalibration(cal)
        imp2.setCalibration(cal)
        imp3.setCalibration(cal)

        
        

    
       
    
    return imp1, imp2, imp3
Ejemplo n.º 6
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.º 7
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]
def set_options(image, series = None):
	"""
	creates ImporterOptions object and sets options
	returns the imps object
	"""
	if series is not None:
		options = ImporterOptions()
		options.setId(image)
		options.setSeriesOn(s,True)
		imps = BF.openImagePlus(options)
		return imps
	else:
		print("no series found")
		options = ImporterOptions()
		options.setId(image)
		imps = BF.openImagePlus(options)
		return imps
Ejemplo n.º 9
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)
def choose_series(filepath, params):
	"""if input file contains more than one image series (xy position), prompt user to choose which one to use"""
	# todo: if necessary (e.g. if lots of series), can improve thumbnail visuals based loosely on https://github.com/ome/bio-formats-imagej/blob/master/src/main/java/loci/plugins/in/SeriesDialog.java
	import_opts = ImporterOptions();
	import_opts.setId(filepath);
	
	reader = ImageReader();
	ome_meta = MetadataTools.createOMEXMLMetadata();
	reader.setMetadataStore(ome_meta);
	reader.setId(filepath);
	no_series = reader.getSeriesCount();
	if no_series == 1:
		return import_opts, params;
	else:
		series_names = [ome_meta.getImageName(idx) for idx in range(no_series)];
		dialog = GenericDialog("Select series to load...");
		dialog.addMessage("There are multiple series in this file! \n" + 
						"This is probably because there are multiple XY stage positions. \n " + 
						"Please choose which series to load: ");
		thumbreader = BufferedImageReader(reader);
		cbg = CheckboxGroup();
		for idx in range(no_series):
			p = Panel();
			p.add(Box.createRigidArea(Dimension(thumbreader.getThumbSizeX(), thumbreader.getThumbSizeY())));
			ThumbLoader.loadThumb(thumbreader, idx, p, True);
			dialog.addPanel(p);
			cb = Checkbox(series_names[idx], cbg, idx==0);
			p.add(cb);

		dialog.showDialog();
		if dialog.wasCanceled():
			raise KeyboardInterrupt("Run canceled");
		if dialog.wasOKed():
			selected_item = cbg.getSelectedCheckbox().getLabel();
			selected_index = series_names.index(selected_item);
			params.setSelectedSeriesIndex(selected_index);
			for idx in range(0, no_series):
				import_opts.setSeriesOn(idx, True) if (idx==selected_index) else import_opts.setSeriesOn(idx, False);
	reader.close();
	return import_opts, params
Ejemplo n.º 11
0
# Channel Splitter Definition
splitter = ChannelSplitter()
 
# reader belonging to the import process
reader = process.getReader()
 
# reader external to the import process
impReader = ImagePlusReader(process)

# loop through all series in file
for i in range(0, nseries):
	print "%d/%d %s" % (i+1, nseries, process.getSeriesLabel(i)[10:])
     
	# 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()

	# deactivate series for next round (otherwise will re-analyze everything)
	opts.setSeriesOn(i, False)

	# run analysis on active series for all images in stack
	for imp in imps:
		channels = splitter.split(imp)
		
		for c in channels:
Ejemplo n.º 12
0
        if ns==-1 and process.getSeriesCount()==1:
            print "Weird..."
            ns=0
        else:
            pn = i.split("_Pos")[-1].split(".")[0]
            print "Inferred position number:", pn
            for j in range(process.getSeriesCount()):
                if "_Pos"+str(int(pn)) in process.getSeriesLabel(j):
                    ns=j
                    break
            if ns==-1:
                print process.getSeriesCount()
                print [process.getSeriesLabel(i) for i in range(process.getSeriesCount())]
                print "GRAVE ERROR!"
                sys.exit(1)
        opt.setSeriesOn(0,False)
        opt.setSeriesOn(ns,True)
        print "-- Opening "+process.getSeriesLabel(ns)
        im = BF.openImagePlus(opt)
        opt.setSeriesOn(ns,False)
        imp = im[-1]
        imL.append(imp)

nch=None
for i in imL:
    print i.getTitle(), i.getNSlices(), i.getNChannels(), i.getNFrames()
    if chl is None:
       if nch is None:
           nch = i.getNChannels()
       elif i.getNChannels() != nch:
           raise TypeError("Not all the files have the same sumber of channels, and --channels=all was specified")
Ejemplo n.º 13
0
seriesCount = reader.getSeriesCount()
reader.close()

log('Found {} series'.format(seriesCount))

outfile = os.path.join(outdir,'results.csv')
h = 'Name,path,Rarea,Rmean,Rstd,Garea,Gmean,Gstd,GQarea,GQmean,GQintden,GQstd,nPunctae,RMregions,maxp,extravar'
with open(outfile,'a') as of:
		of.write(h+'\n')

for impi in range(seriesCount):
	log('Analyzing series {}/{}...'.format(impi+1,seriesCount))
	options = ImporterOptions()
	options.setId(sipmm_inputFile.getAbsolutePath())
	options.clearSeries()
	options.setSeriesOn(impi,True)

	imp, = BF.openImagePlus(options)

	#Separate Green, Red
	chans = ChannelSplitter.split(imp)
	if two_channels:
		if len(chans)!=2:
			log('ERROR! Expecting a 2-channel images and got {}'.format(len(chans)))
		green, red = chans
	else:
		if len(chans)!=3:
			log('ERROR! Expecting a 3-channel images and got {}'.format(len(chans)))
		green, red, nuc = chans
		
	
				nYTiles = nYTiles + 1
			for y in range(nYTiles):
				for x in range(nXTiles):
					# Calculate the correct size and offset for each tile
					tileX = x * tileSizeX
					tileY = y * tileSizeY
					effTileSizeX = tileSizeX * currentScale
					if ((tileX * currentScale) + effTileSizeX) >= width:
						effTileSizeX = width - (tileX * currentScale)
					effTileSizeY = tileSizeY * currentScale
					if ((tileY * currentScale) + effTileSizeY) >= height:
						effTileSizeY = height - (tileY * currentScale)

					# Read the tile, create the downsampled version and then write to output
					tile = reader.openBytes(image, tileX * currentScale, tileY * currentScale, effTileSizeX, effTileSizeY)
					downsample = scaler.downsample(tile, effTileSizeX, effTileSizeY, currentScale, FormatTools.getBytesPerPixel(type), reader.isLittleEndian(), 
					    FormatTools.isFloatingPoint(type), reader.getRGBChannelCount(), reader.isInterleaved())
					writer.saveBytes(image, downsample, tileX, tileY, effTileSizeX / currentScale, effTileSizeY / currentScale)

writer.close();
reader.close();

IJ.log("Done")

options = ImporterOptions()
options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
options.setId(outFile)
options.setSeriesOn(2, True);
imps = BF.openImagePlus(options)
for imp in imps:
    imp.show()