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()
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 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)
Example #4
0
def MakeSubset(directory_load, directory_save, chl, frames, z_planes, loops,
               total, pat, title, imp2):
    subd = NonBlockingGenericDialog("Make subset")
    subd.addCheckbox("Duplicate only the current frames", False)
    subd.addCheckbox("Export XYTC of a subset of loops", False)

    subd.addSlider("Subset from loop number", 0, loops - 1, 0)
    subd.addSlider("Subset to loop number", 0, loops - 1, 0)
    subd.showDialog()

    slider_subd1 = subd.getSliders().get(0).getValue()
    slider_subd2 = subd.getSliders().get(1).getValue()
    checkbox_subd1 = subd.getNextBoolean()
    checkbox_subd2 = subd.getNextBoolean()

    if checkbox_subd1 == True:
        SliceNum = imp2.getCurrentSlice()
        FloorSlice50 = float(SliceNum) / frames
        S50 = (math.floor(FloorSlice50) * frames) + 1
        S100 = S50 + (frames - 1)
        print("Slice" + str(SliceNum) + "_FloorSlice_" + str(FloorSlice50) +
              "_frames_" + str(S50) + "-" + str(S100) + "")
        IJ.run(
            "Duplicate...", "title=Image_DUP duplicate range=" + str(S50) +
            "-" + str(S100) + "")
        impDup = WM.getImage("Image_DUP")
    if checkbox_subd2 == True:
        SubsetL(directory_load, directory_save, chl, frames, z_planes, loops,
                total, pat, title, slider_subd1, slider_subd2)
Example #5
0
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 repeat_measure():
    IJ.run("Select None")
    gd = NonBlockingGenericDialog("Redraw ROI?")
    gd.showDialog()
    if gd.wasOKed():
        selection(region)
    if gd.wasCanceled():
        exit_assay()
Example #7
0
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)
Example #8
0
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
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()
Example #10
0
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 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)
Example #12
0
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
Example #13
0
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
Example #14
0
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()
Example #15
0
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
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 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;
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")
Example #19
0
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 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;
Example #21
0
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):
    (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))
Example #23
0
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 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()
        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)
Example #26
0
            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')
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):
Example #28
0
            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"
Example #29
0
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_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;