def run(indir=None,outdir=None): IJ.run("Close All") IJ.log(" ") IJ.log("!!concat: concatenation of lsm, czi created with AutofocusScreen VBA macro!!") '''Main execution. Ask users for input and output directories if not specified''' if indir is None: indir = IJ.getDirectory("Choose the input directory") if indir is None or indir == '': IJ.showMessage("Concat: No input directory defined!") return if outdir is None: outdir = IJ.getDirectory("Choose output directory. If cancel macro uses respective local directories") if outdir == '': outdir = None if outdir is not None: if not os.path.exists(outdir): os.mkdir(outdir) start_time = time() for root, dirs, files in os.walk(indir, topdown = False): locfiles = glob(root+"/*.lsm") print locfiles locfiles= locfiles + glob(root+"/*.czi") if locfiles is not None: find_timepoints(root, locfiles, outdir) return start_time
def run(imp): if None == imp: IJ.showMessage("No images open!") return type = imp.getType() n_slices = imp.getStackSize() if 1 == n_slices: ip = imp.getProcessor().crop() processSlice(ip, type) # show result in a new image ImagePlus("Noisy_" + imp.title, ip).show() else: stack1 = imp.getStack() roi = imp.getRoi() if None == roi: width = imp.width height = imp.height else: rect = roi.getBounds() width = rect.width height = rect.height stack2 = ImageStack(width, height) for i in range(1, n_slices+1): ip = stack1.getProcessor(i) # stack processors need the roi to be explicitly set if roi: ip.setRoi(rect) ip = ip.crop() processSlice(ip, type) stack2.addSlice(stack1.getSliceLabel(i), ip) # show result in a new image ImagePlus("Noisy_" + imp.title, stack2).show()
def Dialog(imp): dpi = 300 # a4 width in inches defaultWidth = 11.69 defaultHeight = defaultWidth / ratio defaultAspectRatio = 1.41 if imp: gd = GenericDialogPlus("Cover Maker") gd.addMessage("Input Options") gd.addFileField("Select image database", "", 20) gd.addMessage("Cover Maker Options") gd.addNumericField("tile width", 12, 0) gd.addNumericField("tile height", 9, 0) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" return databasepath = gd.getNextString() tilewidth = gd.getNextNumber() tileheight = gd.getNextNumber() return databasepath, imp.getWidth(), imp.getHeight(), int( tilewidth), int(tileheight) else: IJ.showMessage("You should have at least one image open.")
def runPoreDetection(): '''roiManager=RoiManager(False) roiManager.runCommand("open", roiname) roiHash=roiManager.getROIs() roi=roiHash.get("Right") print roi''' imageList = Utility.GetOpenImageList() nbgd = NonBlockingGenericDialog(Messages.AddRoi) nbgd.addMessage(Messages.ChooseImage) if (imageList == None): IJ.showMessage(Messages.noOpenImages) return nbgd.addChoice("Image1:", imageList, imageList[0]) nbgd.showDialog() name = nbgd.getNextChoice() inputImp = WindowManager.getImage(name) inputDataset = Utility.getDatasetByName(data, name) detectionParameters = DetectionParameters(10, 200, 0.5, 1.0, 0.3) #inputImp.setRoi(roi) nbgd2 = NonBlockingGenericDialog(Messages.PositionRoi) nbgd2.addMessage(Messages.PositionRoiAndPressOK) nbgd2.showDialog() poreDetectionUV(inputImp, inputDataset, inputImp.getRoi().clone(), ops, data, display, detectionParameters)
def runPoreDetection(): '''roiManager=RoiManager(False) roiManager.runCommand("open", roiname) roiHash=roiManager.getROIs() roi=roiHash.get("Right") print roi''' imageList=Utility.GetOpenImageList() nbgd=NonBlockingGenericDialog(Messages.AddRoi) nbgd.addMessage(Messages.ChooseImage) if (imageList==None): IJ.showMessage(Messages.noOpenImages) return; nbgd.addChoice("Image1:", imageList, imageList[0]); nbgd.showDialog() name = nbgd.getNextChoice() inputImp = WindowManager.getImage(name) inputDataset=Utility.getDatasetByName(data, name) detectionParameters=DetectionParameters(10, 200, 0.5, 1.0, 0.3) #inputImp.setRoi(roi) nbgd2=NonBlockingGenericDialog(Messages.PositionRoi) nbgd2.addMessage(Messages.PositionRoiAndPressOK) nbgd2.showDialog() poreDetectionUV(inputImp, inputDataset, inputImp.getRoi().clone(), ops, data, display, detectionParameters)
def split_and_save(imp): base_title = imp.getShortTitle() base_dir = imp.getOriginalFileInfo().directory d = GenericDialog("Split Stacks") d.addMessage("Indicate the channels in your image stack, separated by commas") d.addMessage("Add the channels *in the order that you took the images*") d.addMessage("For example, \"TL, 410, 470, 410, 470\"") d.addStringField("Channels", "TL, 470, 410", 40) d.showDialog() # exit if cancelled if d.wasCanceled(): return None channels = number_duplicate_channels([x.strip() for x in d.getNextString().split(',')]) # Check that the number of images in stack is divisible by the number of channels # If not, quit. Else keep going if (imp.getNSlices() % len(channels) != 0): IJ.error("Invalid Channel Specification", "The number of slices (%d) is not divisible by the number of channels (%d). Exiting." % (imp.getNSlices(), len(channels))) return None imp.show() IJ.run("Deinterleave", "how=%d" % len(channels)) for i, img_id in enumerate(WindowManager.getIDList()): channel_i = WindowManager.getImage(img_id) channel_i.setTitle(base_title + "_" + channels[i]) IJ.saveAs(channel_i, "tif", base_dir + channel_i.getTitle()) IJ.showMessage("Saved image stacks as separate channels in %s" % base_dir)
def Dialog(imp): dpi = 300 # a4 width in inches defaultWidth = 11.69 defaultHeight = defaultWidth/ratio defaultAspectRatio = 1.41 if imp: gd = GenericDialogPlus("Cover Maker") gd.addMessage("Input Options") gd.addFileField("Select image database", "", 20) gd.addMessage("Cover Maker Options") gd.addNumericField("tile width", 12, 0) gd.addNumericField("tile height", 9, 0) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" return databasepath = gd.getNextString() tilewidth = gd.getNextNumber() tileheight = gd.getNextNumber() print 'path:', databasepath return databasepath, imp.getWidth(), imp.getHeight(), int(tilewidth), int(tileheight) else: IJ.showMessage( "You should have at least one image open." )
def main(): # Tricky hack to get ImagePlus from IJ1 interface img = IJ.getImage() display = DefaultLegacyService().getInstance().getImageMap().lookupDisplay(img) dataset = DefaultImageDisplayService().getActiveDataset(display) imp = dataset.getImgPlus() # I don't really understand why sometime SCIFIO is not used # When it's not, we can't access to getMetadata() if not isinstance(imp, SCIFIOImgPlus): IJ.showMessage("This image has not been opened with SCIFIO") return # Get metadata metadata = imp.getMetadata() # Why the f**k this is needed ? while isinstance(metadata, AbstractMetadataWrapper): metadata = metadata.unwrap() # Check if metadata are OME or not if isinstance(metadata, Metadata): omeMeta = metadata.getOmeMeta() else: IJ.showMessage("This file does not contain OME metadata") return # Get xml string and print it with spaces indentation xml_string = DefaultOMEXMLService().getOMEXML(omeMeta.getRoot()) xml = dom.parseString(xml_string) xml_string = xml.toprettyxml(indent=" ") IJ.log(xml_string)
def createListfiles() : IJ.showMessage("Select a folder with the .tif files") selectdir=IJ.getDirectory("image") selectdir=IJ.getDirectory("") listfiles=glob.glob(selectdir+"*.tif") #fullprefix = str.rsplit(str(listfiles[0]), "/", 1) fullprefix = os.path.split(listfiles[0]) root = fullprefix[0] lastprefix = str.split(fullprefix[1], "_") del(listfiles) gdselectfiles = NonBlockingGenericDialog("List files Choice") gdselectfiles.addMessage("") gdselectfiles.addStringField("Prefix ?", lastprefix[0], 32) gdselectfiles.addStringField("Filter (w00001DIA) ?", "1DIA") gdselectfiles.addStringField("Positions (s0001) ?", "1-2") gdselectfiles.addStringField("Temps (t0001) ?", "1-11") #gdselectfiles.addStringField("Files pattern", "*DIA_s*1_t*.tif", 32) gdselectfiles.showDialog() prefix = str(gdselectfiles.getNextString()) channel = str(gdselectfiles.getNextString()) temppositions = str(gdselectfiles.getNextString()) positions = str.split(temppositions, "-") temptimes = str(gdselectfiles.getNextString()) times = str.split(temptimes, "-") if channel != "" : channel = "_w000"+channel positionslist=[] if positions[0] != "" : for p in range(int(positions[0]), int(positions[1])+1, 1) : positionslist.append("_s"+"%04i"%(p)) else : positionslist.append("") timeslist=[] if times[0] != "" : for t in range(int(times[0]), int(times[1])+1, 1) : timeslist.append("_t"+"%04i"%(t)) else : timeslist.append("") patterns=[] listfiles = [] for p in positionslist : files = [] for t in timeslist : patterns.append(channel+p+t+".tif") tempfilename = os.path.join(root, prefix+patterns[-1]) files.append(tempfilename) #files.append(root+"/"+prefix+patterns[-1]) listfiles.append(files) if len(listfiles)>1 : return (prefix, patterns, listfiles, positionslist) else : return (prefix, patterns, files, "_s0001")
def openAtFolder(event): if 0 == path.getText().find("http"): IJ.showMessage("Can't open folder: it's an URL") return directory = os.path.dirname(path.getText()) od = OpenDialog("Open", directory, None) filepath = od.getPath() if filepath: IJ.open(filepath)
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 __browse(self, event): IJ.showMessage("Select project directory") self.__selectdir=IJ.getDirectory("image") choix = swing.JFileChooser(self.__selectdir) choix.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) retour=choix.showOpenDialog(self) if(retour==swing.JFileChooser.APPROVE_OPTION) : self.__selectdir = choix.getSelectedFile().getAbsolutePath() self.__dispDossier.text = self.__selectdir
def __ImportPref(self, flag) : indiceinterest=5 if len(self.__params) < 1 : if flag == 1 : IJ.showMessage("Select the text file containing the preferences you want (Track.txt file)") self.__selectdir=IJ.getDirectory("image") frame = Frame("Text file settings ?") fd = FileDialog(frame) fd.setDirectory(self.__selectdir) fd.show() self.__selectdir = fd.getDirectory() self.__textfile = fd.getFile() #self.__selectdir=IJ.getDirectory("") #listfiles=glob.glob(selectdir+"*DIA_s0001*.tif") #fichier = open(self.__selectdir+"Track.txt","r") fichier = open(self.__selectdir+self.__textfile,"r") lignes=fichier.readlines() self.__params=[] for i in range(indiceinterest,len(lignes)): # ATTENTION À CHANGER AVEC PARAM DE RANGEROI params=lignes[i].split("=") val=params[1].split("\n") if params[0]=="SUBBACK" : self.__subback=bool(int(val[0])) if params[0]=="SUBBACKRADIUS" : self.__radius=Double(val[0]) if params[0]=="DISTPARAM_AREA_COEFF" : self.__distparam[0]=int(val[0]) if params[0]=="DISTPARAM_AREA_MAXDELTA" : self.__distparam[1]=Double(val[0]) if params[0]=="DISTPARAM_ANGLE_COEFF" : self.__distparam[2]=int(val[0]) if params[0]=="DISTPARAM_ANGLE_MAXDELTA" : self.__distparam[3]=Double(val[0]) if params[0]=="DISTPARAM_FERETMAX_COEFF" : self.__distparam[4]=int(val[0]) if params[0]=="DISTPARAM_FERETMAX_MAXDELTA" : self.__distparam[5]=Double(val[0]) if params[0]=="DISTPARAM_POSITIONX_COEFF" : self.__distparam[6]=int(val[0]) if params[0]=="DISTPARAM_POSITIONX_MAXDELTA" : self.__distparam[7]=int(val[0]) if params[0]=="DISTPARAM_POSITIONY_COEFF" : self.__distparam[8]=int(val[0]) if params[0]=="DISTPARAM_POSITIONY_MAXDELTA" : self.__distparam[9]=int(val[0]) if params[0]=="DISTMETHOD" : self.__distmethod=str(val[0]) if params[0]=="OPTIONMANTHRESH" : self.__manthresh=bool(int(val[0])) if params[0]=="THRESHMETHOD" : self.__thresMethod=str(val[0]) if params[0]=="OPTIONANGLE" : self.__optionAngle=bool(int(val[0])) if params[0]=="OPTIONNEWCELLS" : self.__optionNewCells=bool(int(val[0])) if params[0]=="OPTIONTIMELAPSE" : self.__optionTimelapse=bool(int(val[0])) if params[0]=="TIMELAPSE" : self.__timelapse=int(val[0]) # imported booleans : self.__subback, self.__manthresh, self.__optionAngle, self.__optionNewCells, self.__optionTimelapse minmax=val[0].split(";") if params[0]=="Area" : self.__params.append(("Area",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Mean" : self.__params.append(("Mean",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Angle" : self.__params.append(("Angle",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Major" : self.__params.append(("Major",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Minor" : self.__params.append(("Minor",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Solidity" : self.__params.append(("Solidity",Double(minmax[0]),Double(minmax[1]))) if params[0]=="AR" : self.__params.append(("AR",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Round" : self.__params.append(("Round",Double(minmax[0]),Double(minmax[1]))) if params[0]=="Circ" : self.__params.append(("Circ",Double(minmax[0]),Double(minmax[1])))
def __end(self, event): if len(self.__iplist)==0 : IJ.showMessage("", "Stack is empty") return self.__iplist.sort(key = lambda ip : ip.width) self.__ipw=[ ip.getWidth() for ip in self.__iplist ] self.__iph=[ ip.getHeight() for ip in self.__iplist ] maxw=max(self.__ipw) maxh=max(self.__iph) if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in self.__iplist ] else : resizelist = [] for ip in self.__iplist : tempip = ShortProcessor(maxw, maxh) xloc = int(math.floor((maxw/2.00) - (ip.width/2.00))) yloc = int(math.floor((maxh/2.00) - (ip.height/2.00))) tempip.copyBits(ip, xloc, yloc, Blitter.COPY) resizelist.append(tempip) ims = ImageStack(maxw, maxh) #for ip in resizelist : ims.addSlice("", ip) for i in range(len(resizelist)) : ims.addSlice(self.__labels[i], resizelist[i]) self.__impRes = ImagePlus(self.__name, ims) self.__impRes.show() self.__sens = [1 for i in range(len(self.__iplist)) ] if self.__appmedian : IJ.run(self.__impRes, "Median...", "radius=1 stack") if self.__align : self.__falign() if self.__avg : self.__favg() if self.__mosa : self.__fmosa() if self.__maxfinder : self.__fmaxfinder() if self.__fire : IJ.run(self.__impRes, "Fire", "") if self.__measures : self.__fmeasures() self.__sens[:] = [] self.__listrois[:] = [] self.__iplist[:] = [] self.__cellsrois[:] = [] self.__ipw[:] = [] self.__iph[:] = [] self.__init = False
def __split(self, event) : sel = self.getSelected() if len(sel) != 1 : IJ.showMessage("only one cell should be selected !") return else : cellname = sel[0] rois = self.__rm.getRoisAsArray() self.__rm.runCommand("reset") n = int(IJ.getNumber("slice to split ?", 1)) for i in range(n) : self.__rm.addRoi(rois[i]) #print self.__path+cellname+"-a.zip" self.__rm.runCommand("Save", self.__path+cellname+"-a.zip") self.__rm.runCommand("reset") for i in range(n, len(rois)) : self.__rm.addRoi(rois[i]) self.__rm.runCommand("Save", self.__path+cellname+"-b.zip") self.__rm.runCommand("reset") root = self.__path.rsplit(os.path.sep, 2)[0]+os.path.sep if not path.exists(root+"Cells"+os.path.sep) :os.makedirs(root+"Cells"+os.path.sep, mode=0777) fichiertemp = open(root+"Cells"+os.path.sep+cellname+"-a.cell","w") fichiertemp.write("NAMECELL="+cellname+"-a\n") fichiertemp.write("PATHCELL="+root+"Cells"+os.path.sep+cellname+"-a.cell\n") fichiertemp.write("PATHROIS="+root+"ROIs"+os.path.sep+cellname+"-a.zip\n") fichiertemp.write("NSLICES="+str(len(rois))+"\n") fichiertemp.write("SLICEINIT="+str(1)+"\n") fichiertemp.write("SLICEEND="+str(n)+"\n") r = random.randrange(5,205,1) g = random.randrange(10,210,1) b = random.randrange(30,230,1) fichiertemp.write("COLOR="+str(r)+";"+str(g)+";"+str(b)+"\n") fichiertemp.close() fichiertemp = open(root+"Cells"+os.path.sep+cellname+"-b.cell","w") fichiertemp.write("NAMECELL="+cellname+"-b\n") fichiertemp.write("PATHCELL="+root+"Cells"+os.path.sep+cellname+"-b.cell\n") fichiertemp.write("PATHROIS="+root+"ROIs"+os.path.sep+cellname+"-b.zip\n") fichiertemp.write("NSLICES="+str(len(rois))+"\n") fichiertemp.write("SLICEINIT="+str(n+1)+"\n") fichiertemp.write("SLICEEND="+str(len(rois))+"\n") r = random.randrange(5,205,1) g = random.randrange(10,210,1) b = random.randrange(30,230,1) fichiertemp.write("COLOR="+str(r)+";"+str(g)+";"+str(b)+"\n") fichiertemp.close()
def filter(self, regex): # regex is a string if not regex: IJ.showMessage("Enter a valid search text string") return fn = None if '/' == regex[0]: fn = partial(re.match, re.compile(regex[1:])) else: fn = lambda path: -1 != path.find(regex) try: self.filtered_paths = self.paths.parallelStream().filter( Filter(fn)).toArray() except: print sys.exc_info()
def exportMask(evt=None): display = Display.getFront() arealists = display.getSelection().getSelected(AreaList) canvas = display.getCanvas() numLayer = display.getLayerSet().size(); if arealists.isEmpty(): IJ.log("No arealists selected -- I just take the FIRST ONE!!") #IJ.showMessage("No arealists selected -- select one!") zDispList = display.getLayerSet().getDisplayableList() if len(zDispList) > 0: arealists = zDispList else: IJ.log("Project does not contain any AreaLists!") IJ.showMessage("Project does not contain any AreaLists!") return AreaList.exportAsLabels(arealists, canvas.getFakeImagePlus().getRoi(), 1.0, 0, numLayer-1, False, False, False);
def SaveDialog(imp): dpi = 300 # a4 width in inches defaultWidth = 11.69 defaultHeight = defaultWidth / ratio defaultAspectRatio = 1.41 if imp: gd = GenericDialogPlus("Cover Maker") gd.addMessage("Saving options") gd.addNumericField("resolution (dpi)", dpi, 0) gd.addNumericField("width (pixels)", defaultWidth * dpi, 0) gd.addNumericField("height (pixels)", defaultHeight * dpi, 0) gd.addNumericField("width (inches)", defaultWidth, 2) gd.addNumericField("height (inches)", defaultHeight, 2) gd.addFileField("Select Originals database", "", 20) fields = gd.getNumericFields() resField = fields.get(0) widthPixels = fields.get(1) heightPixels = fields.get(2) widthInches = fields.get(3) heightInches = fields.get(4) # resolution and size listener textListener = ResolutionListener(resField, widthPixels, heightPixels, widthInches, heightInches) resField.addTextListener(textListener) widthInches.addTextListener(textListener) heightInches.addTextListener(textListener) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" return newres = gd.getNextNumber() newwidth = gd.getNextNumber() newheight = gd.getNextNumber() originalspath = gd.getNextString() return int(newwidth), int(newheight), newres, originalspath else: IJ.showMessage("You should have at least one image open.")
def SaveDialog(imp): dpi = 300 # a4 width in inches defaultWidth = 11.69 defaultHeight = defaultWidth/ratio defaultAspectRatio = 1.41 if imp: gd = GenericDialogPlus("Cover Maker") gd.addMessage("Saving options") gd.addNumericField("resolution (dpi)", dpi, 0) gd.addNumericField("width (pixels)", defaultWidth*dpi, 0) gd.addNumericField("height (pixels)", defaultHeight*dpi, 0) gd.addNumericField("width (inches)", defaultWidth, 2) gd.addNumericField("height (inches)", defaultHeight, 2) gd.addFileField("Select Originals database", "", 20) fields = gd.getNumericFields() resField = fields.get(0) widthPixels = fields.get(1) heightPixels = fields.get(2) widthInches = fields.get(3) heightInches = fields.get(4) # resolution and size listener textListener = ResolutionListener(resField, widthPixels, heightPixels, widthInches, heightInches) resField.addTextListener(textListener) widthInches.addTextListener(textListener) heightInches.addTextListener(textListener) gd.showDialog() if gd.wasCanceled(): print "User canceled dialog!" return newres = gd.getNextNumber() newwidth = gd.getNextNumber() newheight = gd.getNextNumber() originalspath = gd.getNextString() return int(newwidth), int(newheight), newres, originalspath else: IJ.showMessage( "You should have at least one image open." )
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 get_setup(): '''Returns two ImagePlus objects and a dictionary of properties to copy.''' dialog = GenericDialog('Copy Properties setup') dialog.addMessage('Select the source and target image and the properties to copy.') image_ids = WindowManager.getIDList() if not image_ids or len(image_ids) < 2: IJ.showMessage('Two or more images are necessary to use this plugin.') return [None]*3 image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] dialog.addChoice('Source', image_titles, image_titles[0]) dialog.addChoice('Target', image_titles, image_titles[1]) dialog.addCheckbox('Copy Calibration', True) dialog.addCheckbox('Copy Slice Labels', False) dialog.showDialog() if dialog.wasCanceled(): return [None]*3 source = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) target = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) choices = {'cal': dialog.getNextBoolean(), 'labels': dialog.getNextBoolean() } return source, target, choices
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 run(): msg = "<html>" wm = WindowManager wcount = wm.getWindowCount() if wcount == 0: msg += "No windows open, nothing to do.<br/>" IJ.showMessage(PluginTitle, msg) return msg += "Number of open windows: " + str(wcount) + "<br/>" # let the User choose a directory to store the files target = DirectoryChooser("Choose target directory").getDirectory() if target is None: # User canceled the dialog msg += "<br/>No directory chosen, aborting.<br/>" IJ.showMessage(PluginTitle, msg) return msg += "Selected '" + target + "'as destination folder.<br/>" # determine padding width for filenames pad = len(str(wcount)) for i in range(wcount): # image ID lists start with 1 instead of 0, so for convenience: wid = i + 1 imp = wm.getImage(wid) imgid = wm.getNthImageID(wid) #print "window id:", wid, ", imageID:", wm.getNthImageID(wid) # Construct filename filename = 'tile_' + str(wid).zfill(pad) + '.tif' filepath = target + '/' + filename fs = FileSaver(imp) if imp.getImageStackSize() > 1: if not fs.saveAsTiffStack(filepath): IJ.error("<html>Error saving current image, stopping.") return else: if not fs.saveAsTiff(filepath): IJ.error("<html>Error saving current image, stopping.") return msg += "<br/>Successfully saved " + str(wcount) + " files.<br/>" IJ.showMessage(PluginTitle, msg)
def diagrambuttonPressed(event) : IJ.showMessage("Push 'Auto' button each time you want to see the diagram") x1=10 y1=20 x2=100 y2=50 x3=60 y3=30 xr=10 yr=20 wr=20 hr=20 rect=Rectangle(xr,yr,wr,hr) #img=IJ.getImage() #nbslices=self.__img.getImageStackSize() nbslices=self.__maxLife IJ.run("Hyperstack...", "title=Diagram type=32-bit display=Color width="+str(x2+(nbslices+1)*x3)+" height="+str(y2+y3*len(dico))+" channels=1 slices="+str(len(self.__measures))+" frames=1") im=IJ.getImage() ip=im.getProcessor() for i in range(len(self.__measures)) : indiceligne=0 maxvalue=0 minvalue=1000000 im.setPosition(1,i+1,1) for cellname in self.__listcellname : indiceligne+=1 for indicecolonne in range(1,nbslices+1): rect.setLocation(x2+indicecolonne*x3+int(x3/6),(y1+indiceligne*y3-int(y3/2))) # we create at the first iteration a dictionary with the rectangles (for a future use) if i==0 : self.__gridrectangle[(indiceligne,indicecolonne)]=Rectangle(rect) im.setRoi(rect) ipr=im.getProcessor() # we find the min and max values of the datas for a measure given. if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]>maxvalue : maxvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1] if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]<minvalue : minvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1] # we fill the rectangle with the value of the measure ipr.setValue(self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]) ipr.fill() # we write the names and the n of slices on the image with the maxvalue. ip.setValue(maxvalue) ip.moveTo(x1,y1) ip.drawString(self.__measures[i]) for j in range(1,nbslices+1) : ip.moveTo(x2+j*x3,y1) ip.drawString("Slice "+str(j)) j=0 for cellname in self.__listcellname : ip.moveTo(x1,y2+j*y3) ip.drawString(cellname) j+=1 im.killRoi() im=IJ.run(im,"Fire","") IJ.run("Brightness/Contrast...", "") #im.setMinAndMax(minvalue,maxvalue) #im.updateImage() #we add a mouse listener in order to be able to show the roi corresponding to a rectangle when the user clicks on it. listener = ML() listener.name=imgName for imp in map(WindowManager.getImage, WindowManager.getIDList()): if imp.getTitle().startswith("Diagram") : win = imp.getWindow() if win is None: continue win.getCanvas().addMouseListener(listener)
def helpbuttonPressed(event) : IJ.showMessage("TO DO")
from org.python.core import codecs codecs.setDefaultEncoding('utf-8') from MorphoBact import Morph from BacteriaCell import Bacteria_Cell from CellsSelection import CellsSelection imp=IJ.getImage() hs=3 sw=1 #Color.blue, Color.green, Color.magenta, Color.orange, Color.yellow #red=Color(255,0,0) #green=Color(0,255,0) IJ.showMessage("Select the folder 'Cells' containing the cells to import") selectdir=IJ.getDirectory("image") selectdir=IJ.getDirectory("") #pathdir=str(selectdir).rsplit("/", 2)[0]+"/ROIs/" pathdir=os.path.join(os.path.split(os.path.split(selectdir)[0])[0], "ROIs", "") #rootdir=str(selectdir).rsplit("/", 2)[0]+"/" rootdir=os.path.join(os.path.split(os.path.split(selectdir)[0])[0], "") listfilescells=[] listrois=[] listfilescells.extend(glob.glob(selectdir+"*")) listrois.extend(glob.glob(pathdir+"*")) #allcells=[]
def __ImportCells(self, imagesnames) : #self.__dictCells[imgName]={} rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") listpaths = [] listfilescells=[] if self.__optionImages : IJ.showMessage("Select the folder 'Cells' containing the cells to import") selectdir=IJ.getDirectory("image") selectdir=IJ.getDirectory("") listfilescells.extend(glob.glob(selectdir+os.path.sep+"*")) listpaths.append("") else : IJ.showMessage("Select the text file containing the list cell paths (listpaths.txt)") selectdir=IJ.getDirectory("current") frame = Frame("Text file settings ?") fd = FileDialog(frame) fd.setDirectory(selectdir) fd.show() selectdir = fd.getDirectory() textfile = fd.getFile() fichier = open(selectdir+textfile,"r") listpaths=[ glob.glob(f.split("\n")[0]+"Selected-Cells"+os.path.sep+"*") for f in fichier.readlines()] #for f in templist : # listpaths.append(f.split("\n")+"Cells") listfilescells.append("") if listfilescells[0]=="" : importmode = True else : importmode = False for j in range(len(listpaths)) : self.__dictCells[imagesnames[j]]={} if importmode : listfilescells = listpaths[j] pathtemp = [] for cellfile in listfilescells : filetemp = open(cellfile,"r") linestemp=filetemp.readlines() for line in linestemp : params=line.split("=") values=params[1].split("\n") if params[0] == "NAMECELL" : celltemp=Bacteria_Cell(str(values[0])) self.__dictCells[imagesnames[j]][values[0]]=celltemp self.__dictMeasures[self.__dictCells[imagesnames[j]][values[0]]]={} if params[0] == "PATHROIS" : pathtemp.append(str(values[0])) if params[0] == "NSLICES" : for i in range(int(values[0])) : celltemp.getListRoi().append("") if params[0] == "SLICEINIT" : celltemp.setSlideInit(int(values[0])) for i in range(int(values[0])-2) : celltemp.setRoi("NOT HERE YET",i) if params[0] == "SLICEEND" : celltemp.setSlideEnd(int(values[0])) for i in range(int(values[0])) : celltemp.setRoi("LOST",i) if params[0] == "COLOR" : colorstemp=values[0].split(";") celltemp.setColor(Color(int(colorstemp[0]),int(colorstemp[1]),int(colorstemp[2]))) indiceroi=0 ind=0 tempimp = WindowManager.getImage(imagesnames[j]) if tempimp is not None : IJ.selectWindow(imagesnames[j]) tempimp.show() else : if imagesnames[j][-4:]==".tif" : IJ.selectWindow(imagesnames[j][:-4]) tempimp = IJ.getImage() else : IJ.selectWindow(imagesnames[j]+".tif") tempimp = IJ.getImage() rm.runCommand("reset") for cellname in self.__dictCells[imagesnames[j]].keys() : rm.runCommand("Open", pathtemp[ind]) ind+=1 nbtemp=self.__dictCells[imagesnames[j]][cellname].getLifeTime() for i in range(nbtemp) : rm.select(tempimp, indiceroi) roi=rm.getSelectedRoisAsArray()[0] self.__dictCells[imagesnames[j]][cellname].setRoi(roi,i+self.__dictCells[imagesnames[j]][cellname].getSlideInit()-1) indiceroi+=1 IJ.run("Show Overlay", "") rm.runCommand("UseNames", "true") rm.runCommand("Associate", "true") IJ.run(tempimp, "Labels...", "color=red font=12 show use") if rm.getCount()>0 : IJ.run(tempimp, "From ROI Manager", "") rm.runCommand("Show None") rm.runCommand("Show All") roipath = os.path.split(pathtemp[0])[0]+os.path.sep rootpath = roipath.rsplit(os.path.sep, 2)[0]+os.path.sep self.__listpaths[j] = rootpath self.__rootpath=rootpath
def confirmLoading(): """Acknowledges accessibility to this file""" from ij import IJ IJ.showMessage("BAR lib successfully loaded!")
return tw #- - - M A I N - - - -------------------------------------------------------------------------------------------------- inputDir = DirectoryChooser("DotSeg Preprocess Batch Extension - Please choose directory containing the images").getDirectory() saveFolder = pth.join(pth.split(pth.dirname(inputDir))[0], G_saveSubFold) print "Will save results in folder ", saveFolder regEx = re.compile('ppcd_(?P<name>p\d+_c\d+).tif$', re.IGNORECASE) # create list of match objects of .tif files in directory moFileList = [] # match object File list for fileName in listdir(inputDir): if regEx.match(fileName): # if matches RE, add to list moFileList.append(regEx.match(fileName)) print "Will process files ", moFileList if moFileList == []: IJ.showMessage("Input Exception", "Directory does not contain any preprocessed images.") raise IOError("Input Exception: Directory does not contain any preprocessed images.") if not pth.exists(saveFolder): # check if directory for analysis-files is present makedirs(saveFolder) for image in moFileList: # get rid of 0! print "starting with cell " + image.group() + " " + "("+ str(moFileList.index(image)) + "/" + str(len(moFileList)) + ")" imp = Opener().openImage(inputDir + image.group()) # open Image # read calibration for later calculation of distances in um. calibration = imp.getCalibration() pxWidth = calibration.pixelWidth print "px depth", calibration.pixelDepth timeInterval = round(calibration.frameInterval) #start measurement
original) # duplicate the original image, only the CFOV CFOV.setTitle("CFOV") CFOV.show() ######### Nema process including Re-bin image to larger pixels ################################################################################ desired_pixel_width = getPixel( ) # 6.4 mm default, remember tolerance is +/-30% current_pixel_width = CFOV.getCalibration( ).pixelWidth #get pixel width, 1.16 mm shrink_factor = int(desired_pixel_width / current_pixel_width) # must be an integer IJ.run(CFOV, "Bin...", "x=" + str(shrink_factor) + " y=" + str(shrink_factor) + " bin=Sum") # run the bin plugin IJ.run(CFOV, "Convolve...", "text1=[1 2 1\n2 4 2\n1 2 1\n] normalize") # apply the nema filter ######## Analyse pixels CFOVpixels = CFOV.getProcessor().convertToFloat().getPixels( ) # access processor, get float array of pixels CFOVmean = sum(CFOVpixels) / len(CFOVpixels) #pixels_above_threshold = filter(lambda pix: pix > 0.75*mean, pixels) # return a new array with values above zero, use anonymous function CFOVunifiormity = getUniformity(min(CFOVpixels), max(CFOVpixels)) ######## Print results results_string = "The integral uniformity of the CFOV is: " + str( CFOVunifiormity) + "% for pixel size of " + str( desired_pixel_width) + " mm" IJ.log(results_string) IJ.showMessage(results_string)
def __midline(self): debug=False #print "line 251", self.__boolML if self.__boolML : ordpoints=self.__midLine[:] npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) return polyOrd #if self.getMaxF()<15 : return None #self.__FeretAxis() #return self.__line self.__boolML=True self.__image.killRoi() self.__image.setRoi(self.__contour) boundRect=self.__contour.getBounds() boundRoi=Roi(boundRect) xori=boundRect.x yori=boundRect.y wori=boundRect.width hori=boundRect.height ip2 = ByteProcessor(self.__image.getWidth(), self.__image.getHeight()) ip2.setColor(255) ip2.setRoi(self.__contour) ip2.fill(self.__contour) skmp=ImagePlus("ip2", ip2) skmp.setRoi(xori-1,yori-1,wori+1,hori+1) ip3=ip2.crop() skmp3=ImagePlus("ip3", ip3) skmp3.killRoi() #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l287") #------------------------------------------------------------- IJ.run(skmp3, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l294") #------------------------------------------------------------- IJ.run(skmp3, "BinaryConnectivity ", "white") ip3.setThreshold(3,4, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(skmp3, "Convert to Mask", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l302") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.updateAndDraw() skmp3.show() IJ.showMessage("imp3 l308") #------------------------------------------------------------- rawPoints=[] w=ip3.getWidth() h=ip3.getHeight() rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] tempbouts=[val for val in rawPoints if val[2]==2] if len(tempbouts)!=2 : return None # test #if len(tempbouts)!=2 : # # IJ.run(skmp3, "BinaryConnectivity ", "white") # ip3.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) # IJ.run(skmp3, "Convert to Mask", "") # #------------------------------------------------------------- # if debug==debug : # skmp3.updateAndDraw() # skmp3.show() # IJ.showMessage("if test l 328") ##------------------------------------------------------------- # rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] # tempbouts=[val for val in rawPoints if val[2]==2] ip3.setRoi(boundRect) if rawPoints==[]: return None npoints=len(rawPoints) xpoints=[point[0] for point in rawPoints] ypoints=[point[1] for point in rawPoints] valpoints=[point[2] for point in rawPoints] bouts={} if tempbouts==[]: return None if tempbouts[0][1]>tempbouts[1][1]: bouts["A"]=tempbouts[0] bouts["B"]=tempbouts[1] else: bouts["A"]=tempbouts[1] bouts["B"]=tempbouts[0] rawPoints.remove(bouts["A"]) rawPoints.remove(bouts["B"]) rawPoints.append(bouts["B"]) tempList=[val for val in rawPoints] p=bouts["A"] Dist={} ordPoints=[] for j in range(len(rawPoints)): Dist.clear() for i in range(len(tempList)): dx=p[0]-tempList[i][0] dy=p[1]-tempList[i][1] d=math.sqrt(dx*dx+dy*dy) Dist[d]=tempList[i] distList=Dist.keys() mind=min(distList) nextpoint=Dist[mind] ordPoints.append(nextpoint) tempList.remove(nextpoint) p=nextpoint ordPoints.insert(0, bouts["A"]) npoints=len(ordPoints) if npoints < 4 : return None xpoints=[point[0] for point in ordPoints] ypoints=[point[1] for point in ordPoints] polyOrd1=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) f=min(self.__midParams[0], len(xpoints)//2) angleA1=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[1],ypoints[1]) angleA2=polyOrd1.getAngle(xpoints[1],ypoints[1], xpoints[2],ypoints[3]) angleA = (angleA1+angleA2)/2.00 angleA=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[f],ypoints[f]) angleA=angleA*(math.pi/180) angleB1=polyOrd1.getAngle(xpoints[-2],ypoints[-2], xpoints[-1],ypoints[-1]) angleB2=polyOrd1.getAngle(xpoints[-3],ypoints[-3], xpoints[-2],ypoints[-2]) angleB = (angleB1+angleB2)/2.00 angleB=polyOrd1.getAngle(xpoints[-f],ypoints[-f], xpoints[-1],ypoints[-1]) angleB=angleB*(math.pi/180) coef=self.__midParams[1] xa = xpoints[0]-coef*f*math.cos(angleA) ya = ypoints[0]+coef*f*math.sin(angleA) xb = xpoints[-1]+coef*f*math.cos(angleB) yb = ypoints[-1]-coef*f*math.sin(angleB) lineA=Line(xpoints[0],ypoints[0], xa, ya) lineB=Line(xpoints[-1],ypoints[-1], xb, yb) lineA.setWidth(0) lineB.setWidth(0) lineA.setStrokeWidth(0) lineB.setStrokeWidth(0) ip2.setColor(0) ip2.fill() ip2.setColor(255) ip2.setRoi(lineA) lineA.drawPixels(ip2) ip2.setRoi(lineB) lineB.drawPixels(ip2) ip2.setRoi(self.__contour) ip2.setColor(0) ip2.fillOutside(self.__contour) ip2=ip2.crop() imb=ImagePlus("new-ip2", ip2) #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l416") #------------------------------------------------------------- w2=ip2.getWidth() h2=ip2.getHeight() ip4 = ByteProcessor(w2+2, h2+2) im4=ImagePlus("im4", ip4) for i in range(w2): for j in range(h2): ip4.set(i+1,j+1,max([ip2.getPixel(i,j),ip3.getPixel(i,j)])) #im4.show() #------------------------------------------------------------- if debug : im4.show() IJ.showMessage("im4 l430") #------------------------------------------------------------- im4.killRoi() #IJ.run(im4, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l300") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") ip4=im4.getProcessor() rawPoints2=[] w4=ip4.getWidth() h4=ip4.getHeight() rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] # test if len(self.__MidBouts)!=2 : IJ.run(im4, "BinaryConnectivity ", "white") ip4.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(im4, "Convert to Mask", "") rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] ordpoints=[] p0=self.__MidBouts[0] rawPoints2.remove(p0) c=0 while p0!=self.__MidBouts[1]: if c<len(rawPoints2): point=rawPoints2[c] else: break if abs(point[0]-p0[0])<2 and abs(point[1]-p0[1])<2: p0=point ordpoints.append(point) rawPoints2.remove(point) c=0 else: c=c+1 ordpoints.insert(0, self.__MidBouts[0]) self.__midLine=ordpoints[:] self.__midCenters = self.__Centers(self.__midLine) npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) #print self.__midLine #print self.__MidBouts #print xpoints #print ypoints return polyOrd
# What about changing the ROI properties (color, name # name, dimensions, etc.) of the Rectangle created in # the previous exercise? Lets ask ourselves about it: from ij import IJ import ij.gui.YesNoCancelDialog as dialog # Let's prompt us for the question: question_prompt = dialog( IJ.getInstance(), # 1st argument: Parent frame "What about ROI properties?", # 2nd argument: Dialog title "Can you change the ROI color, its name, etc?" # 3rd argument: Dialog message ) # see http://javadoc.imagej.net/ImageJ1/index.html?ij/gui/YesNoCancelDialog.html # Let's get the answer: if question_prompt.cancelPressed(): # Was the dialog canceled? IJ.showMessage("Refuse to answer? Are you tired?") elif question_prompt.yesPressed(): # Was the answer "Yes"? IJ.showMessage("Cool. Go ahead!") else: # If none of the above, the remaining option was "No" IJ.showMessage("Hmmm... Did you look into the ij.gui.Roi API?") # Tip 1: You will find useful methods in: # - http://javadoc.imagej.net/ImageJ1/index.html?ij/gui/Roi.html # - http://javadoc.imagej.net/ImageJ1/index.html?ij/ImagePlus.html # # Tip 2: Let the recorder do it for you # - Plugins> Macros> Record... # - Select a scripting language (e.g. BeanShell) # - Set your prefered options in Edit>Selection>Properties # Q1: What was the string produced by the recorder? # Q2: How can it be incorporated in the previous exercise?
for ndId, tagNames in candidateTable.iteritems(): nd = candidateIdVsNode[ndId] isCandidate = False votes = [] for tagName in tagNames: if candidateRe.match(tagName): isCandidate = True if voteRe.match(tagName): votes.append(tagName) if isCandidate: if 1 != len(votes): # one and only one vote should exist print "found missing vote" nMissingVotes = nMissingVotes + 1 nd.addTag(Tag("REVOTE-this", KeyEvent.VK_R)) print "done." return nMissingVotes ## run checking votes with a dialogue hint firstProject = Project.getProjects().get(0) if IJ.showMessageWithCancel("Checking Votes For TrakEM2 Project", "Will now check for missing votes in TrakEM2 project:\n"+firstProject.getTitle()): n = checkVotes(firstProject) if 0 == n: msg = "Well done! All candidates ara voted in:\n"+firstProject.getTitle() else: msg = str(n)+" votes missing in project:\n"+firstProject.getTitle()+"\n \nSearch REVOTE- to view missed votes.\nPlease re-check after appending missing votes." IJ.showMessage("Checking Votes Done", msg)
# IJ BAR: https://github.com/tferr/Scripts#scripts # # Imports numeric values copied to the clipboard into the Results table. It is # now deprecated. It was of utility prior to BAR v1.1.7, when BARs that analyzed # tabular data could only read values from the main IJ "Results" table. It is # included here as a programming example. # # Requirements: Requires BAR_-XX.jar to be installed in the plugins folder of IJ # # NB: When copying data from withing IJ (e.g., lists from histograms or plot profiles), # Use Edit>Options>Input/Output... to specify if column headers/row numbers should be # copied to the clipboard import os, tempfile from bar import Utils as barUtils from ij import IJ from ij.plugin.filter import Analyzer import ij.measure.ResultsTable as RT fd, path = tempfile.mkstemp() try: os.write(fd, barUtils.getClipboardText()) os.close(fd) rt = RT.open(path) #IOException if getClipboardText()=="" if Analyzer.resetCounter(): rt.show("Results") except: IJ.showMessage("Could not place clipboard into Results table.") finally: os.remove(path)
def run_trackmate(imp, path, filename, params, batch_mode=False): # initialize trackmate model model = Model() # Set logger - use to see outputs, not needed in batch mode model.setLogger(Logger.IJ_LOGGER) # Create setting object from image settings = Settings() settings.setFrom(imp) cal = imp.getCalibration() model.setPhysicalUnits("micron", "sec") # Configure detector settings.detectorFactory = LogDetectorFactory() # settings.detectorFactory = DogDetectorFactory() settings.detectorSettings = { 'DO_SUBPIXEL_LOCALIZATION': params.do_subpixel_localization, 'RADIUS': params.radius, 'TARGET_CHANNEL': 0, 'THRESHOLD': params.threshold, 'DO_MEDIAN_FILTERING': params.do_median_filtering, } # print(params) # Add spot filters filter_quality = FeatureFilter('QUALITY', params.quality, True) settings.addSpotFilter(filter_quality) filter_snr = FeatureFilter('SNR', params.snr, True) settings.addSpotFilter(filter_snr) # Compute spot features settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory()) settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory()) # Compute track features settings.addTrackAnalyzer(TrackBranchingAnalyzer()) settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackIndexAnalyzer()) settings.addTrackAnalyzer(TrackLocationAnalyzer()) settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer()) settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer()) # Update model ModelFeatureUpdater(model, settings) # Configure tracker settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() settings.trackerSettings[ 'LINKING_MAX_DISTANCE'] = params.linking_max_distance settings.trackerSettings[ 'GAP_CLOSING_MAX_DISTANCE'] = params.gap_closing_max_distance settings.trackerSettings['MAX_FRAME_GAP'] = params.max_frame_gap # Add track filters filter_T1 = FeatureFilter('TRACK_DURATION', params.track_duration, True) filter_MTD = FeatureFilter('TRACK_DISPLACEMENT', params.track_displacement, True) settings.addTrackFilter(filter_T1) settings.addTrackFilter(filter_MTD) # Instantiate trackmate trackmate = TrackMate(model, settings) # Execute all ok = trackmate.checkInput() if not ok: IJ.showMessage("No spots found... Adjust detection parameter.\n" + str(trackmate.getErrorMessage())) sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: IJ.showMessage("No spots found... Adjust detection parameter.\n" + str(trackmate.getErrorMessage())) sys.exit(str(trackmate.getErrorMessage())) filename = os.path.splitext(filename)[0] #filename without extension outFile = File(os.path.join(path, filename + "_Tracks.xml")) ExportTracksToXML.export(model, settings, outFile) #imp.close() tm_writer = TmXmlWriter(File(os.path.join(path, filename + "_TM.xml"))) tm_writer.appendModel(model) tm_writer.appendSettings(settings) tm_writer.writeToFile() if not batch_mode: selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp) displayer.render() displayer.refresh() # Echo results with the logger we set at start: model.getLogger().log(str(model))
def ColMigBud(): def setupDialog(imp): gd = GenericDialog("Collective migration buddy options") gd.addMessage("Collective migration buddy 2.0, you are analyzing: " + imp.getTitle()) calibration = imp.getCalibration() if (calibration.frameInterval > 0): default_interval = calibration.frameInterval default_timeunit = calibration.getTimeUnit() else: default_interval = 8 default_timeunit = "min" gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals gd.addCheckbox("Do you want to use a gliding window?", True) gd.addCheckbox( "Project hyperStack? (defaluts to projecting current channel only)", False) gd.addStringField("time unit", default_timeunit, 3) gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice('Method to use for frame projection:', methods_as_strings, methods_as_strings[5]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd #Start by getting the active image window and get the current active channel and other stats imp = WindowManager.getCurrentImage() cal = imp.getCalibration() nSlices = 1 #TODO fix this in case you want to do Z-stacks title = imp.getTitle() current_channel = imp.getChannel() #zp = ZProjector(imp) #Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] medthod_dict = dict(zip(methods_as_strings, methods_as_const)) # Run the setupDialog, read out and store the options gd = setupDialog(imp) frame_interval = gd.getNextNumber() time_unit = gd.getNextString() glidingFlag = gd.getNextBoolean() hyperstackFlag = gd.getNextBoolean() #Set the frame interval and unit, and store it in the ImagePlus calibration cal.frameInterval = frame_interval cal.setTimeUnit(time_unit) imp.setCalibration(cal) start_frame = int(gd.getNextNumber()) stop_frame = int(gd.getNextNumber()) #If a subset of the image is to be projected, these lines of code handle that if (start_frame > stop_frame): IJ.showMessage("Start frame > Stop frame, can't go backwards in time!") raise RuntimeException("Start frame > Stop frame!") if ((start_frame != 1) or (stop_frame != imp.getNFrames())): imp = Duplicator().run(imp, 1, nChannels, 1, nSlices, start_frame, stop_frame) no_frames_per_integral = int(gd.getNextNumber()) #the doHyperstackProjection method can't project past the end of the stack if hyperstackFlag: total_no_frames_to_project = imp.getNFrames() - no_frames_per_integral #the doProjection method can project past the end, it just adds black frames at the end #When not projecting hyperstacks, just copy the current active channel from the active image else: total_no_frames_to_project = imp.getNFrames() imp = Duplicator().run(imp, current_channel, current_channel, 1, nSlices, start_frame, stop_frame) #The Z-Projection magic happens here through a ZProjector object zp = ZProjector(imp) projection_method = gd.getNextChoice() chosen_method = medthod_dict[projection_method] zp.setMethod(chosen_method) outstack = imp.createEmptyStack() if glidingFlag: frames_to_advance_per_step = 1 else: frames_to_advance_per_step = no_frames_per_integral for frame in range(1, total_no_frames_to_project, frames_to_advance_per_step): zp.setStartSlice(frame) zp.setStopSlice(frame + no_frames_per_integral) if hyperstackFlag: zp.doHyperStackProjection(False) projected_stack = zp.getProjection().getStack() for channel in range(projected_stack.getSize()): outstack.addSlice(projected_stack.getProcessor(channel + 1)) else: zp.doProjection() outstack.addSlice(zp.getProjection().getProcessor()) #Create an image processor from the newly created Z-projection stack nChannels = imp.getNChannels() nFrames = outstack.getSize() / nChannels imp2 = ImagePlus( title + '_' + projection_method + '_' + str(no_frames_per_integral) + '_frames', outstack) imp2 = HyperStackConverter.toHyperStack(imp2, nChannels, nSlices, nFrames) imp2.show() Startmenu()
def alignbuttonPressed(event) : IJ.showMessage("TO DO")
def main(imp, tolerance, window_radius, pixel_size_nm, out_dir): # set output dir out_dir = str(out_dir) # Find maxima excludeOnEdge = True polygon = MaximumFinder().getMaxima(imp.getProcessor(), tolerance, excludeOnEdge) roi = PointRoi(polygon) # get RoiManager rm = RoiManager.getInstance(); if rm is None: rm = RoiManager() # Check if output table is writable out_table_fn = os.path.join(out_dir, "fwhm_values.txt") try: file_handle = open(out_table_fn, 'w') except IOError: IJ.showMessage("Output file '' not writeable. Check if file is open in Excel...") sys.exit(0) # iterate and write output with file_handle as csvfile: writer = csv.DictWriter(csvfile, fieldnames=["id", "peak_id", "x_pos", "y_pos", "type", "fwhm", "fwhm_nm", "r2_GoF", "avg_fwhm", "area_profile", "area_gauss"], delimiter="\t", lineterminator='\n') writer.writeheader() id_ = 0 # over all peaks for i, p in list(enumerate(roi)): IJ.showProgress(i, roi.getNCounters() +1) # Horizontal lroi = Line(p.x+0.5-window_radius, p.y+0.5, p.x+0.5+window_radius, p.y+0.5) output = fit_gauss(lroi, imp, p, i, id_, "H", rm) writer.writerow(output) id_+=1 # Vertical lroi = Line(p.x+0.5, p.y+0.5-window_radius, p.x+0.5, p.y+0.5+window_radius) output = fit_gauss(lroi, imp, p, i, id_, "V", rm) writer.writerow(output) id_+=1 # Diagonal 1 lroi = Line(p.x+0.5-MN*window_radius, p.y+0.5+MN*window_radius, p.x+0.5+MN*window_radius, p.y+0.5-MN*window_radius) output = fit_gauss(lroi, imp, p, i, id_, "D1", rm) writer.writerow(output) id_+=1 # Diagonal 2 lroi = Line(p.x+0.5-MN*window_radius, p.y+0.5-MN*window_radius, p.x+0.5+MN*window_radius, p.y+0.5+MN*window_radius) output = fit_gauss(lroi, imp, p, i, id_, "D2", rm) writer.writerow(output) id_+=1 IJ.showProgress(1) rm.runCommand("Deselect"); # deselect ROIs to save them all rm.runCommand("Save", os.path.join(out_dir, "fwhm_fiji_rois.zip")) IJ.showMessage("FWHM on Spots: Done")
def mergebuttonPressed(event) : IJ.showMessage("TO DO")
""" listNormal.insert(0,0) return listNormal ############### ## MAIN CODE ## ############### # Get the ImagePlus of the current image imp = WindowManager.getCurrentImage() nbrChannels = imp.getNChannels() # Check if file is lambda stack # by counting the number of channels if nbrChannels == 1: IJ.showMessage("Not a stack!") raise Exception("Not a stack!") # Get the name of the file with and without # extension. title = imp.getTitle(); shortTitle = os.path.splitext(title)[0] # Create output folder corresponding # to image is not existing. Will be # created in the user home folder. home = expanduser("~") output = os.path.join(home,shortTitle) if not os.path.exists(output): os.mkdir(output)
def __addroi(self, event) : if ( not self.__init) : IJ.showMessage("", "please start a new stack") return if ( not self.__initDIA) : IJ.showMessage("", "please select an image for DIA") return if ( not self.__initFLUO) : IJ.showMessage("", "please select an image for FLUO") return twres = TextWindow("measures-"+self.__name, "label\tname\tsol\tarea\tcirc\tAR\tFeret\taxis\traf\tdMajor\tdFeret\tdArea", "", 300, 450) tab="\t" self.__widthl = self.__display2.getText() IJ.selectWindow(self.__impF.getTitle()) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() if self.__impF.getImageStackSize() > 1 : roisarray =[(roi, self.__rm.getSliceNumber(roi.getName())) for roi in self.__rm.getRoisAsArray()] else : roisarray =[(roi, 1) for roi in self.__rm.getRoisAsArray()] self.__rm.runCommand("reset") #self.__rm.runCommand("Delete") IJ.selectWindow(self.__impF.getTitle()) self.__maxraf=float(self.__display19.text) self.__minraf=float(self.__display20.text) count=1 for roielement in roisarray : roi = roielement[0] pos = roielement[1] lab = self.__impF.getImageStack().getShortSliceLabel(pos) if lab==None : lab=str(pos) if self.__conEllipses : IJ.selectWindow(self.__impF.getTitle()) self.__impF.setSlice(pos) self.__impF.setRoi(roi) self.__rm.runCommand("Add") IJ.run(self.__impF, "Fit Ellipse", "") ellipse=self.__impF.getRoi() params = ellipse.getParams() ferets = ellipse.getFeretValues() imp2 = Duplicator().run(self.__impF,pos,pos) IJ.run(imp2, "Rotate... ", "angle="+str(ferets[1])+" grid=0 interpolation=Bilinear enlarge slice") temproi=Roi((imp2.getWidth()-ferets[0])/2.0,(imp2.getHeight()-ferets[2])/2.0,ferets[0],ferets[2]) imp2.setRoi(temproi) imp3 = Duplicator().run(imp2,1,1) ip3=imp3.getProcessor() if int(self.__display5.text) < ip3.getWidth() < int(self.__display6.text) : self.__iplist.append(ip3) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) fer=Line(params[0],params[1],params[2],params[3]) self.__cellsrois.append((fer, pos)) self.__labels.append(self.__isF.getShortSliceLabel(pos)) m=Morph(self.__impF, roi) twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(fer.getLength())+tab+str(1)+tab+str(0)+tab+str(0)+tab+str(0)) self.__dictCells[count]=(str(roi.getName()), lab, roi) count=count+1 continue if roi.getType() in [6,7] : self.__impF.setSlice(pos) self.__impF.setRoi(roi) self.__rm.runCommand("Add") elif roi.getType() in [2,4] : self.__impF.setSlice(pos) self.__impF.setRoi(roi) m=Morph(self.__impF, roi) m.setMidParams(10, 2) midroi=m.MidAxis if midroi == None : continue raf = m.MaxFeret/midroi.getLength() if (self.__maxraf < raf) or (raf < self.__minraf) : continue maxsol = float(self.__display7.text) minsol = float(self.__display8.text) maxarea = float(self.__display9.text) minarea = float(self.__display10.text) maxcirc = float(self.__display11.text) mincirc = float(self.__display12.text) maxar = float(self.__display13.text) minar = float(self.__display14.text) maxfer = float(self.__display15.text) minfer = float(self.__display16.text) maxmean = float(self.__display17.text) minmean = float(self.__display18.text) maxmferet = float(self.__display21.text) minmferet = float(self.__display22.text) testsol = (minsol< m.Solidity < maxsol) testarea = (minarea< m.Area < maxarea) testcirc = (mincirc< m.Circ < maxcirc) testar = (minar< m.AR < maxar) testfer = (minfer< m.MaxFeret < maxfer) testmean = (minmean < m.Mean < maxmean) testmferet = (minmferet < m.MinFeret < maxmferet) #print minmferet , m.MinFeret , maxmferet test = (testsol+testarea+testcirc+testar+testfer+testmean+testmferet)/7 if test : fmaj, ffmx, fa =[],[],[] for r in m.getMidSegments(10, 40, 0) : if r == None : continue m2=Morph(self.__impF, r) fmaj.append(m2.Major) ffmx.append(m2.MaxFeret) fa.append(m2.Area) diffmajor, diffferet, diffarea = 0,0,0 if len(fa) > 4 : medfmaj = self.listmean(fmaj[1:-1]) medffmx = self.listmean(ffmx[1:-1]) medfa = self.listmean(fa[1:-1]) diffmajor = (max(fmaj[1:-1])-medfmaj)/medfmaj diffferet = (max(ffmx[1:-1])-medffmx)/medffmx diffarea = (max(fa[1:-1])-medfa)/medfa twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea)) #print lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea) self.__impF.setRoi(roi) self.__rm.runCommand("Add") self.__impF.killRoi() self.__impF.setRoi(midroi) #self.__dictCells[str(roi.getName())]=(str(roi.getName()), lab, roi) self.__dictCells[count]=(str(roi.getName()), lab, roi) count=count+1 else : #print "test falls" continue else : print "out loop" continue straightener = Straightener() new_ip = straightener.straighten(self.__impF, midroi, int(self.__widthl)) if int(self.__display5.text) < new_ip.getWidth() < int(self.__display6.text) : self.__iplist.append(new_ip) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) #print "add", roi.getName(), roi.getType() self.__cellsrois.append((midroi, pos)) self.__labels.append(self.__isF.getShortSliceLabel(pos)) #roisarray=self.__rm.getRoisAsArray() #self.__rm.runCommand("reset") #self.__rm.runCommand("Delete") self.__impD.killRoi() self.__impF.killRoi() IJ.selectWindow(self.__impD.getTitle())
from ij import IJ IJ.showMessage("Hello World")
def glidingprojection(imp, startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median"): """This function subtracts the gliding projection of several frames from the input stack. Thus, everything which moves too fast is filtered away. Args: imp (ImagePlus): Input image as ImagePlus object. startframe (int, optional): Choose a start frame. Defaults to 1. stopframe (int, optional): Choose an end frame. Defaults to None. glidingFlag (bool, optional): Should a gliding frame by frame projection be used? Defaults to True. no_frames_per_integral (int, optional): Number of frames to project each integral. Defaults to 3. projectionmethod (str, optional): Choose the projection method. Options are 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. Defaults to "Median". Raises: RuntimeException: Start frame > stop frame. Returns: ImagePlus: The output stack. """ # Store some image properties. cal = imp.getCalibration() width, height, nChannels, nSlices, nFrames = imp.getDimensions() title = imp.getTitle() # Some simple sanity checks for input parameters. if stopframe == None: stopframe = nFrames if (startframe > stopframe): IJ.showMessage("Start frame > Stop frame, can't go backwards in time!") raise RuntimeException("Start frame > Stop frame!") # If a subset of the image is to be projected, these lines of code handle that. if ((startframe != 1) or (stopframe != nFrames)): imp = Duplicator().run(imp, 1, nChannels, 1, nSlices, startframe, stopframe) # Define the number of frames to advance per step based on boolean input parameter glidingFlag. if glidingFlag: frames_to_advance_per_step = 1 else: frames_to_advance_per_step = no_frames_per_integral # Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] method_dict = dict(zip(methods_as_strings, methods_as_const)) # Initialize a ZProjector object and an empty stack to collect projections. zp = ZProjector(imp) zp.setMethod(method_dict[projectionmethod]) outstack = imp.createEmptyStack() # Loop through all the frames in the image, and project that frame with the other frames in the integral. for frame in range(1, nFrames + 1, frames_to_advance_per_step): zp.setStartSlice(frame) zp.setStopSlice(frame + no_frames_per_integral) zp.doProjection() outstack.addSlice(zp.getProjection().getProcessor()) # Create an image processor from the newly created Z-projection stack # nFrames = outstack.getSize()/nChannels impout = ImagePlus( title + '_' + projectionmethod + '_' + str(no_frames_per_integral) + '_frames', outstack) impout = HyperStackConverter.toHyperStack(impout, nChannels, nSlices, nFrames) impout.setCalibration(cal) return impout
def __add(self, event): if ( not self.__init) : IJ.showMessage("", "please start a new stack") return if ( not self.__initDIA) : IJ.showMessage("", "please select an image for DIA") return if ( not self.__initFLUO) : IJ.showMessage("", "please select an image for FLUO") return self.__widthl = self.__display2.getText() roi = self.__impD.getRoi() if roi == None : IJ.showMessage("", "No selection") return if roi.getType() in [6,7] : nslice = self.__impD.getCurrentSlice() self.__impF.setSlice(nslice) self.__impF.setRoi(roi) elif roi.getType() in [2,4] : nslice = self.__impD.getCurrentSlice() self.__impF.setSlice(nslice) m=Morph(self.__impF, roi) m.setMidParams(10, 2) roi=m.MidAxis if roi == None : self.__display.text = "roi fail" if not self.__skip : IJ.showMessage("", "failed roi, please draw it as polyline") return #if roi.getType() != 6 : self.__impF.setRoi(roi) else : IJ.showMessage("", "This selection is not yet allowed") return self.__impF.setRoi(roi) straightener = Straightener() new_ip = straightener.straighten(self.__impF, roi, int(self.__widthl)) self.__iplist.append(new_ip) self.__labels.append(self.__isF.getShortSliceLabel(nslice)) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) +" width="+str(new_ip.getWidth())+ " height="+ str(new_ip.getHeight()) roi.setPosition(self.__impD.getCurrentSlice()) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() self.__rm.add(self.__impD, roi, len(self.__iplist)) self.__cellsrois.append((roi, self.__impD.getCurrentSlice())) #self.__rm.runCommand("Show All") IJ.selectWindow(self.__impD.getTitle())
# Create a snapshot of the images under the area: imp = loader.getFlatImage(layer, box, 1, 0xffffffff, ImagePlus.GRAY8, Patch, False) # Set the area as a roi imp.setRoi(ShapeRoi(area)) # Perform measurements (uncalibrated) # (To get the calibration, call layerset.getCalibrationCopy()) stats = ByteStatistics(imp.getProcessor(), moptions, calibration) table.incrementCounter() table.addLabel("Name", ali.getTitle()) table.addValue(0, ali.getId()) table.addValue(1, index) # the layer index table.addValue(2, layer.getZ()) table.addValue(3, stats.area) table.addValue(4, stats.mean) # Update and show the table table.show("AreaLists") # Get the front display, if any: display = Display.getFront() if display is not None: # Obtain the LayerSet of the current Display canvas: layerset = Display.getFront().getLayer().getParent() # Measure! measureCustom(display.getFront().getLayer().getParent()) else: IJ.showMessage("Open a TrakEM2 display first!")
channel = gd.getNextChoiceIndex() + 1 # zero-based virtual = gd.getNextBoolean() return channel, virtual 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)) if imp is None: IJ.showMessage("Correct_3D_drift error " + filename + " No image loaded") return if not imp.isHyperStack(): IJ.showMessage("Correct_3D_drift error " + filename +" Not a hyper stack!") return if imp.getNFrames() == 1: IJ.showMessage("Correct_3D_drift error " + filename + ". There is only one time frame!") return if imp.getNSlices() == 1: IJ.showMessage("Correct_3D_drift error " + filename + ". To register slices of a stack, use 'Register Virtual Stack Slices'" ) return if channel == 'last': channel = imp.getNChannels(); if channel > imp.getNChannels():
def run(): IJ.log("Correct_3D_Drift") imp = IJ.getImage() if imp is None: return if 1 == imp.getNFrames(): IJ.showMessage("Cannot register because there is only one time frame.\nPlease check [Image > Properties...].") return options = getOptions(imp) if options is None: return # user pressed Cancel if options['z_min'] < 1: IJ.showMessage("The minimal z plane must be >=1.") return if options['z_max'] > imp.getNSlices(): IJ.showMessage("Your image only has "+str(imp.getNSlices())+" z-planes, please adapt your z-range.") return if options['virtual'] is True: dc = DirectoryChooser("Choose target folder to save image sequence") target_folder = dc.getDirectory() if target_folder is None: return # user canceled the dialog if not validate(target_folder): return else: target_folder = None # # compute drift # IJ.log(" computing drift..."); IJ.log(" at frame shifts of 1"); dt = 1; shifts = compute_and_update_frame_translations_dt(imp, dt, options) # multi-time-scale computation if options['multi_time_scale'] is True: dt_max = imp.getNFrames()-1 # computing drifts on exponentially increasing time scales 3^i up to 3^6 # ..one could also do this with 2^i or 4^i # ..maybe make this a user choice? did not do this to keep it simple. dts = [3,9,27,81,243,729,dt_max] for dt in dts: if dt < dt_max: IJ.log(" at frame shifts of "+str(dt)) shifts = compute_and_update_frame_translations_dt(imp, dt, options, shifts) else: IJ.log(" at frame shifts of "+str(dt_max)); shifts = compute_and_update_frame_translations_dt(imp, dt_max, options, shifts) break # invert measured shifts to make them the correction shifts = invert_shifts(shifts) #print(shifts) # apply shifts if not options['only_compute']: IJ.log(" applying shifts..."); #print("\nAPPLYING SHIFTS:") if options['subpixel']: registered_imp = register_hyperstack_subpixel(imp, options['channel'], shifts, target_folder, options['virtual']) else: shifts = convert_shifts_to_integer(shifts) registered_imp = register_hyperstack(imp, shifts, target_folder, options['virtual']) if options['virtual'] is True: if 1 == imp.getNChannels(): ip=imp.getProcessor() ip2=registered_imp.getProcessor() ip2.setColorModel(ip.getCurrentColorModel()) else: registered_imp.copyLuts(imp) else: if imp.getNChannels() > 1: registered_imp.copyLuts(imp) registered_imp.show() else: if imp.getRoi(): xmin = imp.getRoi().getBounds().x ymin = imp.getRoi().getBounds().y zmin = 0 xmax = xmin + imp.getRoi().getBounds().width - 1 ymax = ymin + imp.getRoi().getBounds().height - 1 zmax = imp.getNSlices()-1 else: xmin = 0 ymin = 0 zmin = 0 xmax = imp.getWidth() - 1 ymax = imp.getHeight() - 1 zmax = imp.getNSlices() - 1 save_shifts(shifts, [xmin, ymin, zmin, xmax, ymax, zmax]) IJ.log(" saving shifts...")
for tagName in tagNames: if candidateRe.match(tagName): isCandidate = True if voteRe.match(tagName): votes.append(tagName) if isCandidate: if 1 != len(votes): # one and only one vote should exist print "found missing vote" nMissingVotes = nMissingVotes + 1 nd.addTag(Tag("REVOTE-this", KeyEvent.VK_R)) print "done." return nMissingVotes ## run checking votes with a dialogue hint firstProject = Project.getProjects().get(0) if IJ.showMessageWithCancel( "Checking Votes For TrakEM2 Project", "Will now check for missing votes in TrakEM2 project:\n" + firstProject.getTitle()): n = checkVotes(firstProject) if 0 == n: msg = "Well done! All candidates ara voted in:\n" + firstProject.getTitle( ) else: msg = str(n) + " votes missing in project:\n" + firstProject.getTitle( ) + "\n \nSearch REVOTE- to view missed votes.\nPlease re-check after appending missing votes." IJ.showMessage("Checking Votes Done", msg)
def run(self) : nextstep=self.__mainsettings() # step 1 if nextstep : nextstep = self.__selectionSettings() # step 2 else : IJ.showMessage("Bye...") return False if nextstep : nextstep = self.__runMethode() # step 3 else : IJ.showMessage("Bye...") return False f = open(self.__pathdir+self.__time+"-listpaths.txt", "w") for i in range(len(self.__imagesnames)) : name = self.__imagesnames[i] if name[-4:]!=".tif" : name=name+".tif" if not self.__batch : IJ.showMessage("Analysis of stack : "+name) self.__pathdir = self.__listpaths[i] while nextstep : if len(self.__imagesnames) > 1 : self.__activeTitle = name if self.__batch : self.__img=WindowManager.getImage(name) IJ.selectWindow(self.__img.getID()) nextstep = True else : nextstep = self.__selectMeasureStack() # step 4 self.__maxLife = self.__img.getImageStackSize() if nextstep : nextstep = self.__settings(name) else : IJ.showMessage("Bye...") return False nextstep=True try : self.__dictCells[name] except KeyError : try : self.__dictCells[name[:-4]] except KeyError : try : self.__dictCells[name+".tif"] except KeyError : print "error" continue else: name = name+".tif" if self.__dictNcells[name] > 0 : f.write(self.__listpaths[i]+"\n") continue else : name = name[:-4] if self.__dictNcells[name] > 0 : f.write(self.__listpaths[i]+"\n") continue if self.__dictNcells[name] > 0 : f.write(self.__listpaths[i]+"\n") continue f.close() return True
def runOnFile(self, afile, show = True, jobnr = None): afile = str(afile) if afile == '' or afile is None: od = OpenDialog("Choose image file", None) if od.getFileName() == None: return afile = os.path.join(od.getDirectory(), od.getFileName()) if '.log' in afile: return try: zk = ZeissKeys() msg = Message() print "Hi" if self.jobs is None: IJ.showMessage("You need to first set the parameters") if all([job['pip']=='None' for job in self.jobs]): IJ.showMessage("Nothing to do! At least on job different than None") return 0 #create a copy otherwise self.jobs gets overwritten jobs = copy.deepcopy(self.jobs) random.seed() #create a roiManager in case one is missing and reset it roim = RoiManager.getInstance() if roim == None: roim = RoiManager() roim.runCommand("reset") for i, job in enumerate(self.jobs): jobl = job #not really necessary if jobl['pip'] == 'None': continue self.JOBS_DICT[jobl['pip']] + jobl['task'] + "_" if jobnr is not None: if jobnr == i: #force opening imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task']), 1) else: continue else: imageDef = self.openFile(afile, self.getPrefix(self.JOBS_DICT[jobl['pip']], jobl['task'])) print imageDef jobl['channel'] = int(jobl['channel']) if imageDef is None: continue #clean up registry for errors IJ.log("Clean up errorMsg registry") IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_errormsg+" value=[""] windows=REG_SZ") [imageC, pixelSize, filepath, filename] = imageDef if jobl['channel'] > len(imageC): raise IOError('Expecting at least ' + str(jobl['channel']) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)') self.rois = [None]*self.nrOfJobs self.Segs = [None]*self.nrOfJobs self.Procs = [None]*self.nrOfJobs #switch color to Cyan for better visibility IJ.run(imageC[jobl['channel']-1], "Cyan", "") #segment self.Procs[i], self.Segs[i], validParticles, self.rois[i] = segmentChannel_Weka(imageC, **jobl) if validParticles is None: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ") #write values to registry try: executeTask_Weka(validParticles, **jobl) except Exception, err: self.exitWithError(str(err)) return if self.rois[i] is None: imageC[jobl['channel']-1].show() self.Segs[i].show() self.Procs[i].show() continue if validParticles is None: particle = [] else: particle = [part[0] for part in validParticles] imgOut = autTool.createOutputImg(imageC[jobl['channel']-1], self.rois[i], particle) imgOut.show() self.saveOutputImg(imgOut, filepath, i+1) IJ.run("Collect Garbage", "")
def main(): # Get active dataset #img = IJ.getImage() display = displayservice.getActiveDisplay() active_dataset = imagedisplayservice.getActiveDataset(display) if not active_dataset: IJ.showMessage('No image opened.') return # Get image path fname = active_dataset.getSource() dir_path = os.path.dirname(fname) if not fname: IJ.showMessage('Source image needs to match a file on the system.') return # Open ROIs rois = RoiManager.getInstance() if not rois: roi_path = os.path.join(dir_path, "RoiSet.zip") if not os.path.isfile(roi_path): try: roi_path = glob.glob(os.path.join(dir_path, "*.roi"))[0] except: roi_path = None if not roi_path: IJ.showMessage('No ROIs. Please use Analyze > Tools > ROI Manager...') return rois = RoiManager(True) rois.reset() rois.runCommand("Open", roi_path) IJ.log('Image filename is %s' % fname) dt = get_dt(active_dataset) rois_array = rois.getRoisAsArray() for i, roi in enumerate(rois_array): crop_id = i + 1 IJ.log("Croping %i / %i" % (crop_id, len(rois_array))) # Get filename and basename of the current cropped image crop_basename = "crop%i_%s" % (crop_id, active_dataset.getName()) crop_basename = os.path.splitext(crop_basename)[0] + ".ome.tif" crop_fname = os.path.join(os.path.dirname(fname), crop_basename) # Get bounds and crop bounds = roi.getBounds() dataset = crop(ij, datasetservice, active_dataset, bounds.x, bounds.y, bounds.width, bounds.height, crop_basename) # Show cropped image ij.ui().show(dataset.getName(), dataset) # Save cropped image (ugly hack) IJ.log("Saving crop to %s" % crop_fname) imp = IJ.getImage() bfExporter = LociExporter() macroOpts = "save=[" + crop_fname + "]" bfExporter.setup(None, imp) Macro.setOptions(macroOpts) bfExporter.run(None) imp.close() IJ.log('Done')
return retResults def writeResults(passResults, passOutput, passProbability): # Create results TSV with open(passOutput, "w") as fileHandle: fileHandle.write("{0}\n".format(HEADER)) for image in passResults: for row in passResults[image]: fieldText = "\t".join(map(str, row)) fileHandle.write("{0}\t{1}\t{2}\n".format( image, passProbability, fieldText)) # Setup measurements to record in CSV setupMeasurements() # Present user definable options, then process options = optionsDialog() if options: # Prepare output directory if not os.path.exists(os.path.join(options[0], options[2])): os.makedirs(os.path.join(options[0], options[2])) # Analyze images results = processImages(options) writeResults(results, os.path.join(options[0], options[2], RESULTS_FILE), options[3]) IJ.showMessage("Analysis Complete!")
#- - - M A I N - - - # select directory that is to be processed path = DirectoryChooser("DotSeg Preprocess Batch Extension - Please choose directory containing the images").getDirectory() saveFolder = pth.join(pth.split(pth.dirname(path))[0], G_saveSubFold) # create list of match objects of .tiff files in directory regEx = re.compile('(?!ppcd_)(?P<prefix>.+).tiff?$', re.IGNORECASE) moFileList = [] # match object File list for fileName in listdir(path): if regEx.match(fileName): # if matches RE, add to list moFileList.append(regEx.match(fileName)) if moFileList == []: IJ.showMessage("Input Exception", "No unprocessed images found in the directory you selected.") raise IOError("No unpocessed TIFFs found in this folder.") for image in moFileList: print "Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")" IJ.log("Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")") imp = Opener().openImage(path + image.group()) # open Image #if imp.getBitDepth() != 8: # converting to 8 bit if # ImageConverter(imp).convertToGray8() roi = imp.roi imps = CS.split(imp) ppc = PPC() for aimp in imps: ppc.setImp(aimp) ppc.run() if roi != None: