def get_reader(file, inputMeta): options = ImporterOptions() options.setId(file) imps = BF.openImagePlus(options) reader = ImageReader() reader.setMetadataStore(inputMeta) reader.setId(file) return reader
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
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.'
def extractChannel(oirFile, ch): options = ImporterOptions() options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE) options.setId(oirFile) options.setCBegin(0, ch) options.setCEnd(0, ch) #options.setSeriesOn(1,True) imps = BF.openImagePlus(options) ip = imps[0] return(ip)
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 readImageFile(imageFile): #IJ.log(imageFile) #print(imageFile) extension = imageFile.split('.').pop() #Array.pop(). Pratique pour faire une fonction getExtension() options = ImporterOptions() options.setId(imageFile) if extension == "nd": reader = MetamorphReader() else: reader = ImageReader() reader.setId(imageFile) return reader, options
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]
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
def open_image(imgfile): options = ImporterOptions() options.setId(imgfile) options.setSplitChannels(False) options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE) imps = BF.openImagePlus(options) splitimps = [ImagePlus("%s-C-%i" % (imps[0].getTitle(), i),imps[0].getStack().getProcessor(i)) for i in range(1,imps[0].getNChannels()+1)] for si in splitimps: si.setCalibration(imps[0].getCalibration().copy()) return imps[0], splitimps
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
def findclearcell(inDir, currentDir, fileName): print "Opening", fileName file_path= os.path.join(currentDir, fileName) options = ImporterOptions() options.setId(file_path) options.setSplitChannels(True) imps = BF.openImagePlus(options) for imp in imps: imp.show() if not imps: return IJ.selectWindow(fileName + " - C=2") IJ.run("Close") IJ.selectWindow(fileName + " - C=1") IJ.run("Close") IJ.selectWindow(fileName + " - C=0") IJ.run("Close") IJ.selectWindow(fileName + " - C=3") IJ.run("8-bit") IJ.run("Options...", "iterations=1 count=1 black edm=8-bit") IJ.setThreshold(62, 255) IJ.run("Convert to Mask", "method=Default backgorund=Dark black") Macro.setOptions("Stack position") for n in range(4,15): n+=1 IJ.setSlice(n) IJ.run(imp, "Analyze Particles...", "size=7.2-9 circularity=0.7-0.95 display")
def readSingleChannelImg(imgFile): options = ImporterOptions() options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE) options.setId(imgFile) imps = BF.openImagePlus(options) ip = imps[0] return(ip)
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 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
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
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
def main(): root = myDir.getPath() # get the root out the java file object print(root) import os, glob # set up bioformats from loci.plugins import BF from loci.plugins.in import ImporterOptions options = ImporterOptions() options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE) options.setGroupFiles(True) # if the files are named logically if will group them into a stack # this will do the maximum intensity projection from ij.plugin import ZProjector Zproj = ZProjector() for path, subdirs, files in os.walk(root): print(path) # just get the one of the files that matches your image pattern flist = glob.glob(os.path.join(path,"*.tif")) print(len(flist)) if( flist ): file = flist[0] print("Processing {}".format(file)) options.setId(file) imp = BF.openImagePlus(options)[0] # show the image if you want to see it IJ.run(imp, "Grays", "") imp.show() imp_max = Zproj.run(imp,'max') IJ.run(imp_max, "Grays", "") imp_max.show() # save the Z projection IJ.save(imp_max,file.rsplit('_',1)[0]+'_processed.tif')
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
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
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()
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)
chDNA = parser.getint(section, 'chDNA') 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",
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 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]
""" print channels 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);
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()
# @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")
#-*- 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)
layers = [0.235, 0.315, 0.45] labels = ["Top", "Middle", "Bottom"] # Initialize variables for Saving name = ['File'] layer = ['Layer'] results = ['Slice,Count,Total Area,Average Size,%Area'] summary = {"Top": [], "Middle": [], "Bottom": []} # Check if folders are there or not if not os.path.exists(saveDir): os.mkdir(saveDir) # set up options for import opts = ImporterOptions() opts.setId(filename) opts.setUngroupFiles(True) # set up import process process = ImportProcess(opts) process.execute() nseries = process.getSeriesCount() # Channel Splitter Definition splitter = ChannelSplitter() # reader belonging to the import process reader = process.getReader() # reader external to the import process
omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(sipmm_inputFile.getAbsolutePath()) 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)))
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
from ij.gui import PolygonRoi from ij.gui import Roi from ij.plugin import ZProjector, HyperStackConverter from ij.process import ImageStatistics as IS from ij.process import ImageConverter as IC from ij.plugin import Concatenator from net.imagej.axis import Axes from jarray import array from net.imglib2.type.numeric.integer import UnsignedByteType import net.imglib2.type.logic.BitType import net.imglib2.algorithm.neighborhood.HyperSphereShape from net.imglib2.type.numeric.real import FloatType,DoubleType from ij.measure import ResultsTable from net.imagej.ops import Ops from loci.plugins.in import ImporterOptions options = ImporterOptions() options.setId(Input_File.getAbsolutePath()) from loci.formats import ImageReader from loci.formats import MetadataTools #get import ready and import reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(Input_File.getAbsolutePath()) seriesCount = reader.getSeriesCount() reader.close() #open image imp, = BF.openImagePlus(options) #get output path variable outdir=Output_File.getAbsolutePath() #get input path variable
# 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!)
def readbf(imagefile, metainfo, setflatres=False, readpylevel=0, setconcat=False, openallseries=True, showomexml=False, autoscale=True): # initialize the importer options options = ImporterOptions() options.setOpenAllSeries(openallseries) options.setShowOMEXML(showomexml) options.setConcatenate(setconcat) options.setAutoscale(autoscale) options.setId(imagefile) # 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
def readczi(imagefile, stitchtiles=True, setflatres=False, readpylevel=0, setconcat=True, openallseries=True, showomexml=False, attach=False, autoscale=True): log.info('Filename : ' + imagefile) metainfo = {} # checking for thr file Extension metainfo['Extension'] = MiscTools.getextension(MiscTools.splitext_recurse(imagefile)) log.info('Detected File Extension : ' + metainfo['Extension']) # initialize the reader and get the OME metadata reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() #metainfo['ImageCount_OME'] = omeMeta.getImageCount() reader.setMetadataStore(omeMeta) reader.setId(imagefile) metainfo['SeriesCount_BF'] = reader.getSeriesCount() reader.close() # get the scaling for XYZ physSizeX = omeMeta.getPixelsPhysicalSizeX(0) physSizeY = omeMeta.getPixelsPhysicalSizeY(0) physSizeZ = omeMeta.getPixelsPhysicalSizeZ(0) if physSizeX is not None: metainfo['ScaleX'] = round(physSizeX.value(), 3) metainfo['ScaleY'] = round(physSizeX.value(), 3) if physSizeX is None: metainfo['ScaleX'] = None metainfo['ScaleY'] = None if physSizeZ is not None: metainfo['ScaleZ'] = round(physSizeZ.value(), 3) if physSizeZ is None: metainfo['ScaleZ'] = None options = DynamicMetadataOptions() options.setBoolean("zeissczi.autostitch", stitchtiles) options.setBoolean("zeissczi.attachments", attach) czireader = ZeissCZIReader() czireader.setFlattenedResolutions(setflatres) czireader.setMetadataOptions(options) czireader.setId(imagefile) # 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()) # metainfo = {} metainfo['rescount'] = czireader.getResolutionCount() metainfo['SeriesCount_CZI'] = czireader.getSeriesCount() #metainfo['flatres'] = czireader.hasFlattenedResolutions() #metainfo['getreslevel'] = czireader.getResolution() # Dimensions metainfo['SizeT'] = czireader.getSizeT() metainfo['SizeZ'] = czireader.getSizeZ() metainfo['SizeC'] = czireader.getSizeC() metainfo['SizeX'] = czireader.getSizeX() metainfo['SizeY'] = czireader.getSizeY() # check for autostitching and possibility to read attachment metainfo['AllowAutoStitching'] = czireader.allowAutostitching() metainfo['CanReadAttachments'] = czireader.canReadAttachments() # read in and display ImagePlus(es) with arguments options = ImporterOptions() options.setOpenAllSeries(openallseries) options.setShowOMEXML(showomexml) options.setConcatenate(setconcat) options.setAutoscale(autoscale) options.setId(imagefile) # open the ImgPlus imps = BF.openImagePlus(options) metainfo['Pyramid Level Output'] = readpylevel + 1 try: imp = imps[readpylevel] pylevelout = metainfo['SeriesCount_CZI'] except: # fallback option log.info('PyLevel=' + str(readpylevel) + ' does not exist.') log.info('Using Pyramid Level = 0 as fallback.') imp = imps[0] pylevelout = 0 metainfo['Pyramid Level Output'] = pylevelout # get the stack and some info imgstack = imp.getImageStack() metainfo['Output Slices'] = imgstack.getSize() metainfo['Output SizeX'] = imgstack.getWidth() metainfo['Output SizeY'] = imgstack.getHeight() # calc scaling in case of pyramid scale = float(metainfo['SizeX']) / float(metainfo['Output SizeX']) metainfo['Pyramid Scale Factor'] = scale metainfo['ScaleX Output'] = metainfo['ScaleX'] * scale metainfo['ScaleY Output'] = metainfo['ScaleY'] * scale # set the correct scaling imp = MiscTools.setscale(imp, scaleX=metainfo['ScaleX Output'], scaleY=metainfo['ScaleX Output'], scaleZ=metainfo['ScaleZ'], unit="micron") # close czireader czireader.close() return imp, metainfo
#Define results output folder folder = input_folder+"timepoints/" if not os.path.exists(folder): os.mkdir(folder) # collect list of files to be processed #file_list = [filename for filename in os.listdir(input_folder) if ".tif" in filename] # Recursive option file_list = [os.path.join(dp, f) for dp, dn, fn in os.walk(input_folder) for f in fn if '.tif' in f] for file_path in file_list: # read in and display ImagePlus(es) with arguments options = ImporterOptions() options.setId(file_path) options.setSplitTimepoints(True) imps = BF.openImagePlus(options) for imp in imps: imp.show() name = imp.getTitle() details = name.split("_")[0] print file_path pos = details.split('Pos')[1] time = name.split("=")[1] image_type = re.split(r'.lif |- |_|\\', file_path)[-3] mutant = re.split(r'.lif |- |_|\\', file_path)[-6] cotrans = re.split(r'.lif |- |_|\\', file_path)[-5] new_name = mutant+"_"+cotrans+"_pos_"+pos+"_t_"+time+"_"+image_type
zpimp = zp.getProjection() return zpimp def saveMip(img, file_path): if mipPrefTIFF: FileSaver(img).saveAsTiff(file_path + ".tiff") if mipPrefJPG: FileSaver(img).saveAsJpeg(file_path + ".jpg") for root, dirs, files in os.walk(inDir): for file in files: if file.endswith(fileExt): logging.info('Starting image #%i (%s)', imageCount, str(file)) options = ImporterOptions() options.setAutoscale(True) options.setId(os.path.join(root, file)) options.setSplitChannels(True) imps = BF.openImagePlus(options) imageCount += 1 for imp in imps: reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(os.path.join(root, file)) filename = str(imp) channel_id = int(re.findall("C=(\d)", filename)[0]) channel_name = omeMeta.getChannelName(0, channel_id) out_name = filename.split('"')[1]
def __init__(self, filepath): """ Load an image or stack from filepath. Args: filepath (str): Full path to an image file. Can be .tif, .lsm, .czi, etc """ if not os.path.isfile(filepath): bPrintLog('ERROR: bImp() did not find file: ' + filepath,0) return 0 self.filepath = filepath folderpath, filename = os.path.split(filepath) self.filename = filename self.enclosingPath = folderpath self.enclosingfolder = os.path.split(folderpath)[1] self.dateStr = '' self.timeStr = '' self.imp = None tmpBaseName, extension = os.path.splitext(filename) isZeiss = extension in ['.czi', '.lsm'] self.islsm = extension == '.lsm' self.isczi = extension == '.czi' istif = extension == '.tif' if istif: # scanimage3 comes in with dimensions: [512, 512, 1, 52, 1]) = [width, height, numChannels, numSlices, numFrames] self.imp = Opener().openImage(filepath) self.imp.show() elif isZeiss: #open lsm using LOCI Bio-Formats options = ImporterOptions() #options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE) options.setId(filepath) imps = BF.openImagePlus(options) for imp in imps: self.imp = imp #WindowManager.getImage(self.windowname) imp.show() if not self.imp: bPrintLog('ERROR: bImp() was not able to open file: '+ filepath,0) self.windowname = filename #self.imp = WindowManager.getImage(self.windowname) # numChannels is not correct for scanimage, corrected in readTiffHeader() (width, height, numChannels, numSlices, numFrames) = self.imp.getDimensions() self.width = width # pixelsPerLine self.height = height # linesPerFrame self.numChannels = numChannels self.numSlices = numSlices self.numFrames = numFrames self.infoStr = self.imp.getProperty("Info") #get all tags self.voxelx = 1 self.voxely = 1 self.voxelz = 1 #self.numChannels = 1 #self.bitsPerPixel = 8 self.zoom = 1 self.motorx = None self.motory = None self.motorz = None self.scanImageVersion = '' self.msPerLine = None self.dwellTime = None # read file headers (date, time, voxel size) if isZeiss: self.readZeissHeader(self.infoStr) elif istif: self.readTiffHeader(self.infoStr) self.updateInfoStr() self.channelWindows = [] self.channelImp = [] if self.numChannels == 1: self.channelWindows.append(self.windowname) self.channelImp.append(self.imp) else: self.deinterleave()
metadata = '/Volumes/LaCie_DataStorage/xiaochao_wei_STORM imaging/STORM_imaging/analysis_test/metadata' ''' # parse metadata from loci.formats import ImageReader from loci.formats import MetadataTools reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(filepath) SizeT = reader.getSizeT() reader.close() print(SizeT) ''' # load bio-format from loci.plugins import BF from loci.plugins.in import ImporterOptions options = ImporterOptions() # options.setTBegin(0, SizeT) # options.setTEnd(0, SizeT + 5) options.setId(filepath) # open image imps = BF.openImagePlus(filepath) for imp in imps: imp.show()