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 readCZIattachment(imagefile, stitchtiles=False, setflatres=False, readpylevel=0, setconcat=False, openallseries=False, showomexml=False, attach=False, autoscale=True): # define the reader options reader_options, czireader = ImportTools.setReaderOptions(imagefile, stitchtiles=stitchtiles, setflatres=setflatres, setconcat=setconcat, openallseries=openallseries, showomexml=showomexml, attach=attach, autoscale=autoscale) # open the ImgPlus imps_attach = BF.openImagePlus(reader_options) # read image data using the specified pyramid level imp_attach, slices, width, height, pylevel = ImageTools.getImageSeries(imps_attach, series=readpylevel) czireader.close() return imp_attach
def openjpg(imagefile, metainfo, method='IJ', series=0): if method == 'IJ': # using IJ static method imp = IJ.openImage(imagefile) if method == 'Opener': # Using Opener class imp = Opener().openImage(imagefile) if method == 'BF': # using BioFormats library imps = BF.openImagePlus(imagefile) # read image data using the specified pyramid level imp, slices, width, height, pylevel = ImageTools.getImageSeries(imps, series=series) metainfo['Output Slices'] = slices metainfo['Output SizeX'] = width metainfo['Output SizeY'] = height return imp, metainfo
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 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 showimage(self): roim = RoiManager.getInstance() if roim is None: roim = RoiManager() IJ.run("Close All") IJ.run("Clear Results") try: roim.reset() except AttributeError: roim.runCommand("reset") obj = self.fcsimages[self.idximg][0] imgName = self.fcsimages[self.idximg][1] img = BF.openImagePlus(imgName)[0] img.setZ(obj[1][2]+1) img.setC(3) IJ.run(img, "Grays", ""); img.setC(1) img.show() #draw rois for i in range(1, len(obj)+1): PR = PointRoi(obj[i][0],obj[i][1]) try: PR.setSize(3) PR.setPointType(0) roim.addRoi(PR) except: roim.addRoi(PR) roim.runCommand('Show All with Labels')
def main(argv): """Segment mitochondria.""" datadir = '/Users/michielk/M3S1GNUds7' filename = 'M3S1GNUds7_tiff.tif' filepath = os.path.join(datadir, filename) imp = BF.openImagePlus(filepath)
def readSingleChannelImg(imgFile): options = ImporterOptions() options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE) options.setId(imgFile) 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 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 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 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 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 get_image(input_file): imp = BF.openImagePlus(input_file)[0] # Reorder stack to swap Z and T if needed nframes = imp.getDimensions()[4] nslices = imp.getDimensions()[3] if nframes == 1: IJ.run("Re-order Hyperstack ...", "channels=[Channels (c)] slices=[Frames (t)] frames=[Slices (z)]"); return imp
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 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 imageloader(path, debug=False): ''' Wrapper to deal with opening bioformat images properly in macros Returns an ImagePlus if successful and exception if not. Read ij.ImagePlus and loci.plugins.BF.openImagePlus for details. ''' from ij import ImagePlus from loci.plugins import BF ext = os.path.splitext(path)[1] if ext in BIOFORMATS: return BF.openImagePlus(path)[0] else: return ImagePlus(path)
def main(): files = [] for filt in img_extensions.split(";"): if len(filt.strip()) > 0: files += glob.glob(os.path.join(str(input_dir), filt.strip())) else: files += glob.glob(os.path.join(str(input_dir), "*.*")) break if len(files) == 0: IJ.showMessage("No files found in '{}'\nfor extensions '{}'".format( str(input_dir), img_extensions)) else: for fn in files: try: imp = BF.openImagePlus(fn)[0] except: IJ.showMessage( "Could not open file '{}' (skipping).\nUse extension filter to filter non-image files..." .format(str(fn))) continue img = IJF.wrap(imp) cali = imp.getCalibration().copy() if pixel_width > 0: cali.pixelWidth = pixel_width cali.pixelHeight = pixel_width cali.setUnit("micron") if frame_interval > 0: cali.frameInterval = frame_interval cali.setTimeUnit("sec.") imp_out = smooth_temporal_gradient(ops, img, sigma_xy, sigma_t, frame_start, frame_end, normalize_output) imp_out.setCalibration(cali) channels = ChannelSplitter.split(imp_out) fn_basename = os.path.splitext(fn)[0] IJ.save(channels[0], "{}_shrinkage.tiff".format(fn_basename)) IJ.save(channels[1], "{}_growth.tiff".format(fn_basename)) print("{} processed".format(fn_basename)) IJ.showMessage( "Growth/shrinkage extraction of {} inputs finsihed.".format( len(files)))
def openImage(self, imageFile): try: images = BF.openImagePlus(imageFile) self.imp = images[0] except UnknownFormatException: return None if self.imp.getNChannels() < 2: IJ.error("Bad image format", "Image must contain at lease 2 channels!") return None if not self.pairs or \ not self.methods: self.getOptionsDialog(self.imp) title = self.imp.title self.imp.title = title[:title.rfind('.')] return self.imp
def main(argv): """Convert .dm3 files to tifs.""" inputdir = 'INPUTDIR' outputdir = 'OUTPUTDIR' output_postfix = 'OUTPUT_POSTFIX' infiles = glob.glob(os.path.join(inputdir, '*.dm3')) for infile in infiles: imp = BF.openImagePlus(infile) tail = os.path.split(infile)[1] filename = os.path.splitext(tail)[0][-4:] + output_postfix + '.tif' outpath = os.path.join(outputdir, filename) IJ.save(imp[0], outpath)
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 setUp(self): self.t = set_up_params(output_path_dir, test=False) self.cp = cab.cp self.change_ini() self.d, self.s = self.t.startScript() #self.cp.update("ChannelOptions", {"c1opt_boollist": "[False, False, False, True]"}) #self.cp.readIni() from ij import IJ from loci.plugins import BF for i, f in enumerate(self.d.filenames): imp = BF.openImagePlus(f)[0] # imp.show() cab.headless = True self.imp = cab.Image(f, self.d, self.s, False) self.db = cab.db_interface(inipath, self.imp)
def load_ome_img(file_name): """ :param file_name: :return: """ imps = BF.openImagePlus(file_name) imag = imps[0] # parse metadata reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(file_name) print(omeMeta) reader.close() return (imag, omeMeta)
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 openImageFile(folder, imageFile): folder = folder.decode('utf8') imageFile = imageFile.decode('utf8') imagePath = str(folder)+"/"+str(imageFile) reader, options = readImageFile(imagePath) seriesCount = reader.getSeriesCount() #Nombre de séries zDepthByChannel = reader.getSizeZ() #Profondeur Z #imageStackImps = BF.openImagePlus(options) seriesOfImageFile = [] for numberSerie in range(seriesCount): options.setSeriesOn(numberSerie,True); #Pour LIF - compter les séries - https://gist.github.com/ctrueden/6282856 imageStackImps = BF.openImagePlus(options); #print imageStackImps mainImageStackImp = imageStackImps[-1] #0 mainImageStackImp.setTitle(str(imageFile)+"_"+str(numberSerie)) seriesOfImageFile.append(mainImageStackImp) #return mainImageStackImp return seriesOfImageFile
def get_image(info, default_path, used_files): """handle getting image from file""" check_for_file_overlap_OK = False; while not check_for_file_overlap_OK: info.set_input_file_path(file_location_chooser(default_path)); if info.get_input_file_path() in used_files: dlg = GenericDialog("Image already used..."); dlg.addMessage("This image has already been used in this analysis run. \n " + "Continue with this image, or choose a new one?"); dlg.setOKLabel("Continue"); dlg.setCancelLabel("Choose again..."); dlg.showDialog(); check_for_file_overlap_OK = False if dlg.wasCanceled() else True; else: check_for_file_overlap_OK = True; import_opts, info = choose_series(info.get_input_file_path(), info) imps = bf.openImagePlus(import_opts); imp = imps[0]; try: memory_usage = IJ.currentMemory()/IJ.maxMemory(); print("memory usage = " +str(memory_usage)); # arbitrary limit... if memory_usage > 0.95: IJ.run(imp, "8-bit", ""); print("WARNING - IMAGE CONVERTED TO 8 BIT TO CONSERVE MEMORY!"); info.set_metadata_file_path(os.path.splitext(info.get_input_file_path())[0] + ".txt"); metadata = import_iq3_metadata(info.get_metadata_file_path()); IJ.run(imp, "Properties...", "channels=" + str(int(metadata['n_channels'])) + " slices=" + str(int(metadata['z_pixels'])) + " frames=1 unit=" + str(metadata['x_unit']) + " pixel_width=" + str(metadata['x_physical_size']) + " pixel_height=" + str(metadata['y_physical_size']) + " voxel_depth=" + str(metadata['z_extent']/metadata['z_pixels'])); info.set_xy_pixel_size_um(metadata['x_physical_size']); info.set_z_plane_spacing_um(metadata['z_extent']/metadata['z_pixels']); info = parse_info_from_filename(info); except e as Exception: print(e.message); finally: if imp is not None: imp.close(); return imp, info;
def split_image(file_): print "Processing: %s" %(basename(file_)) #load with loci (allows also to load *.czi) images = BF.openImagePlus(file_) image = images[0] #split channels chSp = ChannelSplitter() title = splitext(image.title)[0] imageC = chSp.split(image) print "Number of channels: ", len(imageC) for iCh in range(0, len(imageC)): imageStack = imageC[iCh].getImageStack() for iSlice in range(0,imageC[0].getNSlices()): #print iSlice impOut = ImagePlus("outImg", imageStack.getProcessor(iSlice+1)) ntitle = to_wellbased_nameing_scheme(title, iCh+1, iSlice+1) IJ.log("Image: %s -> %s " %(title, ntitle)) IJ.saveAs(impOut, "Tiff", join(outdir, ntitle) )
def main(input_dir, file_contains, params): file_list = glob.glob(os.path.join(str(input_dir), "*.{}".format(file_ext))) file_contains = file_contains.strip() if len(file_contains) > 0: file_list = filter(lambda x: file_contains in os.path.basename(x), file_list) if len(file_list) == 0: IJ.showMessage("No files found to process.") return for input_file in file_list: imp = BF.openImagePlus(input_file)[0] path = os.path.dirname(input_file) file_name = os.path.basename(input_file) run_trackmate(imp, path, file_name, params, batch_mode=True) IJ.showMessage("Processing of {} input files done.".format(len(file_list)))
def process(srcDir, dstDir, nameContains, currentDir, fileName, keepDirectories, anneBoleyn, overOut): print "Opening", fileName saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir head, tail = os.path.splitext(fileName) imps = BF.openImagePlus(os.path.join(currentDir, fileName)) for imp in imps: if not anneBoleyn: print "Now showing image..." imp.show() IJ.run(imp, "Blue", "") fs = FileSaver(imp) if not os.path.exists(saveDir): os.makedirs(saveDir) if not overOut: if os.path.exists(saveDir + "\\" + head + ".jpg"): print "This JPG exists already and will not be overwritten. Moving on..." else: print "Saving to", os.path.join(saveDir, head + ".jpg") fs.saveAsJpeg(os.path.join(saveDir, head + ".jpg")) imp.close()
def loadResultsFile(resfile): my_file = open(resfile, 'r') my_file.seek(0) for line in my_file: tabLine = line.split('\t') if tabLine[0].isdigit(): #first pt if re.search( 'R\d_P(\d)_K\d_Ch\d-Ch\d.zen', tabLine[1]).group(1) == '1': filename = re.split('_R\d_P(\d)_K\d_Ch\d-Ch\d.zen', os.path.basename(tabLine[2]))[0] + '.xml' dirName = os.path.dirname(tabLine[2]) dirName = dirName.replace("Z:", "X:") filename = os.path.join(dirName,filename) obj, imgName = getPosition(filename) img = BF.openImagePlus(imgName)[0] img.show() #while (line = my_file.readline()): # print "aline" print "finished" my_file.close()
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 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 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
import os, sys from ij import IJ from ij.io import FileSaver from loci.plugins import BF from subprocess import call from ij.plugin import ZProjector try: filepath = getArgument() except Exception, e: sys.exit(" no file " + e) try: imp = BF.openImagePlus(filepath) image = imp[0] zProj = ZProjector(image) zProj.setMethod(zProj.MAX_METHOD) zProj.doProjection() imgMax = zProj.getProjection() #imgMax.show() FileSaver(imgMax).saveAsTiff(os.path.splitext(filepath)[0] + "_MAX.tif") except Exception, e: sys.exit(e) except Exception, e: sys.exit(e)
arg = re.split('\s+-c', arg) if len(arg)>1: xmlfile = arg[0] ch = int(arg[1]) else: xmlfile = arg[0] ch = 1 #open xml file and parse it tree = ET.parse(xmlfile) root = tree.getroot() obj, imgName = getPosition(root) print imgName #open image img = BF.openImagePlus(imgName)[0] img.setZ(obj[1][2]+1) img.setC(int(ch)) img.show() #draw rois for i in range(1, len(obj)+1): PR = PointRoi(obj[i][0],obj[i][1]) try: PR.setSize(3) PR.setPointType(0) roim.addRoi(PR) except: roim.addRoi(PR)
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) if 'Polygon' not in shape:
for ch in range(1, channels + 1): projector = ZProjector(ImagePlus("C%i" % ch, splitter.getChannel(image, ch))) projector.setMethod(ZProjector.MAX_METHOD) projector.doProjection() proj = projector.getProjection() enhancer.equalize(proj) chimps.append(proj) return RGBStackMerge.mergeChannels(chimps, False) manders = MandersColocalization() results = ResultsTable() for imageFile in os.listdir(inputDir): print "Opening " + imageFile try: images = BF.openImagePlus(inputDir + imageFile) image = images[0] except UnknownFormatException: continue preview = getPreview(image) preview.show() rm = RoiManager() dialog = WaitForUserDialog("Action required", "Please select regions of interest in this image. Click OK when done.") dialog.show() rm.close() splitter = ChannelSplitter() imp1 = ImagePlus("CH1", splitter.getChannel(image, imageA)) imp2 = ImagePlus("CH2", splitter.getChannel(image, imageB)) title = image.getTitle() title = title[:title.rfind('.')] image.close()
else: pixels = False if flat and pixels: print("Both --flat and --pixels cannot be specified simultaneously.") sys.exit(1) print referenceFile print objectListFile print outputFile # Open source image try: image = IJ.openImage(referenceFile) except Exception: images = BF.openImagePlus(referenceFile) image = images[0] calibration = image.getCalibration() zscale = calibration.getZ(1) / calibration.getX(1) channels = image.getNChannels() # Read objects objects = csv.reader(open(objectListFile)) fmin = [] fmax = [] thrF = 50.000 sx = image.getWidth() sy = image.getHeight() sz = image.getNSlices()
options['edgeXY'] = True if args.exclude_edge_z: if str(args.exclude_edge_z).upper() == "TRUE": options['edgeZ'] = False else: options['edgeZ'] = True else: options['inputFile'] = "sample.tif" options['outputDir'] = "./" if options['paramsOut'] == None: results = [] try: image = IJ.openImage(options['inputFile']) except Exception: images = BF.openImagePlus(options['inputFile']) image = images[0] if options['oneShot']: results.append(runSimulation(options, image)) else: parameters = makeParameters(options) for index in range(0, len(parameters)): options.update(parameters[index]) results.append(runSimulation(options, image)) resultsTable = ResultsTable() resultsTable.showRowNumbers(False) for i in range(0, len(results)): if options['oneShot']:
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()
@String(label="Base Directory", style="") str_dir @String(label="Image Title", style="") str_img_nam @String(label="Image Extension", style="", value=".tif") str_img_ext file = str_dir + "/" + str_img_nam + str_img_ext # read in and display ImagePlus object(s) from loci.plugins import BF from loci.formats import ImageReader from loci.formats import MetadataTools from ij import IJ from ome.units import UNITS imps = BF.openImagePlus(file) for imp in imps: imp.show() 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!) imageCount = omeMeta.getImageCount() IJ.log("Total # of image series (from BF reader): " + str(seriesCount)) IJ.log("Total # of image series (from OME metadata): " + str(imageCount)) physSizeX = omeMeta.getPixelsPhysicalSizeX(0) physSizeY = omeMeta.getPixelsPhysicalSizeY(0) physSizeZ = omeMeta.getPixelsPhysicalSizeZ(0) IJ.log("Physical calibration:") if (physSizeX is not None): IJ.log("\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol() + " = " + str(physSizeX.value(UNITS.MICROM)) + " microns")
# USER PARAMETERS TO CHANGE ############################# #Diameter in microns cellDiameter=3.0 # The minimum intensity for a peak to be considered minPeak=0 #Use point(1), icosphere(2), or icosphere but limited to the first 3495 points in X (3) plotType=USE_POINT # diameter Cell visualization cellIcosophere=3.0 #Open the image and duplicate it to get an 8 Bits version use to plot od = OpenDialog("Open image file", None) srcFile = od.getPath() srcDir = od.getDirectory() imp = BF.openImagePlus(srcFile)[0] imp8Bits = imp.duplicate() ImageConverter(imp8Bits).convertToGray8() print "Image " + srcFile + " open successfully!" #Create the coordinate.txt file to ouput the point coordinate coordinateFile = open(srcDir + "coordinate.txt", "w") print "Created " +srcDir + "coordinate.txt" # If minPeak is set to 0, set it to automatically. if minPeak == 0: minPeak = AutoThresholder().getThreshold("Percentile", imp.getStatistics().histogram); #Get the pixel calibration cal=imp.getCalibration() #Set Gaussian Sigma parameters for the Difference of Gaussian sigmaLarge=[cellDiameter/cal.pixelWidth,cellDiameter/cal.pixelHeight,cellDiameter/cal.pixelDepth] sigmaSmall=[a/2 for a in sigmaLarge]
def regBf(fn=None, imp=None, refId=None): """ Register a time series stack to a specified reference slice, from a file (imported by BioFormat) or a stack ImagePlus. Returns a registered ImagePlus. The stack must have only 1 z layer. refId is in the format of [int channel, int slice, int frame] If no refId is supplied, will use the first slice [1,1,1] Note: since TurboReg is used for registeration, there will be temporary opened image windows. """ ## Prepare the right ImagePlus if imp is None: if fn is None: od = OpenDialog("Choose a file", None) filename = od.getFileName() if filename is None: print "User canceled the dialog!" return else: directory = od.getDirectory() filepath = directory + filename print "Selected file path:", filepath else: if os.path.exists(fn) and os.path.isfile(fn): filepath = fn else: print "File does not exist!" return imps = BF.openImagePlus(filepath) imp = imps[0] if imp is None: print "Cannot load file!" return else: if fn is not None: print "File or ImagePlus? Cannot load both." return width = imp.getWidth() height = imp.getHeight() # C nChannels = imp.getNChannels() # Z nSlices = imp.getNSlices() # T nFrames = imp.getNFrames() # pixel size calibration = imp.getCalibration() # Only supoort one z layer if nSlices != 1: print "Only support 1 slice at Z dimension." return # set registration reference slice if refId is None: refC = 1 refZ = 1 refT = 1 else: refC = refId[0] refZ = refId[1] refT = refId[2] if (refC not in range(1, nChannels+1) or refZ not in range(1, nSlices+1) or refT not in range(1, nFrames+1) ): print "Invalid reference image!" return stack = imp.getImageStack() registeredStack = ImageStack(width, height, nChannels*nFrames*nSlices) # setup windows, these are needed by TurboReg tmpip = FloatProcessor(width, height) refWin = ImageWindow(ImagePlus("ref", tmpip)) bounds = refWin.getBounds() # refWin.setVisible(False) toRegWin = ImageWindow(ImagePlus("toReg", tmpip)) toRegWin.setLocation(bounds.width + bounds.x, bounds.y) # toRegWin.setVisible(False) toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip)) toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y) # toTransformWin.setVisible(False) # get reference image refImp = ImagePlus("ref", stack.getProcessor(imp.getStackIndex(refC, refZ, refT))) refWin.setImage(refImp) tr = TurboReg_() for t in xrange(1, nFrames+1): IJ.showProgress(t-1, nFrames) # print "t ", t # do TurboReg on reference channel toRegId = imp.getStackIndex(refC, refZ, t) toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId)) toRegWin.setImage(toRegImp) regArg = "-align " +\ "-window " + toRegImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-window " + refImp.getTitle() + " " +\ "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\ "-rigidBody " +\ str(width / 2) + " " + str(height / 2) + " " +\ str(width / 2) + " " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ "0 " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ str(width - 1) + " " + str(height / 2) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(regArg) registeredImp = tr.getTransformedImage() sourcePoints = tr.getSourcePoints() targetPoints = tr.getTargetPoints() registeredStack.setProcessor(registeredImp.getProcessor(), toRegId) # toRegImp.flush() # apply transformation on other channels for c in xrange(1, nChannels+1): # print "c ", c if c == refC: continue toTransformId = imp.getStackIndex(c, 1, t) toTransformImp = ImagePlus("toTransform", stack.getProcessor(toTransformId)) toTransformWin.setImage(toTransformImp) transformArg = "-transform " +\ "-window " + toTransformImp.getTitle() + " " +\ str(width) + " " + str(height) + " " +\ "-rigidBody " +\ str(sourcePoints[0][0]) + " " +\ str(sourcePoints[0][1]) + " " +\ str(targetPoints[0][0]) + " " +\ str(targetPoints[0][1]) + " " +\ str(sourcePoints[1][0]) + " " +\ str(sourcePoints[1][1]) + " " +\ str(targetPoints[1][0]) + " " +\ str(targetPoints[1][1]) + " " +\ str(sourcePoints[2][0]) + " " +\ str(sourcePoints[2][1]) + " " +\ str(targetPoints[2][0]) + " " +\ str(targetPoints[2][1]) + " " +\ "-hideOutput" tr = TurboReg_() tr.run(transformArg) registeredStack.setProcessor(tr.getTransformedImage().getProcessor(), toTransformId) # toTransformImp.flush() sourcePoints = None targetPoints = None IJ.showProgress(t, nFrames) IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames)) refWin.close() toRegWin.close() toTransformWin.close() imp2 = ImagePlus("reg_"+imp.getTitle(), registeredStack) imp2.setCalibration(imp.getCalibration().copy()) imp2.setDimensions(nChannels, nSlices, nFrames) # print "type ", imp.getType() # print "type ", imp2.getType() # print nChannels, " ", nSlices, " ", nFrames # print registeredStack.getSize() for key in imp.getProperties().stringPropertyNames(): imp2.setProperty(key, imp.getProperty(key)) # comp = CompositeImage(imp2, CompositeImage.COLOR) # comp.show() # imp2 = imp.clone() # imp2.setStack(registeredStack) # imp2.setTitle("reg"+imp.getTitle()) # imp2.show() # imp.show() return imp2
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()
overlayImage.setSlice(2) IJ.run(overlayImage, "Delete Slice", "") return overlayImage #### Main Stuff ##### outputFilePath = inputDirectory + '/' + outputFile if os.path.isfile(outputFilePath): os.remove(outputFilePath) outputFile = open(outputFilePath, 'a') for fileName in os.listdir(inputDirectory): print 'Processing Image ' , fileName if '.tif' in fileName: #print 'Opening image...' imps = BF.openImagePlus(os.path.join(inputDirectory, fileName)) image = imps[0] image.show() # Select tumor WaitForUserDialog("Select the tumor by hand.").show() # Measure Area currentROI = image.getROI() image.setRoi(currentRoi) stats = image.getStatistics(Measurements.AREA) currentArea = stats.area image.killRoi() # Create an overlay if currentROI is not None: overlayImage = createOverlay(image, selectedROI) else: