def getOptions(dest): ###function that allows the user to choose their next course of action### # colorscale() gd = NonBlockingGenericDialog("Continue?") gd.setCancelLabel("Quit") gd.enableYesNoCancel("Remain on Image", "Open Next") gd.showDialog() if gd.wasCanceled(): # quits imp = IJ.getImage() current_title = imp.getTitle() imp.close() renamer(dest, current_title, extension) exit() elif gd.wasOKed(): # remains on image count_options = 0 return else: # opens the next image in a directory. count_options = 1 imp = IJ.getImage() current_title = imp.getTitle() imp.close() renamer(dest, current_title, extension) file_opener(current_title, extension) imp = IJ.getImage() imp.setDisplayMode(IJ.GRAYSCALE) colorscale() imp = IJ.getImage() win = imp.getWindow() win.maximize() win.setLocation(int(xpos_def), int(ypos_def)) getOptions(dest)
def displayInfoDialog(text, title = 'Info'): global infoDialog infoDialog = NonBlockingGenericDialog(title) infoDialog.addMessage(text) infoDialog.setLocation(0,0) infoDialog.setSize(400,800) infoDialog.show() return infoDialog
def exit_assay(): gd = NonBlockingGenericDialog("Exit Assay") gd.setCancelLabel("Quit & Save") gd.setOKLabel("Quit") gd.showDialog() if gd.wasCanceled(): # quits imp = IJ.getImage() current_title = imp.getTitle() imp.close() renamer(dest, current_title, extension) exit() elif gd.wasOKed(): exit()
def selection(region): nbgd = NonBlockingGenericDialog(region) nbgd.setCancelLabel('Return') nbgd.enableYesNoCancel('ROI OK', 'Redraw') nbgd.showDialog() if nbgd.wasOKed(): imp = IJ.getImage() roi = imp.getRoi() roi_check(roi) return if nbgd.wasCanceled(): exit_assay() else: repeat_measure()
def repeat_measure(): IJ.run("Select None") gd = NonBlockingGenericDialog("Redraw ROI?") gd.showDialog() if gd.wasOKed(): selection(region) if gd.wasCanceled(): exit_assay()
def getEdgeCoord(x, y, circRad, imp, msg): IJ.run(imp, "Select None", "") imp.setRoi(IJ.OvalRoi(x, y, circRad * 2, circRad * 2)) gd = NonBlockingGenericDialog(msg) gd.addMessage('Select ' + msg + ' coordinates') gd.showDialog() if gd.wasCanceled(): return None # wait for user input coord = imp.getRoi().getContourCentroid() IJ.run(imp, "Select None", "") return coord[0] - circRad, coord[1] - circRad
def makeSelections(x, y, rm, imp, circRad): rm.reset() for j in range(len(x)): for i in range(len(x[-1])): imp.setRoi(IJ.OvalRoi(x[j][i], y[j][i], circRad * 2, circRad * 2)) rm.addRoi(imp.getRoi()) rm.runCommand(imp, "Show All with labels") gd = NonBlockingGenericDialog('Confirm ROI positions') gd.addMessage('Are the ROIs positioned correctly? Move them if necessary') gd.showDialog() if gd.wasCanceled(): return None return imp, rm
def __selectMeasureStack(self) : # We allow the user to choose what to measure in the stack, and on which stack. gd1=NonBlockingGenericDialog("Stack Choice for measures") idimages=WindowManager.getIDList() images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ] imagesnames=[img.getTitle() for img in images] activindex=0 for i in range(len(imagesnames)) : if imagesnames[i] == self.__activeTitle : activindex=i gd1.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex]) gd1.showDialog() chosenstack=gd1.getNextChoice() self.__img=WindowManager.getImage(chosenstack) IJ.selectWindow(self.__img.getID()) if gd1.wasOKed() : return True else : return False
def __selectTrackStack(self) : gd0=NonBlockingGenericDialog("Stack Choice") idimages=WindowManager.getIDList() #images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ] images=[WindowManager.getImage(imgID) for imgID in idimages] imagesnames=[img.getTitle() for img in images] for i in range(len(imagesnames)) : if imagesnames[i] == self.__activeTitle : activindex=i gd0.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex]) gd0.showDialog() chosenstack=gd0.getNextChoice() self.__img = WindowManager.getImage(chosenstack) self.__maxLife = self.__img.getImageStackSize() IJ.selectWindow(self.__img.getID()) self.__activeTitle=self.__img.getTitle() self.__imagesnames[:]=[] #self.__imagesnames.append("image1") self.__imagesnames.append(self.__activeTitle) if gd0.wasOKed() : return True else : return False
def pick_roi_and_crop(self): self.show() self.display_roi() wait = NonBlockingGenericDialog("Move the ROI around the cell of interest") wait.addMessage( "Click ok to crop and process ROI\n" "Cancel to skip this image\n" "Check 'Quit' to terminate script" ) wait.addCheckbox("Quit", False) wait.showDialog() kill_switch = wait.getCheckboxes()[0].state # print kill_switch if wait.wasOKed(): self.crop_project_and_montage() while True: proceed = NonBlockingGenericDialog("Process another ROI?") proceed.addMessage("Click ok to repeat this image\n" "Click cancel to move onto next image") proceed.showDialog() if proceed.wasOKed(): print "Repeat this image" self.crop_project_and_montage() else: print "Lets move on" for i in self.stack_imps.values(): i.close() break return kill_switch else: print "User canceled this image before doing anything" for i in self.stack_imps.values(): i.close() return kill_switch
background_c1.append(float(row[0])) background_c2.append(float(row[1])) # ok we can now access these variables. # resets image imp = IJ.getImage() imp.setT(1) imp.setC(1) # sets the tools to be used IJ.run("Point Tool...", "type=Cross color=Yellow size=Tiny label counter=0 add_to") IJ.setTool("point") # Asks you to select cells, hitting cancel if you made a mistake nbgd = NonBlockingGenericDialog("Select Cells") nbgd.showDialog() if nbgd.wasCanceled(): IJ.run("Remove Overlay") # turns the overlay into an object. imp = IJ.getImage() overlay = Overlay() overlay = imp.getOverlay() # asks if you have selected anything try: roi_points = overlay.toArray() except AttributeError as error: nbgd = NonBlockingGenericDialog("Select some cells boi") nbgd.showDialog() if blur_state == True: set_sigma = "sigma=" + str(blur_val) + " stack"
readme_fpath = os.path.join(script_path, "README.txt") params = Parameters() title = "Membrane Blebbing version " + Parameters._version_string try: f = open(readme_fpath, "rb") text = f.readlines() except: raise IOError("Error reading README.txt") finally: f.close() sb = StringBuilder() for line in text: sb.append(line) panel = Panel() txtArea = JTextArea(sb.toString()) txtArea.setEditable(False) txtArea.setLineWrap(True) txtArea.setWrapStyleWord(True) scrollpane = JScrollPane(txtArea) scrollpane.setPreferredSize(Dimension(500, 200)) panel.add(scrollpane) dialog = NonBlockingGenericDialog(title) #for line in text: # dialog.addMessage(line); dialog.addPanel(panel) dialog.showDialog()
def perform_manual_qc(imp, rois, important_channel=1): """given cell rois generated by automatic methods, allow user to delete/add/redraw as appropriate""" for ch in range(imp.getNChannels()): imp.setC(ch + 1) sat_frac = 0.99 if (ch + 1) == important_channel else 0.01 IJ.run(imp, "Enhance Contrast", "saturated={}".format(sat_frac)) imp.setC(important_channel) IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") for roi in rois: roim.addRoi(roi) auto_rois_only = rois while not proceed: dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual correction of segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T). " ) dialog.addMessage("Delete and redraw cells as appropriate. ") dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added. " ) dialog.showDialog() if dialog.wasCanceled(): print("Manual segmentation canceled") return auto_rois_only elif dialog.wasOKed(): if roim.getCount() == 0: rois = [] confirm_dialog = GenericDialog("Continue?") confirm_dialog.addMessage( "No rois selected in this FOV. Are you sure you want to proceed?" ) confirm_dialog.setOKLabel("Yes, proceed") confirm_dialog.setCancelLabel("No, not yet") confirm_dialog.showDialog() if confirm_dialog.wasOKed(): proceed = True else: rois = roim.getRoisAsArray() proceed = True roim.reset() roim.close() for ch in range(imp.getNChannels()): imp.setC(ch + 1) IJ.run(imp, "Enhance Contrast", "saturated={}".format(0.35)) imp.setC(important_channel) return rois
coords_vals = normalize_coords_in_list(get_list_from_dict(full_keys,coords)) im = IJ.getImage() if im.getNChannels() == 1: LUTarray = [LUT.createLutFromColor(Color.WHITE)] elif im.getNChannels() == 2: LUTarray = [LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.WHITE)] elif im.getNChannels() == 3: LUTarray = [LUT.createLutFromColor(Color.GREEN),LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.WHITE)] elif im.getNChannels() == 4: LUTarray = [LUT.createLutFromColor(Color.BLUE),LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.GREEN),LUT.createLutFromColor(Color.WHITE)] elif im.getNChannels() == 5: LUTarray = [LUT.createLutFromColor(Color.BLUE),LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.GREEN),LUT.createLutFromColor(Color.YELLOW),LUT.createLutFromColor(Color.WHITE)] else: LUTarray = [] nbgd = NonBlockingGenericDialog("Pick freehand ROI") nbgd.setLocation(0,0) nbgd.addMessage("OK to run, cancel to exit") nbgd.showDialog() isContinue = nbgd.wasOKed() while isContinue: roi = im.getRoi() if (roi is not None): float_poly = roi.getFloatPolygon() containing_tiles_superlist = [] for i in range(float_poly.npoints): containing_tiles_superlist.append(find_containing_tiles([float_poly.xpoints[i],float_poly.ypoints[i],0],coords_vals,scale_info[1],scale_info[2])) upscaled_coords = upscale_coords(coords,scale_info[0]) containing_tiles_dict = rearrange_tile_list(containing_tiles_superlist) copy_fullsize_tiles(["tile_"+key for key in containing_tiles_dict.keys()],parentLSMFilePath+"_tiles/",parentLSMFilePath+"_tiles/subtiles/",".ome.tif") subupcoords_vals = normalize_coords_in_list(get_list_from_dict(["tile_"+key for key in containing_tiles_dict.keys()],upscaled_coords))
diff = pts[i] - pts[i-1] if (diff < 0): return False return True theImage = IJ.getImage() stayinloop = True # IJ.run("RGB Color") injuryfirst = True injuryLengths = [] totalLengths = [] injuryRatios = [] Xpositions = [] while stayinloop: gd = NonBlockingGenericDialog("Pick points...") gd.addMessage("Use multipoint tool to pick points along a column (Y-axis).\nAlternate points to mark injured vs uninjured area.") gd.setCancelLabel("Quit") gd.setOKLabel("Define column") gd.addCheckbox("First segment is injury?",injuryfirst) gd.showDialog() if (gd.wasOKed()): roi = theImage.getRoi() if roi is None: IJ.error("No ROI selected") else: polygon = roi.getFloatPolygon() # if len(polygon.xpoints) % 2 == 0 and is_monotonic_increasing(polygon.ypoints): if is_monotonic_increasing(polygon.ypoints):
import os, sys from ij import IJ, ImagePlus, ImageStack from ij.io import DirectoryChooser from ij.measure import Measurements from ij.gui import NonBlockingGenericDialog from ij.gui import WaitForUserDialog # Get input and output directories dc = DirectoryChooser("Choose an input directory") inputDirectory = dc.getDirectory() dc = DirectoryChooser("Choose an output directory") outputDirectory = dc.getDirectory() gd = NonBlockingGenericDialog("Channel Options") gd.addStringField("Enter your name: ", "") gd.showDialog() name = gd.getNextString() if gd.wasCanceled(): print "User canceled dialog!" # Finds all the subfolders in the main directory with open(outputDirectory + "annotations_" + name + ".csv", "w") as log: subfolders = [] # for subfolder in os.listdir(inputDirectory): # if os.path.isdir(inputDirectory + subfolder):
from array import zeros from ij import IJ from ij.gui import NonBlockingGenericDialog from ij.process import ByteProcessor from ij import ImageStack from ij import ImagePlus theImage = IJ.getImage() gd = NonBlockingGenericDialog("Set slice params...") gd.addNumericField("Slice start:",1,0) gd.addNumericField("Slice end:",theImage.getNSlices(),0) gd.showDialog() if (gd.wasOKed()): startSlice = gd.getNextNumber() endSlice = gd.getNextNumber() width = theImage.getWidth() height = theImage.getHeight() newStack = ImageStack(width,height) for i in range(startSlice,endSlice+1): theImage.setSlice(i) theImage.killRoi() pixels = zeros('b',width*height) bp = ByteProcessor(width,height,pixels) bp.setColor(127) doStaySlice = True while doStaySlice: waiter = NonBlockingGenericDialog("Set cast")
def ER_points(all_x, all_y, overlay, ER_measurements): imp = IJ.getImage() overlay = Overlay() overlay = imp.getOverlay() ## gets points added to overlay, and extracts a list of x & y values. list length must be three ### try: roi_points = overlay.toArray() except AttributeError as error: nbgd = NonBlockingGenericDialog("Select three Roi's") nbgd.hideCancelButton() nbgd.showDialog() overlay = imp.getOverlay() roi_points = overlay.toArray() pass for i in range(overlay.size()): roi = overlay.get(i) p = roi_points[i].getPolygon() all_x.append(p.xpoints[0]) all_y.append(p.ypoints[0]) while len(all_x) != 3: if len(all_x) < 3: nbgd = NonBlockingGenericDialog("Must Select three Roi's") nbgd.setCancelLabel("Roi Reset") nbgd.showDialog() if nbgd.wasCanceled(): IJ.run("Remove Overlay", "") ER_points(all_x, all_y, overlay, ER_measurements) if len(all_x) > 3: all_x.pop(0) all_y.pop(0) overlay.clear()
tileToOpen = int(xtiles/2) * int(ytiles/2) windowName = "tile_" + str(tileToOpen) + ".ome.tif" params = "open=["+ tileDir +"tile_"+str(tileToOpen)+".ome.tif] color_mode=Default view=Hyperstack stack_order=XYCZT" ## Gets the number of channels in the image IJ.run("Bio-Formats Importer", params); testTile = WindowManager.getImage(windowName) numTotalChannels = testTile.getNChannels() labels = ["" for x in range(numTotalChannels)] defaultValues = [False for x in range(numTotalChannels)] for i in range(1,numTotalChannels+1): labels[i-1] = "Channel" + str(i) defaultValues[i-1] = False ## Allows user to choose which channels to analyze gd = NonBlockingGenericDialog("Select channel...") gd.addCheckboxGroup(numTotalChannels,1,labels,defaultValues) gd.showDialog() runOnChannel = [False for x in range(numTotalChannels)] for i in range(numTotalChannels): runOnChannel[i] = gd.getNextBoolean() ## Runs the 3D object counter on all the tiles and saves the results to disk 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"); channelImage = ChannelSplitter.split(testTile) testTile.close() for i in range(numTotalChannels): if (runOnChannel[i]): channelImage[i].show() IJ.run(channelImage[i], "3D Objects Counter", "threshold=42 slice=47 min.=300 max.=24903680 statistics") IJ.saveAs("Results", "/Volumes/DUNCAN/2015/03_12_15 ERT2 Confetti DSS earlier trace/A5/9396-abluminal.lsm_tiles/objects/C" + str(i+1) + "-tile_45.csv")
os.chdir(thisdir) # Read csv files into lists, create nuclei list T = txt2list(os.path.join(thisdir, 't.csv')) X = txt2list(os.path.join(thisdir, 'x.csv')) Y = txt2list(os.path.join(thisdir, 'y.csv')) nuclei = defaultdict(list) for i, t in enumerate(T): nuclei[t] = (X[i], Y[i]) print 'Working on: ', cID # Add listener to image listener = PointRoiRefresher(imp, nuclei) ImagePlus.addImageListener(listener) # Wait for user to clear current cell gd = NonBlockingGenericDialog("Advance to next cell?") gd.setOKLabel('Next') gd.setCancelLabel('Completely exit') gd.addCheckbox('Skip this cell?', False) gd.showDialog() if gd.wasOKed(): # OK means 'advance' imp.removeImageListener(listener) if gd.getNextBoolean(): with open(os.path.join(thisdir, 'skipped.txt'), 'w') as f: f.write('Skipped') # Log the cell as done with open(log_filename, 'a') as f: f.write(''.join((cID, '\n'))) print "Advancing to next cell..." continue
def choose_segmentation_and_projection_channels(info): dialog = NonBlockingGenericDialog("Select channels...") channels = [info.ch1_label, info.ch2_label] dialog.addRadioButtonGroup("Segmentation channel: ", channels, 1, len(channels), channels[0]) dialog.addRadioButtonGroup("Projection channel: ", channels, 1, len(channels), channels[1]) dialog.showDialog() if dialog.wasCanceled(): return None seg_ch = dialog.getNextRadioButton() proj_ch = dialog.getNextRadioButton() return channels.index(seg_ch), channels.index(proj_ch)
selection(region) to_transport_channel() average_max = high(bit_depth) IJ.setForegroundColor(255, 255, 255) IJ.setBackgroundColor(1, 1, 1) imp2 = IJ.getImage() IJ.run(imp2, "Draw", "slice") IJ.run("Select None") if always_auto is True: to_transport_channel() average_max = high(bit_depth) if always_auto is False: if always_select is False: nbgd = NonBlockingGenericDialog("Golgi_selection") Methods = ['Automatic Selection', 'Manual Selection'] nbgd.addRadioButtonGroup("Methods", Methods, 2, 1, Methods[0]) nbgd.hideCancelButton() nbgd.showDialog() golgi_method = nbgd.getNextRadioButton() if golgi_method == Methods[0]: average_max = high(bit_depth) elif golgi_method == Methods[1]: to_golgi_channel() IJ.setTool("polygon") region = 'Select Golgi' selection(region) to_transport_channel() average_max = high(bit_depth) IJ.setForegroundColor(255, 255, 255)
def main(): # define here which membrane indices will be used in the analysis, with last index the "control" index membrane_indices = [-1, 0, 1, 3] # for now, work with frontmost open image... imp = IJ.getImage() im_title = imp.getTitle() settings = MembraneEvolutionAnalysisSettings( membrane_indices=membrane_indices) settings.loadPersistedSettings() timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') DirectoryChooser.setDefaultDirectory((settings.output_path)) dc = DirectoryChooser('Select the root folder for saving output') output_root = dc.getDirectory() if output_root is None: raise IOError('no output path chosen') settings.output_path = output_root # get calibration cal = imp.getCalibration() if cal.getTimeUnit() == "sec": cal.setTimeUnit('s') # pop up a dialog prompting for selection of zero time point, frame interval, and time step for analysis time_steps_not_ok = True while time_steps_not_ok: dialog = NonBlockingGenericDialog("Determine time parameters...") dialog.addNumericField("0 timepoint frame (1-index): ", settings.zero_timepoint_frame, 0) dialog.addNumericField("Acquisition time step (s): ", cal.frameInterval, 2) # assume stored in seconds dialog.addNumericField( "Time step for analysis (s): ", cal.frameInterval * settings.analysis_frame_step, 2) dialog.showDialog() if dialog.wasCanceled(): return zero_f = dialog.getNextNumber() acq_t_step = dialog.getNextNumber() analysis_t_step = dialog.getNextNumber() if acq_t_step != 0 and analysis_t_step != 0: analysis_frame_step = analysis_t_step / acq_t_step if round(analysis_frame_step) == analysis_frame_step: time_steps_not_ok = False settings.zero_timepoint_frame = zero_f settings.analysis_frame_step = analysis_frame_step if time_steps_not_ok: warning_dlg = GenericDialog("Error!") warning_dlg.addMessage( "Analysis time step must be an integer multiple of acquisition time steps, and neither should be zero!!" ) warning_dlg.setOKLabel("Try again...") warning_dlg.showDialog() if warning_dlg.wasCanceled(): return start_frame = int(((zero_f - 1) % analysis_frame_step) + 1) end_frame = int(imp.getNFrames() - (imp.getNFrames() - zero_f) % analysis_frame_step) frames = [ f + 1 for f in range(start_frame - 1, end_frame, int(analysis_frame_step)) ] print("frames = " + str(frames)) imp.killRoi() analysis_imp = SubstackMaker().makeSubstack( imp, str(start_frame) + "-" + str(end_frame) + "-" + str(int(analysis_frame_step))) imp.changes = False imp.close() analysis_imp.show() drawn_membranes = [ TimepointsMembranes(input_image_title=im_title, time_point_s=(t - 1) * acq_t_step) for t in frames ] membranes_listener = UpdateRoiImageListener(drawn_membranes) analysis_imp.addImageListener(membranes_listener) # now attach roi listener to store all 0th membranes after showing a waitforuserdialog to prompt continuation IJ.setTool("freeline") for membrane_idx in membrane_indices: # if membrane_idx>50: # IJ.setTool("line"); analysis_imp.killRoi() membranes_listener.resetLastFrame() membranes_listener.setCurrentMembraneIndex(membrane_idx) analysis_imp.setZ(1) continue_dlg = WaitForUserDialog( "Continue?", "Click OK once all the " + str(membrane_idx) + "-index membranes have been drawn") continue_dlg.show() membranes_listener.imageUpdated(analysis_imp) drawn_membranes = membranes_listener.getDrawnMembraneTimepointsList() json_path = os.path.join(output_root, "Membranes " + timestamp + ".json") f = open(json_path, 'w+') try: json.dump(drawn_membranes, f, default=encode_membrane) finally: f.close() # save csv containing mebrane measurements for current membrane index csv_path = os.path.join( output_root, ("Membrane measurements " + timestamp + ".csv")) if membrane_idx == membrane_indices[0]: try: f = open(csv_path, 'wb') writer = csv.writer(f) writer.writerow([ "Membrane index", ("Time point, " + cal.getTimeUnit()), ("Membrane length, " + cal.getUnit()), ("Euclidean length, " + cal.getUnit()), "Membrane sinuoisty" ]) finally: f.close() try: f = open(csv_path, 'ab') writer = csv.writer(f) for mems in drawn_membranes: mem = mems.getMembrane(membrane_idx) if mem is not None: writer.writerow([ membrane_idx, mems.time_point_s, mem.getPathLength() * cal.pixelWidth, mem.getEuclidean() * cal.pixelWidth, mem.getSinuosity() ]) finally: f.close() settings.persistSettings() settings.save_settings() print("Finished getting all membranes with indices " + str(membrane_indices)) analysis_imp.close()
from ij import IJ, ImagePlus, ImageStack, CompositeImage from ij.plugin import HyperStackConverter import ij.plugin from ij import WindowManager as WM import os from os import path import re from re import sub from ij.plugin import Concatenator from ij.io import OpenDialog, DirectoryChooser from ij.gui import GenericDialog, NonBlockingGenericDialog from ij.text import TextPanel as TP from ij.measure import ResultsTable as RT # Create a non-blocking dialog to enter the metadata psgd = NonBlockingGenericDialog( "Choose the frame that shows the right conformation of the heart?") psgd.addNumericField("Which frame to choose?", 1, 0) psgd.addCheckbox("Use table of selected frames?", False) psgd.showDialog() choose = psgd.getNextNumber() choice = psgd.getCheckboxes().get(0).getState() #open a tab separated txt file with one column Frame selected if choice == 1: choose = 0 IJ.run("Table... ", "open=") frametable = WM.getWindow("selected_frames.txt") meta = frametable.getTextPanel() metaRT = TP.getResultsTable(meta) # Choose a directory
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 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 measure_gd(): # Dialouge box for measurements. # It from javax.swing import JButton gd = NonBlockingGenericDialog("Loci to compartment") gd.setResizable(True) gd.pack() gd.addMessage( "Draw a freehand ROI around the loci and closest \ncompartment(e.g. speckle) and press 0 on keyboard." ) next_imp_bt = JButton('Analyze active image', actionPerformed=analyze_image) gd.add(next_imp_bt) gd.setLocation(10, 10) gd.setAlwaysOnTop(True) gd.hideCancelButton() gd.showDialog() # if gd.wasOKed(): IJ.log("Measurement done! Happy FISHing")
from ij import IJ from ij import ImagePlus from ij.gui import NonBlockingGenericDialog from ij.gui import WaitForUserDialog from ij.plugin import ChannelSplitter from ij.plugin import ImageCalculator from ij.measure import ResultsTable from ij.measure import Measurements from ij.plugin.filter import Analyzer ## Main body of script theImage = IJ.getImage() gd = NonBlockingGenericDialog("Pick parameters...") gd.addChoice("Analysis_channel",["Channel "+str(i+1) for i in range(theImage.getNChannels())],"Channel 1") gd.addNumericField("Pick_threshold",50,0) gd.addCheckbox("Apply_min",True) gd.showDialog() if (gd.wasOKed()): analysisChannel = gd.getNextChoiceIndex() + 1 intensityThreshold = gd.getNextNumber() doMin = gd.getNextBoolean() splitImage = ChannelSplitter.split(theImage) dataImage = splitImage[analysisChannel-1].duplicate() if doMin: IJ.run(dataImage,"Minimum...", "radius=2 stack") goRun = True rt = ResultsTable() while goRun: wfud = WaitForUserDialog("Pick freehand ROI, then hit OK to analyze") wfud.show() roi = theImage.getRoi()
rmi.reset() impBin2.killRoi() #Add nuclei to ROIs IJ.run( 'Analyze Particles...', 'size=' + parameters['nucsize'] + ' circularity=' + parameters['nuccircularity'] + ' exclude add') rois.append([zslice, rmi.getRoisAsArray()]) print 'Added ' + str(len(rmi.getRoisAsArray())) + ' ROIs' #Close images impBin1.changes = False impBin1.close() impBin2.changes = False impBin2.close() #View and save ROIs imp.show() rmi.reset() print len(rois) for roisonslice in rois: imp.setPosition(1, roisonslice[0], 1) for roi in roisonslice[1]: imp.setRoi(roi) rmi.runCommand('Add') rmi.runCommand('Save', outputFile) if parameters['test']: gd = NonBlockingGenericDialog('Continue?') gd.showDialog() if gd.wasCanceled(): sys.exit('User cancelled script')
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 __settings(self, imgName) : """ Lets the user to choose different measures to make, and displays it following the choice of the user. """ try : dico=self.__dictCells[imgName] except KeyError : try : dico=self.__dictCells[imgName[:-4]] except KeyError : return False else : imgName=imgName[:-4] dico=self.__dictCells[imgName] for cellname in dico.keys() : self.__dictMeasures[dico[cellname]]={} # Represents the datas on a diagram 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) # Represents the datas on a series of graphs. def graphbuttonPressed(event) : colors=[] #img=IJ.getImage() #nbslices=self.__img.getImageStackSize() nbslices=self.__maxLife acell=dico.values()[0] if self.__useTime : x = acell.getListTimes() namex="Time sec" else : x = range(1,nbslices+1) namex = "Frame" maxx=max(x) minx=min(x) #x=[i for i in range(1,nbslices+1)] font=Font("new", Font.BOLD, 14) tempname = WindowManager.getUniqueName(self.__img.getShortTitle()) for i in range(len(self.__measures)) : #print "i", i, self.__measures[i] yarray=[] flag=True miny=10000000000 maxy=-1000000000 #we find the min and max values in order to set the scale. for cellname in self.__listcellname : colors.append(dico[cellname].getColor()) yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]]) #for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] : for meas in yarray[-1] : if (meas<miny) and (Double.isNaN(meas)==False) : miny=meas if max(yarray[-1])>maxy : maxy=max(yarray[-1]) miny-=0.1*miny maxy+=0.1*maxy count=0.05 for j in range(len(yarray)) : if j==0 : if len(self.__measures)>1 : plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j]) else : plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j]) plot.setLimits(minx,maxx,miny,maxy) plot.setColor(colors[j]) plot.changeFont(font) plot.addLabel(0.05, count, self.__listcellname[j]) else : plot.setColor(colors[j]) plot.setLineWidth(3) plot.addPoints(x,yarray[j],Plot.LINE) plot.addLabel(0.05, count, self.__listcellname[j]) count+=0.05 plot.setColor(colors[0]) plot.show() if len(self.__measures)>1 : IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use") #def histbuttonPressed(event) : # # pass # Represents the values in a tab. def tabbuttonPressed(event) : tab="\t" headings=[] measures=[] #img=IJ.getImage() #for i in range(self.__img.getImageStackSize()+1) : for i in range(self.__maxLife+1) : headings.append("Slice "+str(i)) headings[0]=WindowManager.getUniqueName(self.__img.getShortTitle()) #for m in self.__measurescompl : for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() : headstring="" for head in headings: headstring+=head+tab tw=TextWindow(self.__listfiles[0]+"-"+m,headstring,"",800,600) tp=tw.getTextPanel() #for cellname in dico.keys() : for cellname in self.__listcellname : line=[] line=[str(meas)+tab for meas in self.__dictMeasures[dico[cellname]][m]] line.insert(0, cellname+tab) linestr="" for s in line: linestr+=s tp.appendLine(linestr) tp.updateDisplay() if self.__measuresparambool_global[0] : tw=TextWindow("Latency","cell\tLatency", "",800,600) tp=tw.getTextPanel() for i in range(len(self.__listcellname)) : #if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1]) #else : line=self.__listcellname[i]+"\t"+"NaN" line=self.__listcellname[i]+"\t"+str(latencies[i][1]) tp.appendLine(line) tp.updateDisplay() def helpbuttonPressed(event) : IJ.showMessage("TO DO") def newsetPressed(event) : gd0.dispose() self.__settings() def alignbuttonPressed(event) : IJ.showMessage("TO DO") def mergebuttonPressed(event) : IJ.showMessage("TO DO") def saveResults() : #if len(self.__listcellname) == 0 : nbslices=self.__maxLife acell=dico.values()[0] if self.__useTime : x = acell.getListTimes() namex="Time_sec" else : x = range(1,nbslices+1) namex = "Frame" if not path.exists(self.__rootpath+"Results"+os.path.sep) : os.makedirs(self.__rootpath+os.path.sep+"Results"+os.path.sep, mode=0777) tab="\t" nl="\n" measures=[] headstring="" #if self.__savemode : mode = "a" #else : mode ="w" mode = "a" #for i in range(1, self.__maxLife+1) :headstring += "Slice_"+str(i)+tab for i in range(self.__maxLife) :headstring += str(x[i])+tab #for m in self.__measurescompl : for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() : f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode) #f.write(m+nl) f.write(imgName+"-"+self.__time+"-"+m+"-"+namex+tab+headstring+nl) if len(self.__listcellname) == 0 : f.write("no cells") else : for cellname in self.__listcellname : linestr=cellname+tab for measure in self.__dictMeasures[dico[cellname]][m] : #print m, cellname, measure linestr += str(measure)+tab linestr+=nl f.write(linestr) f.close() if self.__measuresparambool_global[0] : m = "Latency" f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode) f.write(imgName+"-"+self.__time+"-"+m+nl) for i in range(len(self.__listcellname)) : #if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1]) #else : line=self.__listcellname[i]+"\t"+"NaN" line=self.__listcellname[i]+"\t"+str(latencies[i][1]) line+=nl f.write(line) f.close() # # ----------- main measures dialog ------------------------- # # Allows the user to choose the measures to make, etc.. measureslabels_indep=["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"] measureslabels_dep=["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"] measureslabels_global=["Latency", "velocity", "cumulatedDist"] measureslabels_dep_tabonly=set(["MidAxis","FerCoord","FerAxis","Fprofil","MidProfil","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"]) ens_measures_global=set(measureslabels_global) ens_measures_indep=set(measureslabels_indep) ens_measures_dep=set(measureslabels_dep) measureslabels=[] for label in measureslabels_indep : measureslabels.append(label) for label in measureslabels_dep : measureslabels.append(label) #self.__defaultmeasures=[False for i in range(len(measureslabels))] #self.__defaultmeasures_global=[False for i in range(len(measureslabels_global))] gdmeasures=NonBlockingGenericDialog("MeasuresChoice") gdmeasures.setFont(Font("Courrier", 1, 10)) gdmeasures.addMessage("******* TIME SETTINGS *******") gdmeasures.addCheckbox("Only starting at begining :", self.__onlystart) # 1 only start gdmeasures.addNumericField("Minimal Lifetime : ",self.__minLife,0) gdmeasures.addNumericField("Maximal Lifetime : ",self.__maxLife,0) #gdmeasures.addNumericField("Maximal Lifetime : ",self.__img.getImageStackSize(),0) gdmeasures.addCheckbox("x axis in seconds", self.__useTime) # 2 use time gdmeasures.addMessage("") gdmeasures.addMessage("") gdmeasures.addMessage("Choose the measures to make on the cells : ") gdmeasures.addMessage("******* TIME MEASURES *******") gdmeasures.addCheckboxGroup(4,8,measureslabels,self.__defaultmeasures) gdmeasures.addMessage("") gdmeasures.addMessage("******* GLOBAL MEASURES *******") gdmeasures.addMessage("PLEASE : If you have selected movement parameters you MUST to select XC and YC !") gdmeasures.addCheckboxGroup(3,1,measureslabels_global,self.__defaultmeasures_global) gdmeasures.addNumericField("Noise value for maxima finder: ",self.__noise,0) gdmeasures.addMessage("") gdmeasures.addMessage("******* OPTIONS *******") gdmeasures.addCheckbox("Select the cells in next dialog ?", self.__onlyselect) # 3 only select gdmeasures.addCheckbox("Save results to text files ?", self.__savetables) # 4 save files #gdmeasures.addCheckbox("Append mode ?", self.__savemode) # 5 append mode gdmeasures.addCheckbox("Analyse in batch mode ?", self.__batchanalyse) # 6 analysis batch mode gdmeasures.addCheckbox("Update overlay ?", self.__updateoverlay) # 7 update overlay gdmeasures.addMessage("") gdmeasures.addMessage("") help_panel=Panel() helpbutton=Button("HELP") helpbutton.actionPerformed = helpbuttonPressed help_panel.add(helpbutton) gdmeasures.addPanel(help_panel) gdmeasures.hideCancelButton() if not self.__batchanalyse : gdmeasures.showDialog() self.__onlystart=gdmeasures.getNextBoolean() # 1 only start self.__minLife=gdmeasures.getNextNumber() self.__maxLife=gdmeasures.getNextNumber() self.__useTime=gdmeasures.getNextBoolean() # 2 use time self.__measuresparambool=[] self.__measuresparambool_global=[] for i in range(len(measureslabels)) : self.__measuresparambool.append(gdmeasures.getNextBoolean()) self.__defaultmeasures[i]=self.__measuresparambool[-1] for i in range(len(measureslabels_global)) : self.__measuresparambool_global.append(gdmeasures.getNextBoolean()) self.__defaultmeasures_global[i] = self.__measuresparambool_global[i] self.__noise=gdmeasures.getNextNumber() self.__onlyselect=gdmeasures.getNextBoolean() # 3 only select self.__savetables = gdmeasures.getNextBoolean() # 4 save files #self.__savemode = gdmeasures.getNextBoolean() # 5 append mode self.__batchanalyse = gdmeasures.getNextBoolean() # 6 analyse mode self.__updateoverlay = gdmeasures.getNextBoolean() # 7 update overlay # we update a list of all cells that have a lifetime corresponding to what the user chose. if len (self.__allcells) == 0 : for cellname in dico.keys() : if dico[cellname].getLifeTime()>=self.__minLife : #and dico[cellname].getLifeTime()<=self.__maxLife : if self.__onlystart : if dico[cellname].getSlideInit()<2 : self.__allcells.append(cellname) else : self.__allcells.append(cellname) if self.__noise == 0 : self.__noise = None if self.__batchanalyse : self.__onlyselect = False if self.__onlyselect : try : self.__gw except AttributeError : if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777) self.__gw = CellsSelection() self.__gw.setTitle(imgName) self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep) self.__gw.show() self.__gw.setSelected(self.__allcells) while not self.__gw.oked and self.__gw.isShowing() : self.__gw.setLabel("Validate selection with OK !!") self.__listcellname = list(self.__gw.getSelected()) self.__gw.resetok() self.__gw.setLabel("...") self.__gw.hide() else : if self.__gw.getTitle() == imgName : self.__gw.show() self.__gw.setSelected(self.__listcellname) self.__listcellname[:]=[] while not self.__gw.oked and self.__gw.isShowing() : self.__gw.setLabel("Validate selection with OK !!") self.__listcellname = list(self.__gw.getSelected()) self.__gw.resetok() self.__gw.setLabel("...") self.__gw.hide() else : self.__gw.dispose() if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777) self.__gw = CellsSelection() self.__gw.setTitle(imgName) self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep) self.__gw.show() self.__gw.setSelected(self.__allcells) self.__listcellname[:]=[] while not self.__gw.oked and self.__gw.isShowing() : self.__gw.setLabel("Validate selection with OK !!") self.__listcellname = list(self.__gw.getSelected()) self.__gw.resetok() self.__gw.setLabel("...") self.__gw.hide() filestodelet=glob.glob(self.__pathdir+"Selected-Cells"+os.path.sep+"*.cell") for f in filestodelet : os.remove(f) for cell in self.__listcellname : sourcestr = self.__pathdir+"Cells"+os.path.sep+cell+".cell" deststr = self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell" #os.system("copy "+sourcestr+", "+deststr) #shutil.copy(self.__pathdir+"Cells"+os.path.sep+cell+".cell",self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell") shutil.copy(sourcestr,deststr) self.__dictNcells[imgName] = len(self.__listcellname) else : self.__listcellname = list(self.__allcells) self.__dictNcells[imgName] = len(self.__listcellname) if len(self.__listcellname) == 0 : self.__dictNcells[imgName] = 0 return False self.__img.hide() # we make the measures. for i in range(len(measureslabels)) : IJ.showProgress(i, len(measureslabels)) if self.__measuresparambool[i]==True : self.__measurescompl.append(measureslabels[i]) if (measureslabels[i] in measureslabels_dep_tabonly)==False : self.__measures.append(measureslabels[i]) if (i<18) and (measureslabels[i] in ens_measures_indep) : self.__measureAll(self.__img,measureslabels[i],False, imgName, self.__noise) ens_measures_indep.discard(measureslabels[i]) if i>=18 : self.__measureAll(self.__img,measureslabels[i],True, imgName, self.__noise) if self.__measuresparambool_global[0] : # calculate latency latencies=[] for i in range(len(self.__listcellname)) : IJ.showProgress(i, len(self.__listcellname)) latencies.append(self.latencie(self.__listcellname[i], self.__img, imgName, self.__useTime)) if self.__measuresparambool_global[1] : # calculate velocity self.__measures.append("velocity") #velocities=[] for i in range(len(self.__listcellname)) : IJ.showProgress(i, len(self.__listcellname)) self.__measureVelocity(self.__img,imgName) if self.__measuresparambool_global[2] : # calculate cumulatedDistance self.__measures.append("cumulatedDist") #velocities=[] for i in range(len(self.__listcellname)) : IJ.showProgress(i, len(self.__listcellname)) self.__measurecumulDist(self.__img,imgName) self.__img.show() self.__img.getProcessor().resetThreshold() if self.__updateoverlay : if self.__img.getOverlay() is not None : self.__img.getOverlay().clear() outputrois=[] cellnames=[] self.__img.hide() for cellname in self.__listcellname : for r in dico[cellname].getListRoi(): if isinstance(r,Roi) : pos=r.getPosition() #print "MC overlay", cellname, r.getName(), pos #r.setPosition(0) #overlay.add(r) outputrois.append(r) if "cell" in r.getName() : cellnames.append(r.getName()) else : cellnames.append(str(pos)+"-"+cellname) #print cellnames[-1] rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.show() self.__img.show() IJ.selectWindow(self.__img.getTitle()) rm.runCommand("reset") for i in range(len(outputrois)) : outputrois[i].setName(cellnames[i]) rm.addRoi(outputrois[i]) rm.select(rm.getCount()-1) rm.runCommand("Rename", cellnames[i]) IJ.run("Show Overlay", "") rm.runCommand("UseNames", "true") rm.runCommand("Associate", "true") IJ.run(self.__img, "Labels...", "color=red font=12 show use") IJ.run(self.__img, "From ROI Manager", "") rm.runCommand("Show None") rm.runCommand("Show All") # ----------- batch analyse ------------------------ if self.__batchanalyse : if self.__savetables : saveResults() self.__dictMeasures.clear() self.__allcells[:]=[] self.__measurescompl[:]=[] self.__measures[:]=[] return False # ---------- display methodes dialog ---------------- # Allows the user to choose how to see the results of the measures. gd0=NonBlockingGenericDialog("Display") gd0.addMessage("How do you want to see the results ?") panel0=Panel() diagrambutton=Button("Diagram") diagrambutton.actionPerformed = diagrambuttonPressed panel0.add(diagrambutton) graphbutton=Button("Graph") graphbutton.actionPerformed = graphbuttonPressed panel0.add(graphbutton) tabbutton=Button("Tab") tabbutton.actionPerformed = tabbuttonPressed panel0.add(tabbutton) gd0.addPanel(panel0) gd0.addCheckbox("Analyse next stack ?", self.__nextstack) gd0.hideCancelButton() gd0.showDialog() self.__nextstack = gd0.getNextBoolean() # ---------- save tables --------------------------- if self.__savetables : saveResults() # --------- re-start analysis ------------------- self.__dictMeasures.clear() #self.__listcellname[:]=[] self.__allcells[:]=[] self.__measurescompl[:]=[] self.__measures[:]=[] if self.__nextstack : return False else : return True
def measure_gd(src_folder,file_names): from javax.swing import JButton gd = NonBlockingGenericDialog("Loci to compartment") gd.setResizable(True) gd.pack() gd.addMessage("Draw a freehand ROI aound loci and closest \n compartment(e.g. speckle) and press 0 on keyboard.") gd.addMessage("To load next image press Next Image button.") next_imp_bt = JButton('Next Image', actionPerformed=load_next_image) gd.add(next_imp_bt) gd.setLocation(10,10) gd.setAlwaysOnTop(True) gd.hideCancelButton() gd.showDialog() # if gd.wasOKed(): IJ.log( "Measurement done! You're welcome!")
def manual_analysis(imp, file_name, output_folder): """perform analysis based on manually drawn cells""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T)") dialog.addMessage( "You can see what you've added so far if you check \"show all\" on the ROI manager" ) dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added") dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") elif dialog.wasOKed(): rois = roim.getRoisAsArray() roim.reset() roim.close() out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats return None
def showGui(par, title): """Updated version discriminates between string and numeric outputs to treat them accordingly""" numflags = {} gd = NonBlockingGenericDialog(title) s_keys = sorted(par.keys()) for nm in s_keys: if isinstance(par[nm], (int, float, long)): gd.addNumericField(nm, par[nm], 1) numflags[nm] = True else: gd.addStringField(nm, par[nm]) numflags[nm] = False gd.setOKLabel("Go on!") gd.setCancelLabel("Recompute..") gd.centerDialog(False) gd.setLocation(50, 100) gd.showDialog() if gd.wasCanceled(): rep = True else: rep = False for nm in s_keys: if numflags[nm]: par[nm] = gd.getNextNumber() else: par[nm] = gd.getNextString().encode("ascii", "replace") return par, rep
IJ.run("Draw","stack") numSlices = theImage.getNSlices() * theImage.getNChannels() * theImage.getNFrames() for zslice in range(1,numSlices+1): theImage.setSliceWithoutUpdate(zslice) ip = theImage.getProcessor() ip.setColor(255*255) for i in range(0,len(colCenters)): for j in range(0,len(rowCenters)): theString = str(int(j*xtiles+i+1)) ip.drawString(theString,int(colCenters[i]),int(rowCenters[j])) theImage.updateAndDraw() theImage.setSlice(visSlice) ### Sets up main interface for visualization ##### gd = NonBlockingGenericDialog("Explore full resolution...") gd.addMessage("Select ROI for visualization at full resolution") gd.showDialog() doContinue = gd.wasOKed() while (doContinue): roi = theImage.getRoi() boundRect = roi.getBounds() xmin = boundRect.getX() xmax = xmin + boundRect.getWidth() ymin = boundRect.getY() ymax = ymin + boundRect.getHeight() xs = find_tile_range(xmin,xmax,colStarts) ys = find_tile_range(ymin,ymax,rowStarts) tiles = make_tile_series(xs,ys,xtiles,ytiles) print tiles
def apply_thresh_overlay(overlay): ''' Clear outside rois in overlay ''' # --- Dialog ----------------------------------- wlist = WindowManager.getImageTitles() gd = NonBlockingGenericDialog('Apply Mask to') gd.setCancelLabel('Exit') gd.addChoice('Select Movie', wlist, wlist[0]) gd.addCheckbox('Duplicate', True) gd.showDialog() # dialog is open if gd.wasCanceled(): return False sel_win = gd.getNextChoice() do_duplicate = gd.getNextBoolean() # --- Dialog End ------------------------------ win_name = IJ.selectWindow(sel_win) movie = IJ.getImage() movie = slices_to_frames(movie) C = movie.getC() S = movie.getSlice() if do_duplicate: IJ.log('duplicating ' + movie.shortTitle) movie = movie.duplicate() NFrames = movie.getNFrames() if overlay.size() != NFrames: # one roi for each frame! display_msg( 'Mask count mismatch!', 'Mask count mismatch!\nGot ' + str(Nrois) + ' masks and ' + str(NFrames) + ' frames.. !') for frame in range(1, NFrames + 1): movie.setPosition(C, S, frame) mask_roi = overlay.get(frame - 1) ip = movie.getProcessor() ip.setValue(0) ip.setRoi(mask_roi) ip.fillOutside(mask_roi) movie.show() return True
from ij import ImageStack from ij import ImagePlus theImage = IJ.getImage() sourceImages = [] if theImage.getNChannels() == 1: IJ.run("8-bit") sourceImages.append(theImage) else: sourceImages = ChannelSplitter.split(theImage) sourceNames = [] for im in sourceImages: im.show() sourceNames.append(im.getTitle()) gd0 = NonBlockingGenericDialog("Select source image...") gd0.addChoice("Source image",sourceNames,sourceNames[0]) gd0.showDialog() if (gd0.wasOKed()): chosenImage = gd0.getNextChoice() theImage = WindowManager.getImage(chosenImage) IJ.selectWindow(chosenImage) else: theImage = sourceImages[0] IJ.selectWindow(sourceNames[0]) gd = NonBlockingGenericDialog("Set slice params...") gd.addNumericField("Slice start:",1,0) gd.addNumericField("Slice end:",theImage.getNSlices(),0) gd.showDialog()
def __mainsettings(self) : # options : #We ask if the user wants to import cells from .cell files # we track the cells in a stack that the user has to choose. def outputpath(event) : self.__pathdir=IJ.getDirectory("image") self.__pathdir=IJ.getDirectory("") self.__text.setText(self.__pathdir) panel0=Panel() pathbutton=Button("Select output path", actionPerformed = outputpath) #pathbutton.actionPerformed = outputpath self.__text = TextField(self.__pathdir) panel0.add(pathbutton) panel0.add(self.__text) firstgd=NonBlockingGenericDialog("First choices") firstgd.addMessage("------------------ WELCOME ----------------------") firstgd.addMessage("") firstgd.addMessage("Please fill the following options") firstgd.addMessage("") choices=["Already opened images", "Files from hard disk"] firstgd.addChoice("Images source : ", choices, choices[0]) # 1 choice firstgd.addCheckbox("Run in batch mode ?", False) # 2 batch firstgd.addMessage("") firstgd.addCheckbox("Import a set of cells from hardisk ?", self.__optionImport) # 3 import firstgd.addMessage("") firstgd.addNumericField("Size factor (binning)", 2, 0) # 4 number firstgd.addPanel(panel0) firstgd.showDialog() #self.__optionImages=firstgd.getNextBoolean() choice=firstgd.getNextChoiceIndex() # 1 choice self.__batch = firstgd.getNextBoolean() # 2 batch self.__optionImport=firstgd.getNextBoolean() # 3 import self.__binning = firstgd.getNextNumber() # 4 number if choice==0 : self.__optionImages=True else : self.__optionImages=False if firstgd.wasCanceled() : return False #IJ.showMessage("Select a working directory to save results") #self.__pathdir=IJ.getDirectory("image") #self.__pathdir=IJ.getDirectory("") #self.__pathdir=self.__pathdir+imp.getShortTitle()+os.path.sep+time.strftime('%d-%m-%y_%Hh%Mm%Ss',time.localtime())+os.path.sep if self.__pathdir is not None : return True else : return False
from ij import IJ from ij.gui import NonBlockingGenericDialog from ij import ImageStack from ij.gui import WaitForUserDialog from ij import ImagePlus from ij.process import ImageProcessor theImage = IJ.getImage() gd = NonBlockingGenericDialog("Set slice params...") gd.addNumericField("Slice start:",1,0) gd.addNumericField("Slice end:",theImage.getNSlices(),0) gd.showDialog() if (gd.wasOKed()): startSlice = gd.getNextNumber() endSlice = gd.getNextNumber() width = theImage.getWidth() height = theImage.getHeight() newStack = ImageStack(width,height) t_line = 240 for i in range(startSlice,endSlice+1): theImage.setSlice(i) waiter = WaitForUserDialog("Set ROI","Set ROI for thresholding region") waiter.show() roi = theImage.getRoi() newip = theImage.getProcessor().duplicate() newip.setColor(0) newip.fillOutside(roi) newip.snapshot()
import os, sys from ij import IJ, ImagePlus, ImageStack from ij.io import DirectoryChooser from ij.measure import Measurements from ij.gui import NonBlockingGenericDialog from ij.gui import WaitForUserDialog # Get input and output directories dc = DirectoryChooser("Choose an input directory") inputDirectory = dc.getDirectory() dc = DirectoryChooser("Choose an output directory") outputDirectory = dc.getDirectory() gd = NonBlockingGenericDialog("Channel Options") gd.addStringField("Enter your name: ", "") gd.showDialog() name = gd.getNextString() if gd.wasCanceled(): print "User canceled dialog!" # Finds all the subfolders in the main directory with open(outputDirectory + "manual_counts_" + name + ".csv", "w") as log: subfolders = [] # for subfolder in os.listdir(inputDirectory): # if os.path.isdir(inputDirectory + subfolder):
gw.run(dictRois.keys(), pathdir) gw.show() gw.setSelected(dictRois.keys()) while not gw.oked and gw.isShowing() : gw.setLabel("Validate selection with OK !!") listcellname = list(gw.getSelected()) gw.resetok() gw.setLabel("...") gw.hide() rm.runCommand("reset") if imp.getOverlay() is not None : imp.getOverlay().clear() overlay=Overlay() imp.setOverlay(overlay) gd0=NonBlockingGenericDialog("settings") gd0.addCheckbox("Show the overlay during the process ? (slow option)", False) gd0.addNumericField("Minimal Lifetime : ",10,0) gd0.addNumericField("Minimal distance to reversion : ",4,0) gd0.addNumericField("Sub sampling ? : ",1,0) gd0.addNumericField("Radius for fluo tracking ? : ",8,0) gd0.showDialog() isShow = gd0.getNextBoolean() minLife = gd0.getNextNumber() mind = gd0.getNextNumber() subs = gd0.getNextNumber() rayon = gd0.getNextNumber() if gd0.wasCanceled() : isShow = True
def MyWaitForUser(title, message): """non-modal dialog with option to cancel the analysis""" dialog = NonBlockingGenericDialog(title) dialog.setCancelLabel("Cancel analysis") if type(message) is list: for line in message: dialog.addMessage(line) else: dialog.addMessage(message) dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") return
def perform_user_qc(in_imp, edges, alt_edges, fixed_anchors_list, params): """allow the user to intervene to fix erroneously identified membrane edges""" n_frames = in_imp.getNFrames(); n_channels = in_imp.getNChannels(); output_folder = params.output_path; current_edges = edges; rgbstack = ImageStack(in_imp.getWidth(), in_imp.getHeight()); if n_frames > 1: for tidx in range(n_frames): in_imp.setT(tidx+1); ip = in_imp.getProcessor(); rgbip = ip.convertToRGB(); rgbstack.addSlice(rgbip); else: for cidx in range(n_channels): in_imp.setC(cidx+1); ip = in_imp.getProcessor(); rgbip = ip.convertToRGB(); rgbstack.addSlice(rgbip); imp = ImagePlus(("RGB " + in_imp.getTitle()), rgbstack); IJ.run("Colors...", "foreground=red background=white selection=yellow"); for tidx in range(imp.getNSlices()): imp.setSlice(tidx+1); for anchor in params.manual_anchor_positions: imp.setRoi(PointRoi(anchor[0], anchor[1])); IJ.run(imp, "Draw", "slice"); imp.show(); autoset_zoom(imp); imp.setPosition(1); imp.setRoi(current_edges[0]); if n_frames > 1: listener = UpdateRoiImageListener(current_edges); imp.addImageListener(listener); IJ.setTool("freeline"); do_flip = True; while do_flip: dialog = NonBlockingGenericDialog("User quality control"); dialog.enableYesNoCancel("Continue", "Flip all edges"); dialog.setCancelLabel("Cancel analysis"); dialog.addMessage("Please redraw the membrane edges as necessary, \n" + "making sure to draw beyond anchor points at either end...\n" + "Click OK when done. "); p = Panel(); but = Button("Flip this edge"); al = Listener(edges, alt_edges, imp); but.addActionListener(al); p.add(but); dialog.addPanel(p); dialog.showDialog(); if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled"); elif dialog.wasOKed(): do_flip = False; else: print("flip edges"); do_flip = True; if n_frames > 1: imp.removeImageListener(listener); current_edges = alt_edges if (current_edges == edges) else edges; imp.setPosition(1); imp.setRoi(current_edges[0]); if n_frames > 1: listener = UpdateRoiImageListener(current_edges); imp.addImageListener(listener); last_roi = imp.getRoi(); if n_frames > 1: qcd_edges = listener.getRoiList(); if imp.getNFrames() > imp.getNSlices(): qcd_edges[imp.getT() - 1] = last_roi; else: qcd_edges[imp.getZ() - 1] = last_roi; imp.removeImageListener(listener); else: qcd_edges = [last_roi]; mbio.save_qcd_edges2(qcd_edges, output_folder); # next four lines are a quick and dirty hack... if n_frames > 1: nframes = imp.getNFrames() if imp.getNFrames()>imp.getNSlices() else imp.getNSlices(); else: nframes = n_frames; for fridx in range(0, nframes): if (qcd_edges[fridx].getType()==Roi.FREELINE) or (qcd_edges[fridx].getType()==Roi.POLYLINE): if (fridx == 0) or params.constrain_anchors: anchors = params.manual_anchor_positions; else: anchors = fixed_anchors_list[fridx - 1]; fixed_anchors = mb.fix_anchors_to_membrane(anchors, qcd_edges[fridx], params); fixed_anchors = mb.order_anchors(fixed_anchors, params.manual_anchor_midpoint); fixed_anchors_list[fridx] = fixed_anchors; poly = qcd_edges[fridx].getInterpolatedPolygon(0.25, False); polypoints = [(x,y) for x,y in zip(poly.xpoints, poly.ypoints)]; idx = [polypoints.index(fixed_anchors[0]), polypoints.index(fixed_anchors[1])]; idx.sort(); polypoints = polypoints[idx[0]:idx[1]]; newedge = PolygonRoi([x for (x,y) in polypoints], [y for (x,y) in polypoints], Roi.POLYLINE); newedge = mb.check_edge_order(anchors, newedge); imp.setPosition(fridx + 1); imp.setRoi(newedge); IJ.run(imp, "Interpolate", "interval=1.0 smooth adjust"); IJ.run(imp, "Fit Spline", ""); qcd_edges[fridx] = imp.getRoi(); mbio.save_qcd_edges2(qcd_edges, output_folder); imp.changes = False; imp.close(); return qcd_edges, fixed_anchors_list;
def __settings(self, imgName, flag) : """ Allows the user to choose several parameters for the tracking. """ #fenetre=JFrame("Import") #optionpane=JOptionPane("Do you want to import previous preferences ?",JOptionPane.QUESTION_MESSAGE ,JOptionPane.YES_NO_OPTION ) #optionpane.setVisible(True) #dialog = optionpane.createDialog(fenetre, "Import") #dialog.show() #choice = optionpane.getValue() #if choice==JOptionPane.YES_OPTION : self.__ImportPref() image=self.__dictImages[imgName] 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 #self.__macropath=IJ.getDirectory("macros") #self.__macropath=IJ.getDirectory("") #self.__text.setText(self.__macropath) panel0=Panel() pathbutton=Button("Select macro file", actionPerformed = outputpath) #pathbutton.actionPerformed = outputpath self.__text = TextField(self.__macropath) panel0.add(pathbutton) panel0.add(self.__text) # -------- start batch mode --------- # if self.__batch : pass #self.__ImportPref(flag) image.hide() else : image.show() IJ.selectWindow(image.getID()) gd0=NonBlockingGenericDialog("Settings") gd0.setFont(Font("Courrier", 1, 10)) gd0.addMessage("---------------- PRE-PROCESSING OPTIONS -------------------") gd0.addCheckbox("Substract Background",self.__subback) #box 1 subback gd0.addNumericField("Radius",self.__radius,0) gd0.addCheckbox("Run a macro for pre processing",self.__runmacro) #box 2 runmacro gd0.addPanel(panel0) gd0.addMessage("-------------------------------------------") gd0.addMessage("Tracking parameters") gd0.addMessage("Coeffs modulate de weight of each parameter") gd0.addMessage("Max delta set the maximum allowed change in absolute units") gd0.addMessage(" ") gd0.addNumericField("Coeff Area : ",self.__distparam[0],0) gd0.addNumericField("Max deltaArea : ",self.__distparam[1],self.__nbdigits,6,"x times") gd0.addNumericField("Coeff Angle : ",self.__distparam[2],0) gd0.addNumericField("Max deltaAngle : ",self.__distparam[3],self.__nbdigits,6,"degrees") gd0.addNumericField("Coeff Feret : ",self.__distparam[4],0) gd0.addNumericField("Max deltaFeret : ",self.__distparam[5],self.__nbdigits,6,"x times") gd0.addNumericField("Coeff PositionX : ",self.__distparam[6],0) gd0.addNumericField("Max deltaPositionX : ",self.__distparam[7],self.__nbdigits,6,"pixels") gd0.addNumericField("Coeff PositionY : ",self.__distparam[8],0) gd0.addNumericField("Max deltaPositionY : ",self.__distparam[9],self.__nbdigits,6,"pixels") gd0.addMessage("-------------------------------------------") automethods=AutoThresholder.getMethods() gd0.addCheckbox("Manual Threshold",self.__manthresh) #box 3 manthresh gd0.addChoice("Threshol Method : ",automethods,self.__thresMethod) gd0.addMessage("-------------------------------------------") #gd0.addCheckbox("Symmetry Around 0-180",self.__optionAngle) #gd0.addMessage("-------------------------------------------") #gd0.addCheckbox("Save cell files", self.__optionSave) #gd0.addMessage("-------------------------------------------") gd0.addCheckbox("Track new cells", self.__optionNewCells) #box 4 newcells gd0.addMessage("-------------------------------------------") gd0.addCheckbox("Generate time list with follow time lapse interval ?", self.__optionTimelapse) #box 5 timelapse gd0.addNumericField("Estimated time lapse : ",self.__timelapse,self.__nbdigits,6,"seconds") #gd0.hideCancelButton() gd0.showDialog() if gd0.wasCanceled() : return False #chosenstack=gd0.getNextChoice() #self.__img=WindowManager.getImage(chosenstack) self.__subback=gd0.getNextBoolean() #box 1 subback self.__radius=gd0.getNextNumber() self.__runmacro=gd0.getNextBoolean() #box 2 runmacro for i in range(10) : self.__distparam[i]=gd0.getNextNumber() #self.__distmethod=gd0.getNextChoice() self.__manthresh=gd0.getNextBoolean() #box 3 manthresh self.__thresMethod=gd0.getNextChoice() #self.__optionAngle=gd0.getNextBoolean() #self.__optionSave=gd0.getNextBoolean() self.__optionNewCells=gd0.getNextBoolean() #box 4 newcells self.__optionTimelapse=gd0.getNextBoolean() #box 5 timelapse self.__timelapse=int(gd0.getNextNumber()) # -------- start end batch mode --------- # if self.__optionTimelapse : self.__dictTimeStack[imgName]=range(0,image.getImageStackSize()*self.__timelapse, self.__timelapse) if not self.__optionTimelapse and self.__source=="image" : self.__dictTimeStack[imgName]=range(0,image.getImageStackSize()) #if option_import==True : # temparray= #else : temparray=self.__calRois("image1", 1) #imp=self.__dictImages["image1"] if self.__manthresh : ip=image.getProcessor() self.__maxthr=ip.getMaxThreshold() self.__minthr=ip.getMinThreshold() temparray=self.__calRois(image, 1) self.__rr=RangeRois(temparray, image) if (not self.__batch) : image.show() self.__params=self.__rr.showSettingsDialog().values() if self.__batch : image.hide() return True
def crop_review(): """handle UI for reviewing cropping""" print("doing crop review..."); dialog = NonBlockingGenericDialog("Review cropping") dialog.enableYesNoCancel("Keep this crop", "Revert to uncropped image"); dialog.setCancelLabel("Cancel analysis"); dialog.addMessage("Please check whether this cropping is as expected, \n" + "and choose whether to press on or revert to using the \n" + "full, uncropped image. "); dialog.showDialog(); if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled"); elif dialog.wasOKed(): keep_cropping = True; else: keep_cropping = False; return keep_cropping;
from ij import IJ from ij.gui import NonBlockingGenericDialog from ij import WindowManager theImage = IJ.getImage() gd = NonBlockingGenericDialog("Shine Light") gd.addMessage("Select an ROI to shine light") gd.showDialog() doClose = False continueProg = True if (gd.wasCanceled()): continueProg = False while (continueProg): if (doClose): litImage.close() nslices = theImage.getNSlices() params = "title=dupped duplicate range=1-" + str(nslices) IJ.run("Duplicate...", params) litImage = WindowManager.getImage("dupped") params = "saturated=0.4 normalize process_all" IJ.run(litImage,"Enhance Contrast...", params) gd = NonBlockingGenericDialog("Shine Light") gd.addMessage("Select an ROI to shine light") gd.showDialog() if (gd.wasCanceled()): continueProg = False doClose = True
def qc_background_regions(intensity_imp, bg_rois): """allow the user to view and correct automatically-determined background regions""" imp = Duplicator().run(intensity_imp); imp.setTitle("Background region QC"); imp.show(); imp.setPosition(1); autoset_zoom(imp); imp.setRoi(bg_rois[0]); IJ.setTool("freehand"); notOK = True; while notOK: listener = UpdateRoiImageListener(bg_rois, is_area=True); imp.addImageListener(listener); dialog = NonBlockingGenericDialog("Background region quality control"); dialog.enableYesNoCancel("Continue", "Use this region for all t"); dialog.setCancelLabel("Cancel analysis"); dialog.addMessage("Please redraw background regions as necessary...") dialog.showDialog(); if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled"); elif not(dialog.wasOKed()): this_roi = imp.getRoi(); bg_rois = [this_roi for _ in listener.getRoiList()]; imp.removeImageListener(listener); else: last_roi = imp.getRoi(); qcd_bg_rois = listener.getRoiList(); if imp.getNFrames() > imp.getNSlices(): qcd_bg_rois[imp.getT() - 1] = last_roi; else: qcd_bg_rois[imp.getZ() - 1] = last_roi; notOK = False; imp.removeImageListener(listener); imp.changes = False; imp.close(); return qcd_bg_rois;
def showSettingsDialog(self): if self.__image.getOverlay() is not None : self.__image.getOverlay().clear() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() #rm.runCommand("Deselect") #for i in range(rm.getCount()) : # rm.select(i) # rm.runCommand("Set Color", "0000FF", 2) IJ.resetThreshold(self.__image) rm.runCommand("Show All") self.__ranges.clear() #areas, means, majors, minors=[],[],[],[] #for roi in self.__roisArray: # m=Morph(self.__image, roi) # areas.append(m.Area) # means.append(m.Mean) # majors.append(m.Major) # minors.append(m.Minor) #maxarea=max(areas)*1000 #maxint=max(means)*10 #maxline=max(majors)*100 #maxminline=max(minors)*100 #minline=min(minors) #namemeasures=["Area", "Mean", "Angle", "Major", "Minor", "Solidity", "AR", "Round", "Circ"] #maxmeasures=[maxarea, maxint, 180*10, maxline, maxminline, 1*1000, (maxline/minline), 1*1000, 1*1000] #set1000=Set(["Solidity", "Round", "Circ"]) #set10=Set(["Angle"]) def buttonPressed(event): temprois=self.getIncludeRois() for roi in temprois: m=Morph(self.__image, roi) IJ.log("----------------------------------") IJ.log(roi.getName()) for r in self.__ranges.values(): IJ.log(r[0]+" min= "+str(r[1])+" < val="+str(m.__getattribute__(r[0]))+" < max= "+str(r[2])) IJ.run(self.__image, "Remove Overlay", "") o=Overlay() for roi in temprois: o.addElement(roi) self.__image.killRoi() self.__image.setOverlay(o) self.__image.updateAndDraw() def updatepressed(event): self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.run("Threshold...") IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #for i in range(rm.getCount()) : # rm.select(i) # rm.runCommand("Set Color", "0000FF", 2) IJ.resetThreshold(self.__image) rt.show("tempRT") areas=rt.getColumn(ResultsTable.AREA) means=rt.getColumn(ResultsTable.MEAN) majors=rt.getColumn(ResultsTable.MAJOR) minors=rt.getColumn(ResultsTable.MINOR) #print 0 if self.__slidersDict["Area_max"].getMaximum() < int(max(areas)+1): # print 1 self.__slidersDict["Area_max"].setMaximum(int(max(areas))+1) if self.__slidersDict["Area_min"].getMaximum() < int(max(areas)+1): # print 2 self.__slidersDict["Area_min"].setMaximum(int(max(areas))+1) if self.__slidersDict["Mean_max"].getMaximum() < int(max(means)+1): # print 3 self.__slidersDict["Mean_max"].setMaximum(int(max(means))+1) if self.__slidersDict["Mean_min"].getMaximum() < int(max(means)+1): # print 4 self.__slidersDict["Mean_min"].setMaximum(int(max(means))+1) if self.__slidersDict["Major_max"].getMaximum() < int(max(majors)): # print 5 self.__slidersDict["Major_max"].setMaximum(int(max(majors))+1) if self.__slidersDict["Major_min"].getMaximum() < int(max(majors)+1): # print 6 self.__slidersDict["Major_min"].setMaximum(int(max(majors))+1) if self.__slidersDict["Minor_max"].getMaximum() < int(max(minors)+1): # print 7 self.__slidersDict["Minor_max"].setMaximum(int(max(minors))+1) if self.__slidersDict["Minor_min"].getMaximum() < int(max(minors)+1): # print 8 self.__slidersDict["Minor_min"].setMaximum(int(max(minors))+1) if self.__slidersDict["AR_max"].getMaximum() < int((max(majors)+1)/min(minors)+1): # print 9 self.__slidersDict["AR_max"].setMaximum(int((max(majors)+1)/(min(minors)))) if self.__slidersDict["AR_min"].getMaximum() < int((max(majors)+1)/min(minors)): # print 10 self.__slidersDict["AR_min"].setMaximum(int((max(majors)+1)/(min(minors)))) #print 11 for sb in self.__slidersDict.values(): sb.repaint() #rm.runCommand("reset") #temprois=self.getIncludeRois() #IJ.run(self.__image, "Remove Overlay", "") #o=Overlay() #for roi in temprois: # o.addElement(roi) #self.__image.killRoi() #self.__image.setOverlay(o) self.__image.updateAndDraw() def resetpressed(event): self.__ranges.clear() self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #rm.runCommand("Show All") #rm.runCommand("Select All") #rm.runCommand("Set Color", "blue") IJ.resetThreshold(self.__image) keys=self.__slidersDict.keys() for k in keys: if k.endswith("min"): self.__slidersDict[k].setValue(0) self.__slidersDict[k].repaint() else: self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum()) self.__slidersDict[k].repaint() def valueChanged(event): name=event.getSource().getName() names=name.split("_") factor=1 if names[0] in self.__set1000: factor=0.001 if names[0] in self.__set10:factor=0.1 value=event.getSource().getValue()*factor if names[1]=="min": self.__ranges[names[0]]=(names[0], value, self.__slidersDict[names[0]+"_max"].getValue()*factor, self.__boxesDict[names[0]].getState()) #self.__ranges[names[0]]=(names[0], value, self.__slidersDict[names[0]+"_max"].getValue()*factor) else: self.__ranges[names[0]]=(names[0], self.__slidersDict[names[0]+"_min"].getValue()*factor, value, self.__boxesDict[names[0]].getState()) #self.__ranges[names[0]]=(names[0], self.__slidersDict[names[0]+"_min"].getValue()*factor, value) temprois=self.getIncludeRois() IJ.run(self.__image, "Remove Overlay", "") o=Overlay() for roi in temprois: o.addElement(roi) self.__image.killRoi() self.__image.setOverlay(o) self.__image.updateAndDraw() def selectAll(event): name=event.getSource().getLabel() names=name.split("_") factor=1 if names[0] in self.__set1000: factor=0.001 if names[0] in self.__set10:factor=0.1 name=event.getSource().getLabel() names=name.split("_") value=event.getSource().getState() self.__ranges[names[0]]=(names[0], self.__slidersDict[names[0]+"_min"].getValue()*factor, self.__slidersDict[names[0]+"_max"].getValue()*factor, value) gd0=NonBlockingGenericDialog("settings") gd0.setResizable(True) gd0.setFont(Font("Courrier", 1, 8)) count=0 self.__slidersDict={} self.__boxesDict={} self.__boxesDict.clear() self.__slidersDict.clear() for i in range(len(self.__namemeasures)): gd0.setInsets(-10,0,0) gd0.addSlider("Min"+self.__namemeasures[i], 0, self.__maxmeasures[i], 0) gd0.getSliders().get(count).adjustmentValueChanged = valueChanged gd0.getSliders().get(count).setName(self.__namemeasures[i]+"_min") self.__slidersDict[self.__namemeasures[i]+"_min"]=gd0.getSliders().get(count) gd0.addSlider("Max"+self.__namemeasures[i], 0, self.__maxmeasures[i], self.__maxmeasures[i]) gd0.getSliders().get(count+1).adjustmentValueChanged = valueChanged gd0.getSliders().get(count+1).setName(self.__namemeasures[i]+"_max") self.__slidersDict[self.__namemeasures[i]+"_max"]=gd0.getSliders().get(count+1) gd0.addCheckbox("all", True) gd0.getCheckboxes().get(i).itemStateChanged = selectAll gd0.getCheckboxes().get(i).setLabel(self.__namemeasures[i]+"_all") self.__boxesDict[self.__namemeasures[i]]=gd0.getCheckboxes().get(i) gd0.setInsets(-10,0,0) #gd0.addMessage("...........................................................................") count=count+2 panel0=Panel() #trybutton=Button("Try") #trybutton.setActionCommand("DrawOverlay") #trybutton.actionPerformed = buttonPressed #updatebutton=Button("Update") #updatebutton.setActionCommand("Update") #updatebutton.actionPerformed = updatepressed #resetbutton=Button("Reset") #resetbutton.setActionCommand("Reset") #resetbutton.actionPerformed = resetpressed #panel0.add(trybutton) #panel0.add(updatebutton) #panel0.add(resetbutton) #gd0.addPanel(panel0) gd0.setResizable(True) gd0.showDialog() #self.__image.setSlice(self.__firstslice) #self.__image.updateAndDraw() if gd0.wasOKed(): #for key in self.__ranges.keys(): IJ.log("Measure : "+str(self.__ranges[key][0])+" min = "+str(self.__ranges[key][1])+" max = "+str(self.__ranges[key][2])) return self.__ranges
for j in range(len(objectDB[i])): rescaledTup = [objectDB[i][j][27]/scale_info[0],objectDB[i][j][28]/scale_info[0],objectDB[i][j][29],objectDB[i][j][30]/scale_info[0],objectDB[i][j][31]/scale_info[0],objectDB[i][j][32]] objectDB[i][j] = objectDB[i][j] + rescaledTup ## Draws the bounding boxes in the precomputed way virginImage = IJ.getImage() theImage = virginImage.duplicate() virginImage.hide() boxImages = [] for i in range(len(objectDB)): boxImages.append(draw_bounding_boxes(objectDB[i],"image_"+str(i+1),virginImage)) virginImage.show() ## Sets up main GUI interface for examining found objects ngd = NonBlockingGenericDialog("Control box") ngd.addCheckbox("Contained_objects",False) ngd.addCheckbox("Duplicated_objects",False) ngd.addCheckbox("Restitched_objects",False) ngd.addCheckbox("Unique_objects",False) boxes = ngd.getCheckboxes() checkboxObjects = [] for i in range(boxes.size()): checkboxObjects.append(boxes.elementAt(i)) for i in range(len(checkboxObjects)): checkboxObjects[i].addItemListener(CustomCheckboxListener(objectDB,virginImage,boxImages,boxes)) ngd.setCancelLabel("Exit") ngd.setOKLabel("Inspect") ngd.showDialog() if (ngd.wasCanceled()): titles = WindowManager.getImageTitles()
(retval[3], retval[3])) valplot.add( "line", (icalibration.getX(retval[2] + 1), icalibration.getX(retval[1] + 1)), (retval[4], retval[4])) valplot.add( "line", (icalibration.getX(retval[1] + 1), icalibration.getX(retval[1] + 1)), (retval[3], retval[4])) valplot.add( "line", (icalibration.getX(retval[2] + 1), icalibration.getX(retval[2] + 1)), (retval[3], retval[4])) valplot.show() valplot.update() proceed = NonBlockingGenericDialog("Accept Or Reject?") proceed.addCheckbox("Uncheck To Reject", True) proceed.showDialog() proceed = proceed.getNextBoolean() WindowManager.getWindow("Angle-Distance Correlation Values").close() WindowManager.getImage("pixarr").close() WindowManager.getImage("DUP_" + title).close() if proceed: roi = analyte.getRoi() roiStats = roi.getStatistics() ferets = roi.getFeretValues() rt = WindowManager.getWindow( "Cardiomyocyte Results").getTextPanel().getOrCreateResultsTable() a = rt.getCounter() rt.setValue("Correlation Score", a, retval[0]) rt.setValue("Sarcomere Length", a, icalibration.getX(retval[1] + 1))
from ij.io import SaveDialog class CounterPoint: def __init__(self,x,y,clonenum): self.x = x self.y = y self.clonenum = clonenum theImage = IJ.getImage() stayinloop = True cloneNum = 1 pointList = [] while (stayinloop): gd = NonBlockingGenericDialog("Clone counter...") gd.addNumericField("Clone:",cloneNum,0) gd.setOKLabel("Finalize clone") gd.setCancelLabel("Quit") gd.showDialog() if (gd.wasOKed()): roi = theImage.getRoi() if (not roi is None): cloneNum = int(gd.getNextNumber()) polygon = roi.getFloatPolygon() for i in range(polygon.npoints): pointList.append(CounterPoint(polygon.xpoints[i],polygon.ypoints[i],cloneNum)) IJ.run("Draw","stack") theImage.deleteRoi() cloneNum = cloneNum + 1
else: IJ.run("Bio-Formats Importer", "open=" + parentLSMFilePath + "_tiles/tile_" + (containing_tiles_dict.keys())[0] + ".ome.tif color_mode=Default view=Hyperstack stack_order=XYCZT") IJ.log("Opened tile " + str((containing_tiles_dict.keys())[0])) subupcoords_dict = normalize_coords_in_dict(dict(("tile_"+k,upscaled_coords["tile_"+k]) for k in containing_tiles_dict.keys())) activeImage = draw_roi_on_full_res_tile(containing_tiles_dict,subupcoords_dict) if (hadStitched): activeImage.copyScale(calibImage) calib = calibImage.getCalibration() calibImage.close() activeImage.updateAndRepaintWindow() else: calib = activeImage.getCalibration() ## Runs interface that allows to correct for bleedthrough and refraction if activeImage is not None: gd = NonBlockingGenericDialog("Select channel to operate on...") gd.addChoice("Select_channel:",["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"Channel 1") gd.addChoice("Bleeding_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None") gd.addChoice("Refraction_reference_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None") gd.showDialog() if (gd.wasOKed()): channelImages = ChannelSplitter.split(activeImage) channel = gd.getNextChoiceIndex()+1 bleedingC = gd.getNextChoiceIndex() refractRefC = gd.getNextChoiceIndex() if (bleedingC > 0): params = ("bleeding_channel=" + str(bleedingC) + " bloodied_channel=" + str(channel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) dataImage = WindowManager.getImage("Corrected_ch" + str(channel)) if (refractRefC > 0):
from ij import ImagePlus from ij.process import ByteProcessor from ij.plugin import ImageCalculator theImage = IJ.getImage() if theImage.getNSlices() > 1: iStack = ImageStack(theImage.getWidth(),theImage.getHeight()) for sl in range(theImage.getNSlices()): sliceIp = ByteProcessor(theImage.getWidth(),theImage.getHeight()) iStack.addSlice(sliceIp) maskImage = ImagePlus("maskImage",iStack) ## Gets the user-defined ROIs; user can add in any order to image sliceList = [] gd = NonBlockingGenericDialog("Select freehand ROI, then hit OK when ready to store") gd.showDialog() while gd.wasOKed(): roi = theImage.getRoi() if roi is not None: currSlice = theImage.getCurrentSlice() maskImage.setSlice(currSlice) currIp = maskImage.getProcessor() currIp.setRoi(roi) currIp.setColor(255) currIp.fill(currIp.getMask()) sliceList.append(currSlice) theImage.setSlice(currSlice+1) gd = NonBlockingGenericDialog("Select freehand ROI, then hit OK when ready to store") gd.showDialog()
p = re.compile(r'X Tiles: (\d+)') m = p.search(metadata) if m is None: xtiles = 0 else: xtiles = int(m.group(1)) p = re.compile(r'Y Tiles: (\d+)') m = p.search(metadata) if m is None: ytiles = 0 else: ytiles = int(m.group(1)) nTiles = xtiles*ytiles ## Opens the options dialog box gd = NonBlockingGenericDialog("Select channel...") gd.addChoice("Analysis_channel",["Channel "+str(i) for i in range(1,nChannels+1)],"Channel 1") gd.addChoice("Bleeding_channel",["Channel "+str(i) for i in range(nChannels+1)],"Channel 0") gd.addChoice("Refractive_reference_channel",["Channel "+str(i) for i in range(nChannels+1)],"Channel 0") gd.addNumericField("Intensity_threshold",128,0) gd.addNumericField("Size_threshold",100,0) gd.addChoice("Process_filter",["None","Min","Median"],"None") gd.addCheckbox("Operate_on_tile_subset",False) gd.addStringField("Which_tile_subset","1-4,9,11",12) gd.showDialog() ## Parses the information from the dialog box if (gd.wasOKed()): analysisChannel = gd.getNextChoiceIndex()+1 bleedingChannel = gd.getNextChoiceIndex() refChannel = gd.getNextChoiceIndex()
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)