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 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 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)
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()
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
pixXY = parser.getfloat(section, 'pixXY') stepZ = parser.getfloat(section, 'stepZ') rect = ast.literal_eval(parser.get(section, 'rect')) if followLocus: if chDNA>1: chDNA-=1 else: chDNA=2 ## === Open as a BioFormats image stack ## Inspired from: https://forum.image.sc/t/virtual-stack-bioformats-macro-command/23134 #of = "/data/CoulonLab/CoulonLab Dropbox/data/Maxime/Laura/20190415/20191107/concatenated_Pos27DC.ome.tif" #fn = "/data/CoulonLab/CoulonLab Dropbox/data/Maxime/Laura/20190415/20191107/concatenated_Pos27.ome.tif" opt = ImporterOptions() opt.setVirtual(True) opt.setId(fn) im = BF.openImagePlus(opt) imp = im[0] if imp is None: print "Could not open image from file:" IJ.log("title: %s" % imp.title) IJ.log("width: %i" % imp.width) IJ.log("height: %i" % imp.height) IJ.log("number of slices: %i" % imp.getNSlices()) IJ.log("number of channels: %i" % imp.getNChannels()) IJ.log("number of time frames: %i" % imp.getNFrames()) IJ.log("the channel to track is channel %i" % chDNA) types = {ij.ImagePlus.COLOR_RGB : "RGB", ij.ImagePlus.GRAY8 : "8-bit",
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()
#-*- coding:utf-8 -*- ## Fiji Macro to concatenate stacks ## Takes the paths to concatenate as input arguments import sys, os from ij import IJ import ij.gui from java.awt import Font from ij.plugin import Duplicator, Concatenator, SubHyperstackMaker from loci.plugins import BF from loci.plugins.in import ImporterOptions, ImportProcess opt = ImporterOptions() opt.setVirtual(False) ## Constants useBF=False ## Set to True to open files using Bio-Formats types = {ij.ImagePlus.COLOR_RGB : "RGB", ij.ImagePlus.GRAY8 : "8-bit", ij.ImagePlus.GRAY16 : "16-bit", ij.ImagePlus.GRAY32 : "32-bit", ij.ImagePlus.COLOR_256 : "8-bit color"} ## === File checks lf = sys.argv[1:-3] of = sys.argv[-3] # output file tf = sys.argv[-2] # Address of the file of timestamps ch = sys.argv[-1] if not ch.startswith("--channels="): print "Last parameter should be either `--channels=all` or `--channels=[list of channel indices]" sys.exit(1)
# @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")
def process_time_points(root, files, outdir): '''Concatenate images and write ome.tiff file. If image contains already multiple time points just copy the image''' concat = 1 files.sort() options = ImporterOptions() options.setId(files[0]) options.setVirtual(1) image = BF.openImagePlus(options) image = image[0] if image.getNFrames() > 1: IJ.log(files[0] + " Contains multiple time points. Can only concatenate single time points! Don't do anything!") image.close() return width = image.getWidth() height = image.getHeight() for patt in pattern: outName = re.match(patt, os.path.basename(files[0])) if outName is None: continue if outdir is None: outfile = os.path.join(root, outName.group(1) + '.ome.tif') else: outfile = os.path.join(outdir, outName.group(1) + '.ome.tif') reader = ImageReader() reader.setMetadataStore(MetadataTools.createOMEXMLMetadata()) reader.setId(files[0]) timeInfo = [] omeOut = reader.getMetadataStore() omeOut = setUpXml(omeOut, image, files) reader.close() image.close() IJ.log ('Concatenates ' + os.path.join(root, outName.group(1) + '.ome.tif')) itime = 0 try: for ifile, fileName in enumerate(files): print fileName omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(fileName) #print omeMeta.getPlaneDeltaT(0,0) #print omeMeta.getPixelsTimeIncrement(0) if fileName.endswith('.czi'): if ifile == 0: T0 = omeMeta.getPlaneDeltaT(0,0).value() dT = omeMeta.getPlaneDeltaT(0,0).value() - T0 unit = omeMeta.getPlaneDeltaT(0,0).unit() else: timeInfo.append(getTimePoint(reader, omeMeta)) unit = omeMeta.getPixelsTimeIncrement(0).unit() try: dT = round(timeInfo[files.index(fileName)]-timeInfo[0],2) except: dT = (timeInfo[files.index(fileName)]-timeInfo[0]).seconds nrImages = reader.getImageCount() for i in range(0, reader.getImageCount()): try: omeOut.setPlaneDeltaT(dT, 0, i + itime*nrImages) except TypeError: omeOut.setPlaneDeltaT(Time(dT, unit),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(NonNegativeInteger(itime), 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: incr = float(dT/(len(files)-1)) except: incr = 0 try: omeOut.setPixelsTimeIncrement(incr, 0) except TypeError: #new Bioformats >5.1.x omeOut.setPixelsTimeIncrement(Time(incr, unit),0) outfile = concatenateImagePlus(files, outfile) if outfile is not None: filein = RandomAccessInputStream(outfile) fileout = RandomAccessOutputStream(outfile) saver = TiffSaver(fileout, outfile) saver.overwriteComment(filein,omeOut.dumpXML()) fileout.close() filein.close() except: traceback.print_exc() finally: #close all possible open files try: reader.close() except: pass try: filein.close() except: pass try: fileout.close() except: