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 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]
def readSingleChannelImg(imgFile): options = ImporterOptions() options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE) options.setId(imgFile) imps = BF.openImagePlus(options) ip = imps[0] return(ip)
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
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 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 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 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 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]
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 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 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 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
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 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 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_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 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 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 import_image(filename, color_mode='color', split_c=False, split_z=False, split_t=False): """Open an image file using the Bio-Formats importer. Parameters ---------- filename : str The full path to the file to be imported through Bio-Formats. color_mode : str, optional The color mode to be used for the resulting ImagePlus, one of 'color', 'composite', 'gray' and 'default'. split_c : bool, optional Whether to split the channels into separate ImagePlus objects. split_z : bool, optional Whether to split the z-slices into separate ImagePlus objects. split_t : bool, optional Whether to split the time points into separate ImagePlus objects. Returns ------- ij.ImagePlus[] A list of ImagePlus objects resulting from the import. """ options = ImporterOptions() mode = { 'color' : ImporterOptions.COLOR_MODE_COLORIZED, 'composite' : ImporterOptions.COLOR_MODE_COMPOSITE, 'gray' : ImporterOptions.COLOR_MODE_GRAYSCALE, 'default' : ImporterOptions.COLOR_MODE_DEFAULT, } options.setColorMode(mode[color_mode]) options.setSplitChannels(split_c) options.setSplitFocalPlanes(split_z) options.setSplitTimepoints(split_t) options.setId(filename) log.info("Reading [%s]", filename) orig_imps = BF.openImagePlus(options) log.debug("Opened [%s] %s", filename, type(orig_imps)) return orig_imps
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
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 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
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 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
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()
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 inpu=Input_File.getAbsolutePath()
#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 print new_name
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)
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 impReader = ImagePlusReader(process)
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()
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", ij.ImagePlus.GRAY16 : "16-bit",
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); mip.close()
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()