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
Exemplo n.º 2
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()
Exemplo n.º 4
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
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:
		stayinloop = False
		
		## 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()
			p = re.compile(r'^Result')
			for title in titles:
				m = p.search(title)
				if m is not None:
					theImage = WindowManager.getImage(title)
					theImage.close()

			virginImage.show()
			for img in boxImages:
				img.close()
		else:
			titles = WindowManager.getImageTitles()
		roi = theImage.getRoi()
		newip = theImage.getProcessor().duplicate()
		newip.setColor(0)
		newip.fillOutside(roi)
		newip.snapshot()
		newip.setThreshold(0,t_line,ImageProcessor.BLACK_AND_WHITE_LUT)
		newImage = ImagePlus("toggler",newip)
		newImage.show()

		doSameSlice = True
		while (doSameSlice):
			accept_waiter = NonBlockingGenericDialog("Thresholding...")
			accept_waiter.addNumericField("Threshold:",t_line,0)
			accept_waiter.setCancelLabel("Apply new threshold")
			accept_waiter.setOKLabel("Accept threshold")
			accept_waiter.showDialog()
			if (accept_waiter.wasCanceled()):
				newip.reset()
				newip.snapshot()
				t_line = accept_waiter.getNextNumber()
#				if (t_line > 10):
#					t_line = t_line - 5
#				else:
#					t_line = 5
				newip.setThreshold(0,t_line,ImageProcessor.BLACK_AND_WHITE_LUT)
				newImage.updateAndDraw()
			else:
				doSameSlice = False
				for i in range(newImage.getWidth()):
					for j in range(newImage.getHeight()):
Exemplo n.º 8
0
	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")
			waiter.addMessage("Pick 2D ROI")
			waiter.setOKLabel("Save and advance")
			waiter.setCancelLabel("Save")
			waiter.showDialog()

			if (waiter.wasOKed()):
				roi = theImage.getRoi()
				if (roi is None):
					doStaySlice = True
				else:
					bp.fill(roi)
					doStaySlice = False
			else:
				roi = theImage.getRoi()
				if (roi is None):
					doStaySlice = True
				else:
Exemplo n.º 9
0
    # 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

    if gd.wasCanceled():  # Cancel means 'exit'
Exemplo n.º 10
0
	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):
				xset = average(polygon.xpoints)
				IJ.setForegroundColor(255,255,0)
				IJ.run("Draw","stack")