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 get_info(): srcDir = IJ.getDirectory("Input_Directory") if not srcDir: print("No input directory selected") return dstDir = IJ.getDirectory("Output_Directory") if not dstDir: print("No output directory selected") return gd = GenericDialog("Process Folder") gd.addStringField("File_extension", ".lif") gd.addStringField("File_name_contains", "") gd.addCheckbox("Keep directory structure when saving", True) gd.showDialog() if gd.wasCanceled(): return ext = gd.getNextString() containString = gd.getNextString() keepDirectories = gd.getNextBoolean() for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Check for file extension if not filename.endswith(ext): continue # Check for file name pattern if containString not in filename: continue print(srcDir) print(filename) process(srcDir, dstDir, root, filename, keepDirectories)
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 runGUI(defaultTargetChannel=2, defaultdt=1.0, defaultRadius=0.3, defaultThreshold=16, defaultFrameGap=0.01, defaultLinkingMax=0.01, defaultClosingMax=0.01): gd = NonBlockingGenericDialog("ZedMate - v0.18 beta") gd.addMessage( "\tZedMate is a TrackMate-based 3D prticle analyzer \n\t\t\t\t\t\t\t\t\t\t\t(copyright Artur Yakimovich 2018-19)\n\n" ) gd.addStringField("File_extension", ".tif") gd.addStringField("File_name_contains", "") gd.addNumericField("Target_Channel", defaultTargetChannel, 0) gd.addNumericField("dt", defaultdt, 2) gd.addNumericField("Radius", defaultRadius, 2) gd.addNumericField("Threshold", defaultThreshold, 2) gd.addNumericField("Frame_Gap", defaultFrameGap, 0) gd.addNumericField("Linking_Max", defaultLinkingMax, 2) gd.addNumericField("Closing_Max", defaultClosingMax, 2) gd.addMessage("\t\t\t\t\t\t_______________________________________") gd.addCheckbox("Preview Parameters on the First Image Only", 0) gd.addMessage("\t\t\t\t\t(Doesn't save results. Re-opens this Dialog).") gd.addMessage("\t\t\t\t\t\t_______________________________________") gd.addCheckbox("Save MNIST mimicry embedding (beta)", 0) gd.showDialog() if gd.wasCanceled(): return extension = gd.getNextString() containString = gd.getNextString() targetChannel = int(gd.getNextNumber()) dt = gd.getNextNumber() radius = gd.getNextNumber() threshold = gd.getNextNumber() frameGap = int(gd.getNextNumber()) linkingMax = gd.getNextNumber() closingMax = gd.getNextNumber() testMode = gd.getNextBoolean() mimicryEmbd = gd.getNextBoolean() inputDir = IJ.getDirectory("Input_directory") if not inputDir: return if not testMode: outputDir = IJ.getDirectory("Output_directory") if not outputDir: return else: outputDir = inputDir # for the case of test #if not os.path.exists(outputDir): # os.makedirs(outputDir) runBatch(inputDir, outputDir, extension, containString, targetChannel, dt, radius, threshold, frameGap,\ linkingMax, closingMax, testMode, mimicryEmbd)
def readCsv(self): #settingsdir = os.path.join(os.getcwd(), 'plugins/Evalulab/'); settingsdir = os.path.join(IJ.getDirectory('imagej'), 'plugins/Evalulab/') print 'IJm dir:' + IJ.getDirectory('imagej') print settingsdir settingsname = settingsdir + 'settings.txt' print settingsname print settingsname csvfile = open(settingsname, 'rb') csvreader = csv.reader(csvfile, delimiter=',') for row in csvreader: if (len(row) > 0): if (row[0] == 'pixelWidth'): self.pixelWidth = float(row[1]) elif (row[0] == 'pixelHeight'): self.pixelHeight = float(row[1]) elif (row[0] == 'porphyrinMaxSize'): self.porphyrinMaxSize = float(row[1]) elif (row[0] == 'porphyrinMinCircularity'): self.porphyrinMinCircularity = float(row[1]) elif (row[0] == 'porphyrinMaxCircularity'): self.porphyrinMaxCircularity = float(row[1]) elif (row[0] == 'porphyrinRedPercentage'): self.porphyrinRedPercentage = float(row[1]) elif (row[0] == 'sebumMinSize'): self.sebumMinSize = float(row[1]) print self.sebumMinSize elif (row[0] == 'sebumMaxSize'): self.sebumMaxSize = float(row[1]) elif (row[0] == 'sebumMinCircularity'): self.sebumMinCircularity = float(row[1]) elif (row[0] == 'sebumMaxCircularity'): self.sebumMaxCircularity = float(row[1]) elif (row[0] == 'closedPoresMinSize'): self.closedPoresMinSize = float(row[1]) elif (row[0] == 'closedPoresMaxSize'): self.closedPoresMaxSize = float(row[1]) elif (row[0] == 'closedPoresMinCircularity'): self.closedPoresMinCircularity = float(row[1]) elif (row[0] == 'closedPoresMaxCircularity'): self.closedPoresMaxCircularity = float(row[1]) elif (row[0] == 'openPoresMinSize'): self.openPoresMinSize = float(row[1]) elif (row[0] == 'openPoresMaxSize'): self.openPoresMaxSize = float(row[1]) elif (row[0] == 'openPoresMinCircularity'): self.openPoresMinCircularity = float(row[1]) elif (row[0] == 'openPoresMaxCircularity'): self.openPoresMaxCircularity = float(row[1])
def readCsv(self): #settingsdir = os.path.join(os.getcwd(), 'plugins/Evalulab/'); settingsdir = os.path.join(IJ.getDirectory('imagej'), 'plugins/Evalulab/'); print 'IJm dir:'+IJ.getDirectory('imagej') print settingsdir settingsname=settingsdir+'settings.txt' print settingsname print settingsname csvfile=open(settingsname, 'rb') csvreader=csv.reader(csvfile, delimiter=',') for row in csvreader: if (len(row)>0): if (row[0]=='pixelWidth'): self.pixelWidth=float(row[1]) elif (row[0]=='pixelHeight'): self.pixelHeight=float(row[1]) elif (row[0]=='porphyrinMaxSize'): self.porphyrinMaxSize=float(row[1]) elif (row[0]=='porphyrinMinCircularity'): self.porphyrinMinCircularity=float(row[1]) elif (row[0]=='porphyrinMaxCircularity'): self.porphyrinMaxCircularity=float(row[1]) elif (row[0]=='porphyrinRedPercentage'): self.porphyrinRedPercentage=float(row[1]) elif (row[0]=='sebumMinSize'): self.sebumMinSize=float(row[1]) print self.sebumMinSize elif (row[0]=='sebumMaxSize'): self.sebumMaxSize=float(row[1]) elif (row[0]=='sebumMinCircularity'): self.sebumMinCircularity=float(row[1]) elif (row[0]=='sebumMaxCircularity'): self.sebumMaxCircularity=float(row[1]) elif (row[0]=='closedPoresMinSize'): self.closedPoresMinSize=float(row[1]) elif (row[0]=='closedPoresMaxSize'): self.closedPoresMaxSize=float(row[1]) elif (row[0]=='closedPoresMinCircularity'): self.closedPoresMinCircularity=float(row[1]) elif (row[0]=='closedPoresMaxCircularity'): self.closedPoresMaxCircularity=float(row[1]) elif (row[0]=='openPoresMinSize'): self.openPoresMinSize=float(row[1]) elif (row[0]=='openPoresMaxSize'): self.openPoresMaxSize=float(row[1]) elif (row[0]=='openPoresMinCircularity'): self.openPoresMinCircularity=float(row[1]) elif (row[0]=='openPoresMaxCircularity'): self.openPoresMaxCircularity=float(row[1])
def readCsv(self): settingsdir = os.path.join(IJ.getDirectory("imagej"), "plugins/Scripts/Evalulab/") print "IJm dir:" + IJ.getDirectory("imagej") print settingsdir settingsname = settingsdir + "settings.txt" print settingsname print settingsname csvfile = open(settingsname, "rb") csvreader = csv.reader(csvfile, delimiter=",") for row in csvreader: if len(row) > 0: if row[0] == "pixelWidth": self.pixelWidth = float(row[1]) elif row[0] == "pixelHeight": self.pixelHeight = float(row[1]) elif row[0] == "porphyrinMaxSize": self.porphyrinMaxSize = float(row[1]) elif row[0] == "porphyrinMinCircularity": self.porphyrinMinCircularity = float(row[1]) elif row[0] == "porphyrinMaxCircularity": self.porphyrinMaxCircularity = float(row[1]) elif row[0] == "porphyrinRedPercentage": self.porphyrinRedPercentage = float(row[1]) elif row[0] == "sebumMinSize": self.sebumMinSize = float(row[1]) print self.sebumMinSize elif row[0] == "sebumMaxSize": self.sebumMaxSize = float(row[1]) elif row[0] == "sebumMinCircularity": self.sebumMinCircularity = float(row[1]) elif row[0] == "sebumMaxCircularity": self.sebumMaxCircularity = float(row[1]) elif row[0] == "closedPoresMinSize": self.closedPoresMinSize = float(row[1]) elif row[0] == "closedPoresMaxSize": self.closedPoresMaxSize = float(row[1]) elif row[0] == "closedPoresMinCircularity": self.closedPoresMinCircularity = float(row[1]) elif row[0] == "closedPoresMaxCircularity": self.closedPoresMaxCircularity = float(row[1]) elif row[0] == "openPoresMinSize": self.openPoresMinSize = float(row[1]) elif row[0] == "openPoresMaxSize": self.openPoresMaxSize = float(row[1]) elif row[0] == "openPoresMinCircularity": self.openPoresMinCircularity = float(row[1]) elif row[0] == "openPoresMaxCircularity": self.openPoresMaxCircularity = float(row[1])
def __init__(self): self.__dictCells={} self.__measures=[] self.__measurescompl=[] #self.__dictImages={} self.__dictMeasures={} #dictionary of the rectangles of the diagrams. self.__gridrectangle={} self.__listcellname=[] self.__allcells=[] self.__minLife=0 self.__maxLife=0 if IJ.getDirectory("image") is not None : self.__pathdir = IJ.getDirectory("image") else : self.__pathdir=IJ.getDirectory("current") self.__optionSave=False self.__optionSaveBactTrack=False self.__optionImport=False self.__activeTitle="" self.__useTime = False self.__optionImages = True self.__imagesnames = [] self.__listfiles = ["","",""] self.__defaultcellsval = [] self.__savetables = True self.__savemode = True self.__batch = False self.__onlyselect = True self.__onlystart = True self.__noise = 150 self.__minLife = 2 self.__batchanalyse = False self.__listpaths = [] self.__time = time.strftime('%d-%m-%y_%Hh%Mm%Ss',time.localtime()) self.__updateoverlay = True measures1 = ["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"] measures2 = ["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"] measures_global = ["Latency", "velocity", "cumulatedDist"] self.__defaultmeasures=[False for m in measures1+measures2] self.__defaultmeasures_global=[False for m in measures_global] self.__measuresparambool=[] self.__measuresparambool_global=[] self.__nextstack = True self.__dictNcells = {} IJ.run("Options...", "iterations=1 count=1 black edm=Overwrite do=Nothing")
def main(): indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") files = sorted(os.listdir(indir)) IJ.log("files: {}".format(files)) montages = [] for imfile in files: IJ.log("File: {}/{}".format(files.index(imfile)+1, len(files))) if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) montage = makemontage(imp, hsize=6, vsize=6, increment=2) _saveimage(montage, outdir)
def save_tif(): # Get the active image, its title, and the directory where it lies imp = IJ.getImage() imp_title = imp.getTitle() path = IJ.getDirectory("image") IJ.log("Active image source: {}{}".format(path, imp_title)) for i in range(0, len(channel_names)): current_name = channel_names[i] if "C={}".format(i) in imp_title: channel_name = current_name found_name = True else: pass # In the imp title string, find the index where .nd2 first appears. Everything # up to this point is kept for use in saving the file. end_of_title = imp_title.find('.nd2') tif_title = "{}_{}".format(imp_title[:end_of_title], channel_name) # Save the image save_path = "{}{}".format(path, tif_title) IJ.saveAsTiff(imp, save_path) IJ.log("Tif saved at {}.tif".format(save_path)) # Close the image imp.close()
def select_input(self, event): self.input_path = IJ.getDirectory( "Select Directory containing your data") # get the files in that directory self.input_files = listdir(self.input_path) self.input_dapi = [s for s in self.input_files if "DAPI.tif" in s] self.core_names = get_core_names(self.input_dapi) # create output directory self.output_path = path.join( path.dirname(path.dirname(self.input_path)), "Cubified_ROIs") if path.isdir(self.output_path): print "Output path already created" else: mkdir(self.output_path) print "Output path created" # get the processed data self.processed_files = listdir(self.output_path) self.out_core_names = get_core_names( get_core_names(self.processed_files) ) # needs the channel and roi to be removed # populate the lists for f in set(self.core_names): if f not in set(self.out_core_names): # skip if processed self.Dapi_files.addElement(f) for f in set(self.out_core_names ): # a set so that only unique ones are shown self.output_files.addElement(f)
def measure_rois(): # Get the active image, its title, and the directory where it lies imp = IJ.getImage() imp_title = imp.getTitle() path = IJ.getDirectory("image") IJ.log("Active image source: {}{}".format(path, imp_title)) # Set measurements to redirect to the active image IJ.run( "Set Measurements...", "area mean standard min center perimeter bounding fit feret's integrated median stack display redirect={}" .format(imp_title)) # Instantiate RoiManager as rm, select all rois and measure them roim = RoiManager.getInstance() roim.runCommand("Select All") roim.runCommand("Measure") # Save the measurements just made using the name of the active image measurements_filename = imp_title[:-4] IJ.saveAs("Results", "{}{}.csv".format(path, measurements_filename)) IJ.selectWindow("Results") IJ.run("Close") IJ.log("Measurements saved at {}{}.csv".format(path, measurements_filename)) # Close the active image so IJ can move on to the next imp.close()
def main(): indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") files = sorted(os.listdir(indir)) # IJ.log("files: {}".format(files)) # montages = [] for imfile in files: IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files))) if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) channels = ChannelSplitter().split(imp) name = outdir + imfile + "_t001_c001.tif" IJ.run(channels[0], "Image Sequence... ", "format=TIFF save={}".format(name))
def run(): srcDir = IJ.getDirectory("Input_directory") if not srcDir: return gd = GenericDialog("Do you want to run the image correction now?") gd.showDialog() if gd.wasCanceled(): return find_folders(srcDir)
def processImage(): imp = IJ.getImage() image_name = imp.title image_dir = IJ.getDirectory("image") IJ.run(imp, "Measure", "") marker_dir = image_dir + "markers" + os.path.sep makeDir(marker_dir) csv_file = saveResults(imp, marker_dir) IJ.selectWindow(image_name) IJ.run("Close")
def outputpath(event) : macrodir=IJ.getDirectory("macros") frame = Frame("Select the macro file") fd = FileDialog(frame) fd.setDirectory(macrodir) fd.show() macrodir = fd.getDirectory() self.__macropath = fd.getFile() self.__text.setText(self.__macropath) print self.__macropath
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 main(): # Get the wanted input and output directories. indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") # Collect all files in the import directory and sort on file name. files = sorted(os.listdir(indir)) # Loop through all input files. montages = [] for imfile in files: # Some optional feedback if you're impatient. IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files))) # Make montage of every .tiff file and save as .tiff in the output directory. if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) montage = makemontage(imp, hsize=6, vsize=6, increment=2) saveimage(montage, outdir)
def __init__(self): # Sets the number of digits. self.__nbdigits=3 IJ.run("Set Measurements...", "area mean standard modal min centroid center bounding fit shape feret's integrated median skewness kurtosis stack display redirect=None decimal="+str(self.__nbdigits)) # Dictionnary of captures to analyse. self.__dictImages={} # Dictionnary of the times corresponding to the different slices. self.__dictTimeStack={} self.__pathdir="" # Dictionnary of the dictionnary of cells (key = name of stack, value = dictionnary of the cells of the stack). self.__dict={} # List of the parameters chosen by the user in order to calculate the distance. self.__distparam=[] # List of the parameters chosen by the user in order to find the particules in the stack. self.__params=[] # Char of the method used in order to calculate the distance (logarithm distance or euclidean distance). self.__distmethod="Euclidean distance" # Is true if the user wants to subtrack the background, with a radius of self.__radius. self.__subback=False # Is true if the user wants to run a pre processing macro. self.__runmacro=False self.__macropath=IJ.getDirectory("macros") self.__minArea=0 self.__maxArea=1000000 self.__minCirc=0.00 self.__maxCirc=1.00 self.__thresMethod="MaxEntropy" self.__manthresh=False self.__maxthr=255 self.__minthr=0 # Option in order to create a symmetry for angles close to 0° and 180°. self.__optionAngle=False # Option in order to save ROIs in a folder. #self.__optionSave=False self.__optionNewCells=False self.__source="" self.__optionTimelapse=False self.__batch = False self.__positionsList = [] self.__listpaths = [] self.__pathdir = "" self.__selectdir = ""
def run(): print "run:" srcDir = IJ.getDirectory("Input_directory") if not srcDir: return print "Error1:" dstDir = IJ.getDirectory("Output_directory") if not dstDir: return print "Error2:" for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Check for file extension if not filename.endswith(ext): continue # Check for file name pattern if containString not in filename: continue process(srcDir, dstDir, root, filename, keepDirectories)
def main(): # Get the wanted output directory and prepare subdirectories for output. outdir = IJ.getDirectory("output directory") # Open the 'Track statistics.csv' input file and format as getresults() dictionary. rt = opencsv() rt = getresults(rt) # Retrieve the current image as input (source) image. imp = WindowManager.getCurrentImage() # Run the main crop function on the source image. croproi(imp, tracks=rt, outdir=outdir, roi_x=150, roi_y=150, minduration=6)
def actionPerformed(self, event): outDir = IJ.getDirectory("Save category file in directory...") if not outDir: return # when cancelled filename = IJ.getString("Filename", "categories.txt") if not filename: return # when cancelled outPath = os.path.join(outDir, filename) listButtons = winButton.getPanel().getComponents() with open(outPath, "w") as catFile: for button in listButtons: catFile.write(button.getLabel().encode("utf-8") + "\n") # important to use UTF-8 otherwise troubles
def bit_tester(image_name): ## gets the number of bits for an image, error if not 8 or 16 bit. ## dest = IJ.getDirectory("image") filepath = dest + image_name fr = ChannelSeparator() fr.setId(filepath) bitDepth = fr.getBitsPerPixel() if int(bitDepth) in (8, 16): if int(bitDepth) == 8: bit_depth = 2**(bitDepth)-1 if int(bitDepth) == 16: bit_depth = 2**(bitDepth)-1 return bit_depth elif int(bitDepth) not in (8, 16): print("Error image is not 8 or 16 bit") quit()
def processImage(imp, threshold, min_size, max_size, remove_last_slice): title = imp.title image_dir = IJ.getDirectory("image") channel_dir = image_dir + "channel_" + str(channel) + "/" marker_dir = image_dir + "markers/" mapped_images_dir = image_dir + "mapped_images/" makeDir(channel_dir, marker_dir, mapped_images_dir) IJ.run("Split Channels") main_channel_image = "C" + str(channel) + "-" + title IJ.selectWindow(main_channel_image) imp = IJ.getImage() if os.path.exists(channel_dir + main_channel_image): os.remove(channel_dir + main_channel_image) images_list = WindowManager.getImageTitles() for image in images_list: if image != main_channel_image: IJ.selectWindow(image) IJ.run("Close") if remove_last_slice: imp.setSlice(imp.NSlices) IJ.run(imp, "Delete Slice", "") imp.setSlice(1) IJ.saveAsTiff(imp, channel_dir + main_channel_image) #time.sleep(5) IJ.run( imp, "3D Objects Counter", "threshold=" + str(threshold) + " slice=1 min.=" + str(min_size) + " max.=" + str(max_size) + " centres_of_masses statistics") #title="001-002.tiff" #time.sleep(10) image = title.split(".")[0] restults_window = image + ".csv" IJ.saveAs("Results", marker_dir + restults_window) IJ.selectWindow(restults_window) IJ.run("Close") imp.close() imp = IJ.getImage() title = imp.title if os.path.exists(mapped_images_dir + title): os.remove(mapped_images_dir + title) IJ.saveAsTiff(imp, mapped_images_dir + title) imp.close()
def actionPerformed(self, e): ''' Event handler for the buttons. ''' cmd = e.getActionCommand() if cmd=='Browse...': folder = IJ.getDirectory("Select the image folder") if not folder: return self.folderTextField.setText(folder) images = Uploader.getImageList(folder) self.nrOfImagesToUpload = len(images) self.inputFolder = folder self.statusTextField.setText(str(self.nrOfImagesToUpload) + ' images to upload...') if cmd=='Upload Images': print('upload') if self.nrOfImagesToUpload < 1: return else: # convert if ome checked. Add _lbl if ground-truth checked. upload self.statusTextField.setText('Uploading ' + str(self.nrOfImagesToUpload) + ' images...') imageFolder = self.folderTextField.getText() uploader = Uploader.getInstance(self.biaflows) uploader.addObserver(self) self.tmpFolder = None if self.convertToOMETIFCheckBox.getState() or self.uploadAsGroundTruthCheckBox.getState(): self.statusTextField.setText('Converting ' + str(self.nrOfImagesToUpload) + ' images...') # convert and add '_lbl' if ground truth self.tmpFolder = imageFolder + 'biaflows_tmp/' suffix = '' if self.uploadAsGroundTruthCheckBox.getState(): suffix = '_lbl' uploader.convertImagesInFolderToOME(imageFolder, self.tmpFolder, suffix) imageFolder = self.tmpFolder # upload pid = self.projectIDs[self.projectChoice.getSelectedIndex()] sid = self.storageIDs[self.storageChoice.getSelectedIndex()] self.statusTextField.setText('Uploading ' + str(self.nrOfImagesToUpload) + ' images...') uploader.setInputFolder(imageFolder) uploader.setProject(str(pid)) uploader.setStorage(str(sid)) thread = Thread(uploader) thread.start() # cleanup self.statusTextField.setText('Upload started.')
def main(): # Get the wanted output directory and prepare subdirectories for output. outdir = IJ.getDirectory("output directory") # Open the 'Track statistics.csv' input file and format as getresults() dictionary. rt = opencsv() rt = getresults(rt) # Retrieve the current image as input (source) image. imp = WindowManager.getCurrentImage() # Run the main crop function on the source image. # croppoints(imp, spots, outdir, roi_x=150, roi_y=150, ntracks=None, trackid="TRACK_ID", # trackxlocation="POSITION_X", trackylocation="POSITION_Y", tracktlocation="FRAME") croppoints(imp, spots=rt, outdir=outdir, roi_x=150, roi_y=150, ntracks=50) # Combine all output stacks into one movie. combinestacks(outdir, height=8)
def processImage(): imp = IJ.getImage() image_name = imp.title image_dir = IJ.getDirectory("image") IJ.run(imp, "Measure", "") marker_dir = os.path.join(image_dir, "markers" + os.path.sep) processed_marker_dir = os.path.join(image_dir, "processed_markers" + os.path.sep) makeDir(marker_dir, processed_marker_dir) csv_file = saveResults(imp, marker_dir) imp.deleteRoi() tiff_save_name = os.path.join(processed_marker_dir, image_name) IJ.saveAsTiff(imp, tiff_save_name) remove_duplicate_counter(csv_file, processed_marker_dir) # file_dir = os.path.dirname(os.path.abspath(__file__)) IJ.run(imp, "setRoi ", ""); IJ.run("Save") imp.close() return image_dir
def getSettings(self): gd = GenericDialogPlus("Settings") gd.addNumericField("Distance in pixel", 600, 0) gd.addNumericField("Distance in cm", 2.54, 2) gd.addNumericField("Min. size (cm^2)", 0.5, 2) gd.addDirectoryField("Directory", IJ.getDirectory("home")) gd.addStringField("File extension", "*.jpg", 8) gd.showDialog() if gd.wasCanceled(): sys.exit() else: distPixel = gd.getNextNumber() distCm = gd.getNextNumber() minSize = gd.getNextNumber() * (distPixel / distCm) ** 2 imageDir = gd.getNextString() ext = gd.getNextString() return (distPixel, distCm, minSize, imageDir, ext)
def findclearcell_run(): inDir = IJ.getDirectory("Input directory") if not inDir: return gd = GenericDialog("Process Folder") gd.addStringField("File extension", ".oir") gd.addStringField("File name starts with (the date)", "") gd.showDialog() if gd.wasCanceled(): return ext = gd.getNextString() containString = gd.getNextString() for root, directories, filenames in os.walk(inDir): for fileName in filenames: if not fileName.endswith(ext): continue if containString not in fileName: continue print findclearcell(inDir, root, fileName)
def split_stack(): imp = IJ.getImage() path = IJ.getDirectory("image") IJ.run("Stack to Images", "") # close original image and leave split stacks open imp.close() n_images = WindowManager.getImageCount() for i in range(0, n_images): frame_imp = IJ.getImage() imp_title = frame_imp.getTitle() save_path = "{}{}".format(path, imp_title) IJ.saveAsTiff(frame_imp, save_path) IJ.log("{} saved at {}".format(frame_imp, save_path)) frame_imp.close()
def main(): # Get the wanted output directory and prepare subdirectories for output. outdir = IJ.getDirectory("output directory") # Open the 'Track statistics.csv' input file and format as getresults() dictionary. rt = opencsv() rt = getresults(rt) # Retrieve the current image as input (source) image. imp = WindowManager.getCurrentImage() # Run the main crop function on the source image. # croptracks(imp, tracks, outdir, trackid="TRACK_ID", # trackx="TRACK_X_LOCATION", tracky="TRACK_Y_LOCATION", # trackstart="TRACK_START", trackstop="TRACK_STOP", # roi_x=150, roi_y=150) croptracks(imp, tracks=rt, outdir=outdir, roi_x=150, roi_y=150) # Combine all output stacks into one movie. combinestacks(outdir, height=8)
def main(): # Get the wanted output directory and prepare subdirectories for output. outdir = IJ.getDirectory("output directory") # Open the 'Track statistics.csv' input file and format as getresults() dictionary. rt = opencsv() rt = getresults(rt) # Retrieve the current image as input (source) image. imp = WindowManager.getCurrentImage() cal = imp.getCalibration() IJ.log("Calibration: {}".format(cal.scaled())) # Run the main crop function on the source image. croppoints(imp, spots=rt, outdir=outdir, roi_x=150, roi_y=150) # Combine all output stacks into one movie. combinestacks(outdir, height=8)
def run(): global numRep images = map(WM.getImage, WM.getIDList()) nStacks = len(images) #num of stacks opened numSlices = [images[i].getNSlices() for i in range(nStacks)] #[12,13,12] maxSlice = max( numSlices) #the max number of slices among all opened stacks #maxIndex = [i for i,j in enumerate(numSlices) if j == maxSlice] # the index of the image with maxSlice #move max to the head and min to the end imps = [ image for (numSlice, image) in sorted(zip(numSlices, images), reverse=True) ] #sort the images base on their nSlices numRep = zyGetProperty(imps[0], "nFrame") #add slices in imp[0], base on (nStacks-1)*numRep impDup(imps[0], nStacks) #for other imps, loop them and copy/paste every 3(numRep) into imp for i in range(nStacks - 1): n = i + 1 binder(imps[0], imps[n], nStacks, n) #set the nFrame = nStacks*numRep, and save the image # record the numSlices, numFrame, totalSlices and numStacks in the infoStr zyAddProperty(imps[0]) msgStr = "nslices=" + str(maxSlice / numRep) + " nframes=" + str( nStacks * numRep) #IJ.run(imps[0], "Properties...", msgStr) IJ.log("For real: " + msgStr) file_path = IJ.getDirectory('image') file_name = imps[0].getTitle() filename = 'C_' + file_name imps[0].setTitle(filename) destPath = os.path.join(file_path, 'combined') saveStack(destPath, filename, imps[0])
def main(threshold, min_size, max_size, remove_last_slice=False): IJ.run( "3D OC Options", "volume surface nb_of_obj._voxels nb_of_surf._voxels integrated_density mean_gray_value std_dev_gray_value median_gray_value minimum_gray_value maximum_gray_value centroid mean_distance_to_surface std_dev_distance_to_surface median_distance_to_surface centre_of_mass bounding_box dots_size=5 font_size=10 show_numbers white_numbers store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=none" ) IJ.run("Set Measurements...", "area mean centroid redirect=None decimal=6") Commands.closeAll() selected_dir = IJ.getDirectory("Select Directory") print(selected_dir) selected_dir = selected_dir + "/" dir_list = list() file_type = "processed_images" if selected_dir.endswith(file_type + "/"): dir_list.append(selected_dir) else: dir_list = listDir(selected_dir, file_type, recursive=True) print(dir_list) for dir in dir_list: print(dir) cd_dir = dir + "/cd/" print(cd_dir) makeDir(cd_dir) image_list = listDir(dir, file_type=".tiff", recursive=False) for i in image_list: print(i) now = time.time() IJ.open(i) imp = IJ.getImage() IJ.run(imp, "Measure", "") saveResults(imp, cd_dir) #processImage(imp, threshold, min_size, max_size, remove_last_slice) later = time.time() difference = int(later - now) #time.sleep(difference/10) print("The time difference is " + str(difference))
def __SaveStack(self,nameimage,imp): toparse = [self.__subback, self.__manthresh, self.__optionAngle, self.__optionNewCells, self.__optionTimelapse] self.__subback, self.__manthresh, self.__optionAngle, self.__optionNewCells, self.__optionTimelapse = map(self.parsebool, toparse) fichier = open(self.__pathdir+"Track.txt","w") fichier.write("NOMIMAGE="+imp.getTitle()+"\n") fichier.write("PATH="+str(IJ.getDirectory("image"))+"\n") fichier.write("NSLICES="+str(imp.getImageStackSize())+"\n") fichier.write("NCELLS="+str(len(self.__dict[nameimage]))+"\n") fichier.write("CELLSINFOPATH="+self.__pathdir+"\n") fichier.write("SUBBACK="+str(self.__subback)+"\n") fichier.write("SUBBACKRADIUS="+str(self.__radius)+"\n") fichier.write("DISTPARAM_AREA_COEFF="+str(self.__distparam[0])+"\n") fichier.write("DISTPARAM_AREA_MAXDELTA="+str(self.__distparam[1])+"\n") fichier.write("DISTPARAM_ANGLE_COEFF="+str(self.__distparam[2])+"\n") fichier.write("DISTPARAM_ANGLE_MAXDELTA="+str(self.__distparam[3])+"\n") fichier.write("DISTPARAM_FERETMAX_COEFF="+str(self.__distparam[4])+"\n") fichier.write("DISTPARAM_FERETMAX_MAXDELTA="+str(self.__distparam[5])+"\n") fichier.write("DISTPARAM_POSITIONX_COEFF="+str(self.__distparam[6])+"\n") fichier.write("DISTPARAM_POSITIONX_MAXDELTA="+str(self.__distparam[7])+"\n") fichier.write("DISTPARAM_POSITIONY_COEFF="+str(self.__distparam[8])+"\n") fichier.write("DISTPARAM_POSITIONY_MAXDELTA="+str(self.__distparam[9])+"\n") fichier.write("DISTMETHOD="+self.__distmethod+"\n") fichier.write("OPTIONMANTHRESH="+str(self.__manthresh)+"\n") fichier.write("THRESHMETHOD="+str(self.__thresMethod)+"\n") fichier.write("OPTIONANGLE="+str(self.__optionAngle)+"\n") fichier.write("OPTIONNEWCELLS="+str(self.__optionNewCells)+"\n") fichier.write("OPTIONTIMELAPSE="+str(self.__optionTimelapse)+"\n") fichier.write("TIMELAPSE="+str(self.__timelapse)+"\n") for params in self.__params : fichier.write(params[0]+"="+str(params[1])+";"+str(params[2])+"\n") fichier.close()
if int(fdict['time']) == 1: wdict.update({'movie': len(movies), 'treatment': conditions[wdict["well"]]}) wdict.update(description) key = dirname(ifile) if movies.has_key(key): raise RuntimeError('Key not unique') movies[key] = wdict files_ = glob(join(root, "*.lsm")) outfile = join(target_dir, filepattern %wdict) print "New file:" , basename(outfile) processMovie(root, files_, outfile) return len(movies) if __name__ == "__main__": indir = IJ.getDirectory("Choose the input directory") if indir is None: raise SystemExit outdir = IJ.getDirectory("Choose the output directory") if outdir is None: raise SystemExit # indir = "C:\Users\hoefler\Desktop\mergescript\data" # outdir = "C:\Users\hoefler\Desktop\mergescript\output" nmovies = findAndCat(indir, outdir) print "Concatenated %d movies" %nmovies
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(): IJ.showMessage("Correct_3D_drift error " + filename + " image has only " + str(imp.getNChannels) + " you can't register on channel " + str(channel) ) return IJ.log("Register " + filename + " using channel " + str(channel)) if any([frame > imp.getNFrames() or frame < 1 for frame in frames]): print "frame list containes frames not included in image" if target_folder is None: target_folder = IJ.getDirectory("Choose output directory for results") if target_folder is not None: if not os.path.exists(target_folder): os.mkdir(target_folder) shifts, frames = compute_frame_translations(imp, channel, frames) print shifts # Make shifts relative to 0,0,0 of the original imp frame: shifts = concatenate_shifts(shifts) print shifts #Print shifts to file fileT = open(os.path.join(target_folder,"registration3DShifts.txt"),'w') fileT.write("%frameNr Xshift Yshift Zshift\n") print shifts print frames
else: open_dialog = OpenDialog('Select a config file', folder, default_config) return open_dialog.getFileName() else: # Ask user to select a config file. open_dialog = OpenDialog('Select a config file', folder, default_config) return open_dialog.getFileName() ## MAIN FUNCTION ## #imp = IJ.getImage() default_config = 'config.txt' # Get directory of open image or prompt user to choose. folder = IJ.getDirectory('image') if not folder: folder = IJ.getDirectory('Select a folder') config_filename = get_config_file(folder) if config_filename: config_filepath = os.path.join(folder, config_filename) # Load the config file or abort. try: config = open(config_filepath) except: IJ.error('Could not open config file %s' % config_filepath) config = None else: IJ.error('No config file was specified, aborting...')
from __future__ import with_statement import sys import os.path import codecs from ij import IJ, ImagePlus sys.path.append(IJ.getDirectory("plugins") + "/LAMeasure") from LAMeasure_ import PAResult def readPAResults(f): rows = f.readlines() header = rows[0] ret = [] for row in rows[1:]: cols = row.rstrip("\n").split(",") filename = cols[0].decode("utf-8") paResult = map(float, cols[1:]) ret.append(PAResult(filename, paResult)) return (header, ret) def checkLeafNumbers(dir): maskdir = os.path.join(dir, "mask") resdir = os.path.join(dir, "res") with open(os.path.join(dir, "leafnumbers.csv")) as f: leafnumbers = [tuple(s.rstrip("\n").split(",")) for s in f.readlines()] for filename, n in leafnumbers:
IJ.run("Close All"); """ Power=getTag("DAC2_561-Volts"); Gain=getTag("Hamamatsu_DCAM-EMGain"); AcqTime=getTag("Exposure-ms"); def readMeta(tag) { info = getImageInfo(); index1 = indexOf(info, tag); if (index1==-1) return ""; index1 = indexOf(info, ":", index1); if (index1==-1) return ""; index2 = indexOf(info, "\n", index1); value = substring(info, index1+1, index2); return value; } """ dr = IJ.getDirectory("Choose a Directory "); for root, dirs, files in os.walk(dr): try: for f in files: if fn.fnmatch(f, '*meta*'): with open(op.join(root,f), "r") as inpt: for i in inpt: print i
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
print 'Average Radius:' , mean_radius # Create the overlay image overlayImage = image.duplicate() IJ.run(overlayImage, "RGB Color", "") IJ.run(overlayImage, 'Specify...', 'width=' + str(2*mean_radius) + \ ' height=' + str(2*mean_radius) + \ ' x=' + str(mean_cx) + \ ' y=' + str(mean_cy) + ' oval centered'); roi = overlayImage.getRoi() overlayImage.setOverlay(roi, Color(246, 27, 27), 10, None) overlayImage = overlayImage.flatten(); # Now add the overlay image as the first stack newStack = image.createEmptyStack() newStack.addSlice(overlayImage.getProcessor()) newStack.addSlice(image.getProcessor()) image.setStack(newStack) directory = IJ.getDirectory('image') print directory name = image.getShortTitle() print name # Now save results table. Then done. IJ.saveAs('Measurements', directory + name + '.txt') print 'Done saving measurement table!' # Now overwrite the original image IJ.saveAsTiff(image, directory + name + '.tif')
from ij import IJ from ij.gui import GenericDialog, YesNoCancelDialog from ij.plugin.frame import RoiManager from ij.macro import Functions rm = RoiManager.getInstance() imp = IJ.getImage() path = IJ.getDirectory("image") name = imp.getTitle()[0:2] newimp = IJ.getImage() rm.runCommand(newimp, "Show All") for x in range(0, rm.getCount()): rm.select(newimp, x) IJ.run("Line to Area") IJ.run("Measure") # rm.setSelectedIndexes(range(rm.getCount())); # rm.runCommand(newimp, "Combine");
(strength, thisMaximum, thisMinimum, minHeight, maxHeight)) retSeqP = (0, 0, 0, 0, 0) for seqP in seqPointList: print(seqP[-1]) if (seqP[-1] > retSeqP[-1]) and seqP[2] > 0: retSeqP = seqP return retSeqP from ij.measure import ResultsTable from ij import WindowManager from ij.gui import NonBlockingGenericDialog from ij import IJ import sys sys.path.append( IJ.getDirectory("imagej") + "/jars/HaralickFeaturesInteractive/") from Haralick_Features import Haralick_Features as hf cmChan = int(IJ.getProperty("cmChan")) analyte = WindowManager.getCurrentImage() analyte.setC(cmChan) title = analyte.getTitle() cmNumber = IJ.getProperty("cmNumber") if cmNumber is None: cmNumber = 1 IJ.setProperty("cmNumber", cmNumber) cmNumber += 1 sarcomereLength = IJ.getProperty("sarcomereLength") if sarcomereLength is None:
from java.awt.event import ActionListener, AdjustmentListener, WindowEvent from java.awt import Font from ij.plugin.frame import RoiManager from org.python.core import codecs codecs.setDefaultEncoding('utf-8') from ij import IJ, ImagePlus from ij.measure import Calibration, Measurements from ij.gui import Overlay, NonBlockingGenericDialog, Roi from ij.plugin.filter import ParticleAnalyzer mypath=os.path.expanduser(IJ.getDirectory("plugins")+"MeasureCellsDev") #mypath=os.path.expanduser(os.path.join("~","Dropbox","MacrosDropBox","py","MorphoBact2")) sys.path.append(mypath) from MorphoBact import Morph class RangeRois(object): """This class allows to sort an array of ROI according to a range of measures in a range between min and max values """ __rawRanges={} __image=None __test=""
# @DatasetService data # @DisplayService display # @net.imagej.ops.OpService ops # @ImageDisplayService ids from ij import IJ from ij.io import DirectoryChooser import os import sys homedir = IJ.getDirectory("imagej") jythondir = os.path.join(homedir, "plugins/Scripts/Evalulab/") jythondir = os.path.abspath(jythondir) sys.path.append(jythondir) import PoreDetectionUV reload(PoreDetectionUV) from PoreDetectionUV import runPoreDetection import MessageStrings reload(MessageStrings) from MessageStrings import Messages import Utility reload(Utility) if __name__ == "__main__":
from javax.swing import JOptionPane,JFrame import sys import os import time import glob import os.path import getpass import random import glob import tempfile username=getpass.getuser() mypath=os.path.expanduser(IJ.getDirectory("plugins")+"MeasureCellsDev") #mypath=os.path.expanduser(os.path.join("~","Dropbox","MacrosDropBox","py","MorphoBact2")) sys.path.append(mypath) from org.python.core import codecs codecs.setDefaultEncoding('utf-8') from MorphoBact import Morph from BacteriaCell import Bacteria_Cell from LinkRoisAB import link from RangeRois import RangeRois class Bacteria_Tracking(object) : """ This class creates a dictionnary for all the cells in the capture, with a display of the ROIs, according to the preferences chosen by the user.
return self.__pathdir def setPositionslist(self, positions) : self.__positionsList=positions def parsebool(self, val) : if val : return str(1) else : return str(0) ############################################## end class Bacteria_Tracking ################################################################################################ if __name__ == "__main__": import os, glob from os import path bact=Bacteria_Tracking() #def run(self, files, path, scale, batch, **settings): if IJ.showMessageWithCancel("", "active image ? (ok) \nfiles (cancel)") : bact.run(IJ.getImage(), "", 1, False) else : selectdir=IJ.getDirectory("image") selectdir=IJ.getDirectory("") listfiles=[] listfiles.append(glob.glob(selectdir+"*DIA_s0001*t000[1-9].tif")) listfiles.append(glob.glob(selectdir+"*DIA_s0002*t000[1-9].tif")) bact.run(listfiles)
from ij import IJ, ImagePlus, Macro import java.lang.Thread as Thread from ij.gui import WaitForUserDialog import glob, os __author__ = 'Nichole Wespe' imp = IJ.getImage() directory = IJ.getDirectory("image") f = str(imp.getTitle()) date, rows, columns, time_tif = str.split(f) # deconstruct filename time = time_tif.replace('tif','jpg') # need to remove .tif from time row_IDs = list(6*rows[0] + 6*rows[1]) column_IDs = [str(i) for i in 2*(range(int(columns[0]), int(columns[0]) + 6))] zipped = zip(row_IDs, column_IDs) sample_names = ["".join(values) for values in zipped] IJ.setMinAndMax(1900, 11717) # adjust brightness and contrast IJ.run("Apply LUT") IJ.makeRectangle(200, 50, 730, 950) # initialize selection dial = WaitForUserDialog("Adjust selection area") dial.show() # ask user to place selection appropriately IJ.run("Crop") adjDir = os.path.join(directory, "Adjusted") if not os.path.exists(adjDir): os.mkdir(adjDir) adjImage = os.path.join(adjDir, "Adj " + f) IJ.saveAs("Jpeg", adjImage) ## make ROI list
from ij import IJ, Macro import java.lang.Thread as Thread # from ij.gui import WaitForUserDialog import glob, os __author__ = 'Nichole Wespe' inputDir = IJ.getDirectory("Choose Source Directory ") outputDir = IJ.getDirectory("Choose Destination Directory ") pattern = os.path.join(inputDir, "*Start.jpg") fileList = glob.glob(pattern) print "Found " + str(len(fileList)) + " sample files to montage." subDir = os.path.join(outputDir, "Montages") if not os.path.exists(subDir): os.mkdir(subDir) for f in fileList: # get date, sample from filename before opening date, sample, time = os.path.basename(f).split(" ") # find matching End.tif file f2 = os.path.join(inputDir, str(date) +" "+ str(sample) +" End.jpg") montage_name = " ".join([date, sample, "Montage.jpg"]) path = os.path.join(subDir, montage_name) args = "sample=["+montage_name +"] file1=["+ f +"] file2=["+ f2 +"] path=["+ path +"]" Macro.setOptions(Thread.currentThread(), args) IJ.run("create horiz montage", args)
# @ImageJ ij # @AbstractLogService log from ij import IJ from ij import Macro from ij.plugin.frame import RoiManager from net.imagej import DefaultDataset from loci.plugins import LociExporter from loci.plugins.out import Exporter import os import sys import glob sys.path.append(os.path.join(IJ.getDirectory('plugins'), "Scripts", "Plugins")) from libtools import crop from libtools.utils import get_dt 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
from ij import IJ from ij import Macro import os import time import sys sys.path.append(IJ.getDirectory('plugins')) import fijiCommon as fc from mpicbg.trakem2.align import RegularizedAffineLayerAlignment from java.awt.geom import AffineTransform from java.awt import Rectangle from java.util import HashSet from ini.trakem2 import Project, ControlWindow from ini.trakem2.display import Patch from register_virtual_stack import Register_Virtual_Stack_MT namePlugin = 'alignRigid_LM' MagCFolder = fc.startPlugin(namePlugin) ControlWindow.setGUIEnabled(False) # get mosaic size MagCParameters = fc.readMagCParameters(MagCFolder) executeAlignment = MagCParameters[namePlugin]['executeAlignment'] boxFactor = MagCParameters[namePlugin]['boxFactor'] # e.g. 0.5, use only the center part of the layer to compute alignment: 0.5 divides the x and y dimensions by 2 projectPath = fc.findFilesFromTags(MagCFolder,['LMProject'])[0] # alignment parameters regParams = Register_Virtual_Stack_MT.Param() regParams.minInlierRatio = 0 regParams.registrationModelIndex = 1
def selectBest(imp): imp.getWindow().setLocation(0,0) file_name = imp.getTitle() file_path = IJ.getDirectory('image') printLog("filepath is "+file_path,1) [SI_version,nFrame,zStepSize,nStacks]=zyGetProperty(imp,"SI_version,nFrame,zStepSize,nStacks") #need correct nSlices? do not delete any nSlices = imp.getNSlices()/nFrame #otherwise, calculate by fiji function msgStr = "The image has "+str(nFrame)+" frames from "+str(nStacks)+" stacks, was collected by ScanImage version "+str(SI_version) printLog(msgStr,0) if nFrame == 1: printLog("User need to import a file with multi-frames",0) else: #duplicate one for resorting IJ.run(imp,"Duplicate...", "title=resortStack duplicate range=1-%d" %imp.getNSlices()) #bad fiji set this getNSlice() as all slice resort_stack=IJ.getImage() resort_stack.getWindow().setLocation(0,0) IJ.run(resort_stack, "Label...", "format=0 starting=1 interval=1 x=5 y=20 font=18"); #number pickup for every numRep IJ.selectWindow(file_name) #(width, height, nChannels, nSlices, nFrames) = imp.getDimensions(), bad fiji alway get wrong numRep = int(nFrame) m = int(nSlices) #real slice number when correcting the nFrames sPick = [] printLog("-Current tif file:"+file_name,1) printLog("-nSlice="+str(m)+", nFrame="+str(numRep),2) printLog("-start picking the best repeat.",1) for i in range(0,m): j = i*numRep+1 #Z-step number #make montage to check all repeats at the same time for pickup IJ.run(imp,"Make Montage...", "columns="+str(numRep/nStacks)+" rows="+str(nStacks)+" scale=1 first="+str(j)+" last="+str(j+numRep-1)+" increment=1 border=1 font=12 label") m1_imp = IJ.getImage() IJ.run(m1_imp,"8-bit", "") m1_imp.getWindow().setLocation(530,0) IJ.run(m1_imp,"Set... ", "zoom=92 x=0 y=0") m1_title=m1_imp.getTitle() #merge the previous one if i>0 if i==0: prePick = 1 #use first slice as mask IJ.run(resort_stack,"Duplicate...", "title=Max_z duplicate range=1-1" ) zMax=IJ.getImage() zMax_win = zMax.getWindow().setLocation(0,580) else: prePick = sPick[i-1] #use previous selected slice as mask #duplicate numRep times of previous, concatenate, make montage, for merging channel as red with m1_imp m2_imp = mkMask(imp,prePick,numRep,nStacks) #merge the mask, and make new m1_imp as a 2-slice stack: Green (original) with merged m1_imp = zyMergeView(m1_imp,m2_imp) #pickup the best slice with slice number pickN = pickNum(numRep,nStacks) if not pickN: break else: pickN = pickN+j-1 #do the moveSlice on resort_stack: move to the initial of pick: j resort_stack = moveSlice(resort_stack,pickN,j) #preview Z projection in a copy of resort_stack zMax.close() #clear previous Z projection zMax = preview_Z(resort_stack,numRep,i+1) #show the new preview based on new pick #store the lucky slice number for making the substack in the future sPick.append(int(pickN)) #mmp = IJ.getImage() m1_imp.close() if len(sPick) == m: #means you have pick all slices required, but not cancel during process (break all out) IJ.selectWindow(file_name) outList =",".join(str(e) for e in sPick) #better to make a str: outList="slices=1,2,3" printLog("-Slices picked by user:"******"Make Substack...", "slices=%s" %(outList)) #all need to be str sr_imp = IJ.getImage() sr_imp.setTitle('P_'+file_name) #imp.changes = 0 #imp.close() #zMax.close() #need to do: put a header for sr_imp here msgStr = "pixel_width=0.102857 pixel_height=0.102857 voxel_depth="+str(zStepSize) printLog("-Set the property of picked stack "+sr_imp.getTitle()+" to:"+msgStr,1) IJ.run(sr_imp, "Properties...", msgStr) pickName = sr_imp.getTitle() destFolder_SR = os.path.join(file_path, 'Single_rep') #do multireg alignment doAlign(sr_imp,destFolder_SR) zyAddProperty(sr_imp) saveStack(destFolder_SR,pickName,sr_imp) destFolder_RS = os.path.join(file_path, 'reSort') #add Info zyAddProperty(resort_stack) saveStack(destFolder_RS,file_name,resort_stack) else: m1_imp.close() resort_stack.changes = 0 imp.changes = 0 imp.close() zMax.close() resort_stack.close()
def outputpath(event) : self.__pathdir=IJ.getDirectory("image") self.__pathdir=IJ.getDirectory("") self.__text.setText(self.__pathdir)
from ij.plugin import Duplicator from ij.plugin import ChannelSplitter from ij.plugin import SubstackMaker from net.imglib2 import FinalInterval from jarray import array import sys from net.imglib2.meta import ImgPlus from net.imglib2.img.display.imagej import ImageJFunctions from java.awt import Color from ij.plugin.filter import BackgroundSubtracter import os import copy homedir=IJ.getDirectory('imagej') jythondir=os.path.join(homedir,'plugins/Scripts/Evalulab/') jythondir=os.path.abspath(jythondir) sys.path.append(jythondir) import SpotDetectionFunction reload(SpotDetectionFunction) from SpotDetectionFunction import SpotDetectionGray from SpotDetectionFunction import SpotDetection2 from SpotDetectionFunction import SpotDetection3 import CountParticles reload(CountParticles) from CountParticles import countParticles import ExportDataFunction
from ij import IJ # from ij.gui import WaitForUserDialog import glob, os __author__ = 'Nichole Wespe' inputDir = IJ.getDirectory("Choose Source Directory ") pattern = os.path.join(inputDir, "*.tif") fileList = glob.glob(pattern) print "Found " + str(len(fileList)) + " tiff files to process." for f in fileList: IJ.open(f) IJ.run("plate cropper") imp = IJ.getImage() imp.close()
bi = chart.createBufferedImage(600, 400) imp = ImagePlus('My Plot Title', bi) imp.show() #################### # Create SVG image # #################### #Could be open using inkscape, see https://inkscape.org #1- Get a DOMImplementation and create an XML document domImpl = GenericDOMImplementation.getDOMImplementation() document = domImpl.createDocument(None, 'svg', None) #2-Create an instance of the SVG Generator svgGenerator = SVGGraphics2D(document) #3-Draw the chart in the SVG generator bounds = Rectangle(600, 400) chart.draw(svgGenerator, bounds) #4-Select a folder to save the SVG dir = IJ.getDirectory('Where should the svg file be saved?') if(dir!=None): #5-Write the SVG file svgFile = File(dir + 'test.svg') outputStream = FileOutputStream(svgFile) out = OutputStreamWriter(outputStream, 'UTF-8') svgGenerator.stream(out, True) outputStream.flush() outputStream.close() print 'Saved in %s' % (os.path.join(dir,'test.svg'))
# read in and display ImagePlus object(s) from ij.io import OpenDialog from ij import IJ import os import sys imctool_dir = os.path.join(IJ.getDirectory('plugins'), 'imctools') sys.path.append(os.path.realpath(imctool_dir)) import imctools.imagej.library as lib def view_image5d_ome(img, ome_meta): """ :param img: :param ome_meta: :return: """ nchannels = ome_meta.getChannelCount(0) channel_names = [ome_meta.getChannelName(0, i) for i in range(nchannels)] img = lib.get_image5d(imgName=ome_meta.getImageName(0), img_stack=img.getStack(), channel_names=channel_names) img.show() def load_and_view(file_name): (imag, omeMeta) = lib.load_ome_img(file_name)
nSlices = int(infoStr.split('numberOfZSlices=')[1].split('\r')[0]) nFrame = imp.getNSlices()/nSlices SI_nFrame = int(SI_Info.split('numberOfFrames=')[1].split('\r')[0]) nStacks = nFrame/SI_nFrame if nFrame > SI_nFrame else 1 newInfo = '\nzNumSlices='+str(nSlices)+'\nzNumFrame='+str(nFrame)+'\nzTotalSlices='+str(imp.getNSlices())+'\nzNumStacks='+str(nStacks)+'\nzModifiedTime='+"'"+time.strftime("%c")+"'\r" print newInfo infoStr = SI_Info+newInfo imp.setProperty('Info',infoStr) def saveStack(destFolder,file_name,imp): #rename the result and save it to subfolder if not os.path.isdir(destFolder): os.makedirs(destFolder) fullname=os.path.join(destFolder,file_name) #print (fullname) fs = FileSaver(imp) #print 'bSaveStack()', fullPath, 'nslices=', sr_imp.getNSlices() print('save result to: ',fullname) msgStr = "Dimension:" + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices()) print (msgStr) IJ.log(" -Save "+file_name+" to "+destFolder) IJ.log(" -"+msgStr) fs.saveAsTiffStack(fullname) imp = IJ.getImage() file_name = imp.getTitle() file_path = IJ.getDirectory('image') zyAddProperty(imp) saveStack(file_path,file_name,imp) imp.close()