def createLabelColorBar(): imp7 = ImagePlus("labelColorBar", ShortProcessor(180, 20)) ip7 = imp7.getProcessor() pix = ip7.getPixels() n_pixels = len(pix) # catch width w = imp7.getWidth() # create a ramp gradient from left to right for i in range(len(pix)): pix[i] = int((i % w) / 18) + 1 # adjust min and max ip7.setMinAndMax(0, 255) font = Font("SansSerif", Font.PLAIN, 12) overlay = Overlay() for i in range(len(pix)): roi = TextRoi(i * 18 + 2, 2, str(i + 1), font) roi.setStrokeColor(Color.black) overlay.add(roi) imp7.setOverlay(overlay) imp7.show() IJ.run("glasbey_on_dark") imp7 = imp7.flatten() return imp7
def overlay_corners(corners, L): ov = Overlay() for [x, y] in corners: rect = Roi(x, y, L, L) rect.setStrokeColor(Color.RED) rect.setLineWidth(40) ov.add(rect) return ov
def restoreRoi(self): overlay = Overlay() rois = [ r for ind, r in enumerate(self.newRois) if ind != self.outlineRoiInd ] for roi in rois: overlay.add(roi) self.impCrop.setOverlay(overlay)
def drawMinima(self): IJ.run("Remove Overlay", "") self.calculateSubtreeMinima() overlay = Overlay() for child in self.children: for spot in child.minima: roi = OvalRoi(spot.x - spot.radius, spot.y - spot.radius, 2 * spot.radius, 2 * spot.radius) overlay.add(roi) IJ.getImage().setOverlay(overlay)
def roiprocess_ov(imp, filename): """ !!! This is for testing purposes only. It is currently not used !!! """ ov = Overlay() rt = ov.measure(imp) # log.info('Size ResultTable: ' + str(rt.size())) # print('Size ResultTable: ', rt.size()) return None
def drawMinima(minima): rt = ResultsTable.getResultsTable() X = rt.getColumn(ResultsTable.X_CENTROID) Y = rt.getColumn(ResultsTable.Y_CENTROID) D = rt.getColumn(ResultsTable.FERET) overlay = Overlay() for minimum in minima: index = minima[minimum] r = float(D[index]) / 2 roi = OvalRoi(float(X[index])-r, float(Y[index])-r, float(D[index]), float(D[index])) overlay.add(roi) IJ.getImage().setOverlay(overlay)
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 convert_SNTpaths_to_roi(SNTpaths): ''' Converts a list of SNT_paths to an Array of imageJ1 rois. ''' roi_list = [] for SNTpath in SNTpaths: as_tree = Tree() as_tree.add(SNTpath) converter = RoiConverter(as_tree) overlay = Overlay() converter.convertPaths(overlay) roi = overlay.toArray()[0] roi_list.append(roi) return roi_list
def create_mask_selection(movie, sigma=0, thresh_method='Huang', threshold=None): ''' If threshold is *None* use selected AutoThreshold, otherwise use fixed *threshold* ''' C = movie.getC() S = movie.getSlice() NFrames = movie.getNFrames() maxThresh = 2**movie.getBitDepth() tts = ThresholdToSelection() ov = Overlay() # to save the rois for frame in range(1, NFrames + 1): movie.setPosition(C, S, frame) ip = movie.getProcessor().duplicate() # imp = ImagePlus('Blurred', ip) if sigma != 0: ip.blurGaussian(sigma) # manual thresholding if threshold: ip.setThreshold(threshold, maxThresh, 0) # no LUT update # automatic thresholding else: ip.setAutoThreshold(thresh_method, True, False) tts.setup("", movie) shape_roi = tts.convert(ip) # only one connected roi present if type(shape_roi) == ij.gui.PolygonRoi: mask_roi = shape_roi else: # for disconnected regions.. take the shape_roi as is # rois = shape_roi.getRois() # splits into sub rois # mask_roi = get_largest_roi(rois) # sort out smaller Rois mask_roi = shape_roi mask_roi.setPosition(frame) ov.add(mask_roi) return ov
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 __init__(self, p): self.cellCounter = 1 self.olay = Overlay() self.position = p print p.getRoiPath() if p.getRoiPath() != None: # check if there is an existing overlay file and load it! p.loadRois() self.frame = JFrame("CellCropper", size=(200,200)) self.frame.setLocation(20,120) self.Panel = JPanel(GridLayout(0,1)) self.frame.add(self.Panel) #self.nameField = JTextField("p" + "_c",15) self.nameField = JTextField("p" + str(self.position.getID()) + "_c",15) self.Panel.add(self.nameField) self.cutoutButton = JButton("Cut out cell",actionPerformed=cut) self.Panel.add(self.cutoutButton) self.delOlButton = JButton("Delete Overlay",actionPerformed=delOverlay) self.Panel.add(self.delOlButton) self.saveOlButton = JButton("Save Overlay",actionPerformed=saveOverlay) self.Panel.add(self.saveOlButton) self.quitButton = JButton("Quit script",actionPerformed=quit) self.Panel.add(self.quitButton) self.frame.pack() WindowManager.addWindow(self.frame) self.show()
def drawLines(imp, points=None): if points and (len(points)%2 == 0): # points is numeric list of even length pRoi = PointRoi(points[0::2], points[1::2], len(points)/2) pRoi.setShowLabels(True) pRoi.setSize(3) imp.setRoi(pRoi) roi = imp.getRoi() pp = roi.getFloatPolygon() # print "Added", pp.npoints if pp.npoints <= 1: # don't draw if only one point return xys = [] for i in xrange(pp.npoints): xys.append([pp.xpoints[i], pp.ypoints[i]]) ol = Overlay() x0 = xys[0][0] y0 = xys[0][1] cal = imp.getCalibration() for i in xrange(1, pp.npoints): xi = xys[i][0] yi = xys[i][1] # prepare text label d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth dText = String.format("%.2f ", d) + cal.getUnits() textOffset = 30 xt = xi yt = yi # if xi > x0: # xt += textOffset if xi < x0: xt -= textOffset # if yi > y0: # yt += textOffset if yi < y0: yt -= textOffset dTextRoi = TextRoi(xt, yt, dText) ol.add(dTextRoi) lineRoi = Line(x0, y0, xi, yi) lineRoi.setStrokeWidth(1) lineRoi.setStrokeColor(Color(255,255,0)) ol.add(lineRoi) imp.setOverlay(ol) imp.updateAndDraw()
def draw_scale(image, ticks): cal = image.getCalibration() overlay = Overlay() image.setOverlay(overlay) TextRoi.setGlobalJustification(TextRoi.CENTER) offset = image.getHeight() - extend for tick in ticks: tick_pos = cal.getRawX(tick) line = Line(tick_pos, offset, tick_pos, offset + font_size) line.setWidth(font_size // 8) line.setStrokeColor(Color(1.00, 1.00, 1.00)) overlay.add(line) text = TextRoi(tick_pos, offset + font_size, str(tick), font) text_width = text.getFloatWidth() text_y = text.getYBase() text.setLocation(tick_pos - text_width/2, text_y) text.setStrokeColor(Color(1.00, 1.00, 1.00)) overlay.add(text)
def labelMontage(imp, lLabels, cols, rows, w0=12, h0=2, font=24, col=Color.WHITE): """labelMontage(imp, lLabels, cols, rows, w0=12, h0=2, font=24, col=Color.WHITE) Label a montage in the overlay Inputs: imp - the ImagePlus of the montage to label lLabels - a list of labels to write into the overlay cols - the number of columns in the montage rows - the number of rows in the montage w0 - the x offset for the label (defaults to 12 px) h0 - the y offset for the label (defaults to 2 px) font - the size of the font (pts, defaults to 24) col - color of text. Default to Color.WHITE Returns an ImagePlus with a labeled, duplicate of the input image """ print(cols,rows) wBase = imp.getWidth()/cols hBase = imp.getHeight()/rows print(wBase, hBase) l = len(lLabels) xt = 0 y = 0 # make a copy res = imp.duplicate() # let's create an array of text rois ol = Overlay() for i in range(l): x = (i % cols+1)-1 if x < xt: y += 1 xt = x xL = x * wBase + w0 yL = y * hBase + h0 print(xL,yL) tr = TextRoi(xL, yL, lLabels[i]) tr.setColor(col) tr.setFont("SanSerif", font, 1) tr.setJustification(TextRoi.CENTER) tr.setAntialiased(True) ol.add(tr) res.show() res.setOverlay(ol) res.updateAndRepaintWindow() return res
def getOverlay(imp): """ Returns an image overlay cleansed of spot ROIs from previous runs """ overlay = imp.getOverlay() if overlay is None: return Overlay() for i in range(0, overlay.size() - 1): roi_name = overlay.get(i).getName() if roi_name is not None and "Spots" in roi_name: overlay.remove(i) return overlay
def analyse(): rt = ResultsTable() ol = Overlay() masks = [getMask(imp, c) for c in range(1, C+1)] DAPImask = masks[0] IJ.run(DAPImask, "Create Selection", "") DAPIRoi = DAPImask.getRoi() rois = ShapeRoi(DAPIRoi).getRois() for c,mask in enumerate(masks): if c==0:
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 createMIP(self): print "starting createMIP" for a in self.itemSelected: ImStack = None for filename in self.dict1.get(a): self.savfileName = a if not filename.endswith(self.fileExt): continue path = self.sourceDir + filename # Upon finding the first image, initialize the VirtualStack if ImStack is None: imp = IJ.openImage(path) ImStack = VirtualStack(imp.width, imp.height, None, self.sourceDir) # Add a slice, relative to the sourceDIr ImStack.addSlice(filename) #adding text overlay to output images so we can differentiate them. Overlay is non destructive - does not affect pixel values of image, and can be selected and deleted prefix_overlay = Overlay() font = Font("SansSerif", Font.PLAIN, 10) roi = TextRoi(0, 0, a) roi.setStrokeColor(Color(1.00, 1.00, 1.00)) prefix_overlay.add(roi) # OnscreenImage = ImagePlus(self.sourceDir, ImStack) OnscreenImage.setOverlay(prefix_overlay) OnscreenImage.show() print "Generating MIP, waiting..." self.outimp = self.maxZprojection( OnscreenImage) #generate max projection self.outimp.setOverlay(prefix_overlay) self.outimp.show() print "Max projection generated" if self.saveState == "Y": self.saveMIP() print "Finished!"
def drawLines(imp, points=None): if points and (len(points) % 2 == 0): # points is numeric list of even length pRoi = PointRoi(points[0::2], points[1::2], len(points) / 2) pRoi.setShowLabels(True) pRoi.setSize(3) imp.setRoi(pRoi) roi = imp.getRoi() pp = roi.getFloatPolygon() # print "Added", pp.npoints if pp.npoints <= 1: # don't draw if only one point return xys = [] for i in xrange(pp.npoints): xys.append([pp.xpoints[i], pp.ypoints[i]]) ol = Overlay() x0 = xys[0][0] y0 = xys[0][1] cal = imp.getCalibration() for i in xrange(1, pp.npoints): xi = xys[i][0] yi = xys[i][1] # prepare text label d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth dText = String.format("%.2f ", d) + cal.getUnits() textOffset = 30 xt = xi yt = yi # if xi > x0: # xt += textOffset if xi < x0: xt -= textOffset # if yi > y0: # yt += textOffset if yi < y0: yt -= textOffset dTextRoi = TextRoi(xt, yt, dText) ol.add(dTextRoi) lineRoi = Line(x0, y0, xi, yi) lineRoi.setStrokeWidth(1) lineRoi.setStrokeColor(Color(255, 255, 0)) ol.add(lineRoi) imp.setOverlay(ol) imp.updateAndDraw()
def save_roi_set(imp=IJ.getImage()): img_dir, name = get_file_info() roi_dir = make_roi_dir(img_dir, name) roi_path = make_roi_path(roi_dir, name) Roi.setColor(Color.blue) rm = RoiManager().getInstance() rm.deselect() rm.runCommand("Save", roi_path) ol = imp.getOverlay() if ol is None: ol = Overlay() for roi in rm.getRoisAsArray(): ol.add(roi) imp.setOverlay(ol) rm.runCommand("delete") ol.setStrokeColor(Color.blue) Roi.setColor(Color.yellow)
def NND(imp, mapC, compareC): cal = imp.getCalibration() title = imp.getTitle() impZ = imp.getNSlices() dup = Duplicator() compare = dup.run(imp, compareC, compareC, 1, impZ, 1, 1) compare = reslice(compare, cal.pixelWidth) IJ.run(compare, "Gaussian Blur 3D...", "x=3 y=3 z=3") Z = compare.getNSlices() IJ.setAutoThreshold(compare, THRESHOLD + " dark stack") Prefs.blackBackground = True IJ.run(compare, "Convert to Mask", "method=" + THRESHOLD + " background=Dark black") IJ.run(compare, "Exact Signed Euclidean Distance Transform (3D)", "") edtcompare = WindowManager.getImage("EDT") edtcompare.getWindow().setVisible(False) mapp = dup.run(imp, mapC, mapC, 1, impZ, 1, 1) mapp = reslice(mapp, cal.pixelWidth) IJ.run(mapp, "Gaussian Blur 3D...", "x=3 y=3 z=3") IJ.setAutoThreshold(mapp, THRESHOLD + " dark stack") Prefs.blackBackground = True IJ.run(mapp, "Convert to Mask", "method=" + THRESHOLD + " background=Dark black") dists = [] rt = ResultsTable() ol = Overlay() row = 0 for z in range(Z): mapp.setPosition(z + 1) IJ.run(mapp, "Create Selection", "") if mapp.getStatistics().mean == 0: IJ.run(mapp, "Make Inverse", "") roi = mapp.getRoi() if roi is None: continue edtcompare.setPosition(z + 1) edtcompare.setRoi(roi) IJ.setBackgroundColor(0, 0, 0) IJ.run(edtcompare, "Clear Outside", "slice") ip = edtcompare.getProcessor() roiList = ShapeRoi(roi).getRois() #split roi to limit bounds for sr in roiList: bounds = sr.getBounds() for y in range(0, bounds.height): for x in range(0, bounds.width): if sr.contains(bounds.x + x, bounds.y + y): d = ip.getf(bounds.x + x, bounds.y + y) * cal.pixelWidth * 1000 rt.setValue("C" + str(mapC) + " X", row, (bounds.x + x) * cal.pixelWidth) rt.setValue("C" + str(mapC) + " Y", row, (bounds.y + y) * cal.pixelHeight) rt.setValue("C" + str(mapC) + " Z", row, z * cal.pixelDepth) rt.setValue("Distance to C" + str(compareC) + " (nm)", row, d) row += 1 histD = d if histD >= 0: #set all overlapping voxel distances to 0 histD = 0 dists.append( -histD) #invert to positive for outside distance posZ = int(((z + 1) / float(Z)) * impZ) + 1 roi.setPosition(0, posZ, 1) roi.setStrokeColor(Colour.MAGENTA) ol.add(roi) compare.setPosition(z + 1) IJ.run(compare, "Create Selection", "") if compare.getStatistics().mean == 0: IJ.run(compare, "Make Inverse", "") compareRoi = compare.getRoi() if compareRoi is not None: compareRoi.setPosition(0, posZ, 1) compareRoi.setStrokeColor(Colour.CYAN) ol.add(compareRoi) edtcompare.killRoi() histogram(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance", dists) rt.show(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance") imp.setOverlay(ol) compare.close() edtcompare.changes = False edtcompare.close() mapp.close()
def addRoiToOverlay(imp, roi, labCol=Color.white, linCol=Color.white): """addRoiToOverlay(imp, roi, labCol=Color.white, linCol=Color.white) A convenience function to draw a ROI into the overlay of an ImagePlus. This is useful for situations where ROIs are computed from a highly processed image and tha analyst wants to draw them into the overlay of the original image (e.g. particle analysis after a watershed separation. Adapted from addToOverlay() from Analyzer.java Inputs: imp - the ImagePlus instance into which we draw the ROI roi - the ROI to draw labCol - the color or the label (default white) linCol - the color of the stroke/line (default white) Returns imp - the ImagePlus with the updated overlay""" roi.setIgnoreClipRect(True) ovl = imp.getOverlay() if ovl == None: ovl = Overlay() ovl.drawNames(True) ovl.setStrokeColor(linCol) ovl.setLabelColor(labCol); ovl.drawBackgrounds(False); ovl.add(roi) imp.setOverlay(ovl) return imp
plot.setFixedLegendItems(legend) frame = ChartFrame(imp.getTitle()+" Z-Normalised Intensity", chart) frame.pack() frame.setSize( Dimension(800, 800) ) frame.setLocationRelativeTo(None) frame.setVisible(True) imp = IJ.getImage() cal = imp.getCalibration() if cal.pixelWidth > 0.5: IJ.error("Bad calibration: "+str(cal.pixelWidth)+" "+cal.getUnit()) exit(0) ol = Overlay() stack = imp.getStack() W = imp.getWidth() H = imp.getHeight() Z = imp.getNSlices() T = imp.getNFrames() focusStack = getDICfocus(imp) projC1 = getC1Projection(imp, True) cells = getCells(focusStack) nuclei = getNuclei(projC1) measure(projC1, cells, nuclei)
gw = CellsSelection() gw.setTitle(imp.getTitle()) 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 : ",2,0) gd0.addNumericField("Sub sampling ? : ",1,0) gd0.showDialog() isShow = gd0.getNextBoolean() minLife = gd0.getNextNumber() mind = gd0.getNextNumber() subs = gd0.getNextNumber() if gd0.wasCanceled() : isShow = True
class Menue(object): def __init__(self, p): self.cellCounter = 1 self.olay = Overlay() self.position = p print p.getRoiPath() if p.getRoiPath() != None: # check if there is an existing overlay file and load it! p.loadRois() self.frame = JFrame("CellCropper", size=(200,200)) self.frame.setLocation(20,120) self.Panel = JPanel(GridLayout(0,1)) self.frame.add(self.Panel) #self.nameField = JTextField("p" + "_c",15) self.nameField = JTextField("p" + str(self.position.getID()) + "_c",15) self.Panel.add(self.nameField) self.cutoutButton = JButton("Cut out cell",actionPerformed=cut) self.Panel.add(self.cutoutButton) self.delOlButton = JButton("Delete Overlay",actionPerformed=delOverlay) self.Panel.add(self.delOlButton) self.saveOlButton = JButton("Save Overlay",actionPerformed=saveOverlay) self.Panel.add(self.saveOlButton) self.quitButton = JButton("Quit script",actionPerformed=quit) self.Panel.add(self.quitButton) self.frame.pack() WindowManager.addWindow(self.frame) self.show() #IJ.setTool("freehand") '''def getPosition(self, path, filename): moved to containers.position.determineID(path, filename)''' def eventtest(self, event): print "eventtest" def setTextField(self, pos): name = "p" + str(pos) + "_c" self.nameField.setText(name) def openOl(self, path, fileName): print "aaaaah" def show(self): self.frame.visible = True def close(self): if self.olay != None: yncd = YesNoCancelDialog(self.frame, "Save overlay?", "Save overlay?") #frame, title, message if yncd.yesPressed(): self.saveOverlay() WindowManager.removeWindow(self.frame) self.frame.dispose() def resetCounter(self): self.cellCounter = 0 def increaseCounter(self): self.cellCounter += 1 def setCounter(self): self.cellCounter += 1 #'get' functions def getImp(self): return self.imp def getCounter(self): return self.cellCounter def getFrame(self): return self.frame def getFilePath(self): return self.filePath def getTextField(self): return self.nameField.text def getPosition(self): return self.position # overlay functions def addOlay(self, roi): self.olay.add(roi) def getOverlay(self): return self.olay def clearOverlay(self): self.olay.clear() self.cellCounter = 1 def saveOverlay(self): self.position.saveRois()
ipBF.blurGaussian(5) maskBF = getMask(ipBF, AutoThresholder.Method.Triangle) roisBF = getRois(maskBF) ipTomato = stack.getProcessor(imp.getStackIndex(3, z, 1)).duplicate() sub = ipTomato.duplicate() ipTomato.blurGaussian(5) sub.blurGaussian(20) ipTomato.copyBits(sub, 0, 0, Blitter.SUBTRACT) maskTomato = getMask(ipTomato, AutoThresholder.Method.MaxEntropy) roisTomato = getRois(maskTomato) bfMeasure = stack.getProcessor(imp.getStackIndex(2, z, 1)) tomatoMeasure = stack.getProcessor(imp.getStackIndex(3, z, 1)) gfpMeasure = stack.getProcessor(imp.getStackIndex(1, z, 1)) ol = Overlay() rt = ResultsTable() rt.showRowNumbers(False) for bf in roisBF: bfMeasure.setRoi(bf) roiStatsBF = bfMeasure.getStatistics() if roiStatsBF.area * cal.pixelWidth * cal.pixelHeight < BFminA: continue bounds = bf.getBounds() cXbf = int(bounds.x + (bounds.width / 2.0)) cYbf = int(bounds.y + (bounds.height / 2.0)) bf.setStrokeColor(Color.YELLOW) bf.setPosition(0, z, 1) ol.add(bf)
IJ.setBackgroundColor(1, 1, 1) imp2 = IJ.getImage() IJ.run(imp2, "Draw", "slice") IJ.run("Select None") # sets up tools for for ER measurement protocol IJ.run("Point Tool...", "type=Cross color=Yellow size=Tiny add_to") IJ.setTool("point") to_transport_channel() # user interface nbgd = NonBlockingGenericDialog("ER Selection") nbgd.addStringField("Selection radius: ", str(radius), 5) nbgd.hideCancelButton() imp = IJ.getImage() overlay = Overlay() overlay = imp.getOverlay() nbgd.showDialog() if mean_max_det is True: IJ.setTool("polygon") else: IJ.setTool("rectangle") radius = int(nbgd.getNextString().strip()) imp = IJ.getImage() # set variables all_x = [] all_y = [] ER_measurements = []
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" IJ.run("Gaussian Blur...", set_sigma) path = os.chdir(dest) if not os.path.exists(ProFolder): os.mkdir(ProFolder) os.chdir(ProFolder) Path = (os.getcwd())
def batch_open_images(pathImage, pathRoi, pathMask, file_typeImage=None, name_filterImage=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the images. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Reject files that contain the given string (default: wild characters). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True def dog_detection(overlay,img, imp, cal): # Create a variable of the correct type (UnsignedByteType) for the value-extended view zero = img.randomAccess().get().createVariable() # Run the difference of Gaussian cell = 8.0 # microns in diameter min_peak = 2.0 # min intensity for a peak to be considered dog = DogDetection(Views.extendValue(img, zero), img, [cal.pixelWidth, cal.pixelHeight,cal.pixelDepth], cell / 2, cell, DogDetection.ExtremaType.MINIMA, min_peak, False, DoubleType()) peaks = dog.getPeaks() roi = OvalRoi(0, 0, cell/cal.pixelWidth, cell/cal.pixelHeight) print ('Number of cells = ', len(peaks)) p = zeros(img.numDimensions(), 'i') boundRect = imp.getRoi() for peak in peaks: # Read peak coordinates into an array of integers XYZ location of spots peak.localize(p) print(p) if(boundRect is not None and boundRect.contains(p[0], p[1])): oval = OvalRoi(p[0], p[1],cell/cal.pixelWidth, cell/cal.pixelHeight) oval.setColor(Color.RED) overlay.add(oval) def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathImage): full_path = os.path.join(pathImage, file_name) if os.path.isfile(full_path): if check_type(file_name): if check_filter(file_name): path_to_Image.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([full_path, os.path.basename(os.path.splitext(full_path)[0])]) # Create the list that will be returned by this function. Images = [] Rois = [] for img_path, file_name in path_to_Image: # IJ.openImage() returns an ImagePlus object or None. imp = IJ.openImage(img_path) imp.show() print(img_path) if check_filter(file_name): continue; else: print(file_name , pathRoi) RoiName = str(pathRoi) + '/'+ file_name + '_rois' + '.zip' if os.path.exists(RoiName): Roi = IJ.open(RoiName) imp = IJ.getImage() cal= imp.getCalibration()# in microns img = IJF.wrap(imp) print('Image Dimensions', img.dimensions, 'Calibration', cal) print(Roi) # An object equals True and None equals False. rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() try: rm.runCommand('Delete') except: pass rm.runCommand("Open", RoiName) rois = rm.getRoisAsArray() overlay = Overlay() for (i in range(0,len(rois))): overlay.add(rois[i])
def main(imp,options): from ij.plugin import ChannelSplitter from ij.gui import Roi,PointRoi, PolygonRoi, Overlay, Line from java.awt import Color from ij import WindowManager from ij.measure import ResultsTable from ij.text import TextWindow active_z=imp.getZ() imps = ChannelSplitter.split(imp) imp.setZ(active_z) roi_int = imp.getRoi() comp_imp=Zproj(imps[options["comp_ch"]], "SUM", active_z, options["z_range"]) comp_imp=mode_subtract(comp_imp,roi_int) loci_imp=Zproj(imps[options["loci_ch"]], "SUM", imp.getZ(), options["z_range"]) loci_imp=mode_subtract(loci_imp,roi_int) #Finding the boundaries of compartment and loci comp_roi=thresh(sum_prj=comp_imp,thresh=options["comp_T"],roi=roi_int,method="boundary") print "ok" if (options["loci_method"]== "locus center"): loci_roi=thresh(sum_prj=loci_imp, thresh=options["loci_T"], roi=roi_int, method="point") elif options["loci_method"]== "locus boundary": loci_roi=thresh(sum_prj=loci_imp, thresh=options["loci_T"], roi=roi_int, method="boundary") if options["loci_method"]== "locus center": dist,xc,yc,xl,yl=get_center_edge_dist(imp,comp_roi, loci_roi) elif options["loci_method"]== "locus boundary": dist,xc,yc,xl,yl=get_closest_points(imp,comp_roi,loci_roi) rt_exist = WindowManager.getWindow("Loci distance to compartment") if rt_exist==None or not isinstance(rt_exist, TextWindow): table= ResultsTable() else: table = rt_exist.getTextPanel().getOrCreateResultsTable() table.incrementCounter() table.addValue("Label", imp.title) table.addValue("Distance(micron)", dist) if options['measure_feret']: feret_roi,loci_feret,loci_area= feret(sum_prj=loci_imp,thresh=options["loci_T"], roi=roi_int,pixel_size=imp.getCalibration().pixelWidth) table.addValue("Loci feret", loci_feret) table.addValue("Loci area", loci_area) table.show("Loci distance to compartment") ## Adding loci overlay ov=imp.getOverlay() if ov==None: ov=Overlay() line = Line(xc,yc, xl,yl) line.setStrokeWidth(0.2) line.setStrokeColor(Color.PINK) ov.add(line) if options["loci_method"]== "locus center": ov.add(PointRoi(loci_roi["x"],loci_roi["y"])) elif options["loci_method"]== "locus boundary": ov.add(loci_roi) if options['measure_feret']: ov.add(feret_roi) ov.add(comp_roi) imp.setOverlay(ov)
def measureFeatureLength(imp, lw = 2, csvPath=None, bAppend=True, offset = -30, digits = 3, font = 18, linCol = Color.YELLOW, labCol = Color.WHITE, bDebug = False): """ measureFeatureLength(imp, lw = 2, csvPath=None, bAppend=True, offset = -30, digits = 3, font = 18, linCol = Color.YELLOW, labCol = Color.WHITE, bDebug = False) Manually measure the length of a feature in a calibrated ImagePlus and write the results to the overlay. Version of 2016-08-04 Parameters ---------- imp: ImagePlus The image to process lw: int (2) The linewidth for the line csvPath: string (None) The path to a csv file to write measurements bAppend: Boolean (True) A flag. If True new results are appended to the file offset: int (-30) The Y offset for the label. If negative, the label will be written above the measurement, if positive below. digits: int (3) Round the output (in calibrated units) to this number of decimal points. font: int (18) The font size for the measurement. linCol: A color constant (Color.YELLOW) The color for the line in the overlay. labCol: A color constant (Color.WHITE) The color for the label bDebug: A Boolean (False) A flag to print diagnostic incormation Returns ------- None - it does draw in the overlay of the image and write an optional .csv file. Known Issues ------------ With large line widths the length of the drawn line appears lw pixels too long. """ # First define some convenience functions def resetLastMeasureCount(): Prefs.set("JRM.meas.counter", 0) def GetLastMeasureCount(): myCount = Prefs.get("JRM.meas.counter", int(-1)) if myCount < 0: # it was not set, so set it to zero resetLastMeasureCount() return 0 else: myCount = int(myCount) return myCount def setLastMeasureCount(count): count = int(count) Prefs.set("JRM.meas.counter", count) imp = IJ.getImage() if imp == None: print("You need an image...") return else: roi = imp.getRoi() if roi != None: if roi.getType() == Roi.LINE: # print(roi) cal = imp.getCalibration() # print(cal) unit = cal.getUnits() width = cal.pixelWidth height = cal.pixelHeight x1 = roi.x1 * width y1 = roi.y1 * height x2 = roi.x2 * width y2 = roi.y2 * height length = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); if bDebug: sOut = "X1: %d Y1 %d X2 %d Y2 %d" % (roi.x1, roi.y1, roi.x2, roi.y2) print(sOut) print(length, unit) ip = imp.getProcessor() ip.setColor(linCol) oldLW = ip.getLineWidth() ip.setLineWidth(lw) ip.drawLine(roi.x1, roi.y1, roi.x2, roi.y2) ip.setLineWidth(oldLW) imp.updateAndDraw() ol = imp.getOverlay() if ol == None: ol = Overlay() res = imp.duplicate() # first a dummy text ROI to set the font tr = TextRoi(10, 10, "Foo") tr.setColor(labCol) tr.setFont("SanSerif", font, 1) tr.setJustification(TextRoi.CENTER) tr.setAntialiased(True) # explicitly save preferences Prefs.savePreferences() xL = roi.x1 + roi.x2 xL /= 2 if offset < 0: yL = min(roi.y1, roi.y2) yL += offset else: yL = max(roi.y1, roi.y2) yL += offset length = round(length, 3) label = "%g %s" % (length, unit) tr = TextRoi(xL, yL, label) tr.setColor(labCol) tr.setFont("SanSerif", font, 1) tr.setJustification(TextRoi.CENTER) tr.setAntialiased(True) ol.add(tr) imp.setOverlay(ol) imp.show() if csvPath != None: if bAppend: if os.path.isfile(csvPath): theCount = GetLastMeasureCount() + 1 f=open(csvPath, 'a') else: f=open(csvPath, 'w') resetLastMeasureCount() theCount = 1 strLine = 'img, num, length (%s)\n' % unit f.write(strLine) else: f=open(csvPath, 'w') resetLastMeasureCount() theCount = 1 strLine = 'img, num, length (%s)\n' % unit f.write(strLine) strLine = "%s, %d, %.6f\n" % (imp.getShortTitle(), theCount, length) f.write(strLine) f.close() setLastMeasureCount(theCount) strMsg = "measured %s count = %d" % (imp.getShortTitle(), theCount) print(strMsg) else: print("You need a line ROI") # finally deselect IJ.run("Select None")
outputdir = str(outputdir) ais_method = ais_method.lower() ais_threshold /=100 if not path.isdir(inputdir): print inputdir, 'does not exist or is not a directory.' else: summary_rt = ResultsTable.getResultsTable(AIS_SUMMARY_TABLE) if summary_rt is None: summary_rt = ResultsTable() elif clear_summary: summary_rt.reset() if not path.isdir(outputdir): os.makedirs(outputdir) file_pairs = get_file_pairs(inputdir) for item in file_pairs: overlay = Overlay() composite,imps = open_image(item['img']) rois = load_rois(item['roi']) if len(imps) < ais_chno or len(imps) < nucleus_chno: print 'Image %s has %d channels. Cannot process AIS segmentation for channel %d. Skipping.' % (item['img'], len(imps), ais_chno) else: if show_img: composite.show() #for i in imps: # i.show() results, background = process_image(imps, rois, ais_chno, nucleus_chno, bg_roino=3, average=average, sample_width=ais_linewidth, method=ais_method, threshold=ais_threshold) for roiresult in results: ais_roi = roiresult['ais-roi'] nucleus_roi = roiresult['nucleus-roi'] ais_image = roiresult['ais-image'] overlay.add(ais_roi)
results.addValue("stdev", stdev.getRealDouble()) results.addValue("sum", sum.getRealDouble()) results.addValue("comment", comment) # Display the table results.show("Results") # Outline and highlight the regions outline = ops.run("morphology.outline", binary, False) image_imp = ImageJFunctions.wrap(image, "Overlay Render") binary_imp = ImageJFunctions.wrap(binary, "Binary") outline_imp = ImageJFunctions.wrap(outline, "Outline") IJ.run(binary_imp, "Green", "") binary_ROI = ImageRoi(0, 0, binary_imp.getProcessor()) binary_ROI.setZeroTransparent(True) binary_ROI.setOpacity(0.25) IJ.run(outline_imp, "Green", "") outline_ROI = ImageRoi(0, 0, outline_imp.getProcessor()) outline_ROI.setZeroTransparent(True) outline_ROI.setOpacity(1.00) overlay = Overlay() overlay.add(binary_ROI) overlay.add(outline_ROI) image_imp.setOverlay(overlay) image_imp.updateAndDraw() image_imp.show()
def run(imp, preprocessor_path, postprocessor_path, threshold_method, user_comment): output_parameters = { "image title": "", "preprocessor path": float, "post processor path": float, "thresholding op": float, "use ridge detection": bool, "high contrast": int, "low contrast": int, "line width": int, "minimum line length": int, "mitochondrial footprint": float, "branch length mean": float, "branch length median": float, "branch length stdevp": float, "summed branch lengths mean": float, "summed branch lengths median": float, "summed branch lengths stdevp": float, "network branches mean": float, "network branches median": float, "network branches stdevp": float } output_order = [ "image title", "preprocessor path", "post processor path", "thresholding op", "use ridge detection", "high contrast", "low contrast", "line width", "minimum line length", "mitochondrial footprint", "branch length mean", "branch length median", "branch length stdevp", "summed branch lengths mean", "summed branch lengths median", "summed branch lengths stdevp", "network branches mean", "network branches median", "network branches stdevp" ] # Perform any preprocessing steps... status.showStatus("Preprocessing image...") if preprocessor_path != None: if preprocessor_path.exists(): preprocessor_thread = scripts.run(preprocessor_path, True) preprocessor_thread.get() imp = WindowManager.getCurrentImage() else: pass # Store all of the analysis parameters in the table if preprocessor_path == None: preprocessor_str = "" else: preprocessor_str = preprocessor_path.getCanonicalPath() if postprocessor_path == None: postprocessor_str = "" else: postprocessor_str = preprocessor_path.getCanonicalPath() output_parameters["preprocessor path"] = preprocessor_str output_parameters["post processor path"] = postprocessor_str output_parameters["thresholding op"] = threshold_method output_parameters["use ridge detection"] = str(use_ridge_detection) output_parameters["high contrast"] = rd_max output_parameters["low contrast"] = rd_min output_parameters["line width"] = rd_width output_parameters["minimum line length"] = rd_length # Create and ImgPlus copy of the ImagePlus for thresholding with ops... status.showStatus("Determining threshold level...") imp_title = imp.getTitle() slices = imp.getNSlices() frames = imp.getNFrames() output_parameters["image title"] = imp_title imp_calibration = imp.getCalibration() imp_channel = Duplicator().run(imp, imp.getChannel(), imp.getChannel(), 1, slices, 1, frames) img = ImageJFunctions.wrap(imp_channel) # Determine the threshold value if not manual... binary_img = ops.run("threshold.%s" % threshold_method, img) binary = ImageJFunctions.wrap(binary_img, 'binary') binary.setCalibration(imp_calibration) binary.setDimensions(1, slices, 1) # Get the total_area if binary.getNSlices() == 1: area = binary.getStatistics(Measurements.AREA).area area_fraction = binary.getStatistics( Measurements.AREA_FRACTION).areaFraction output_parameters[ "mitochondrial footprint"] = area * area_fraction / 100.0 else: mito_footprint = 0.0 for slice in range(binary.getNSlices()): binary.setSliceWithoutUpdate(slice) area = binary.getStatistics(Measurements.AREA).area area_fraction = binary.getStatistics( Measurements.AREA_FRACTION).areaFraction mito_footprint += area * area_fraction / 100.0 output_parameters[ "mitochondrial footprint"] = mito_footprint * imp_calibration.pixelDepth # Generate skeleton from masked binary ... # Generate ridges first if using Ridge Detection if use_ridge_detection and (imp.getNSlices() == 1): skeleton = ridge_detect(imp, rd_max, rd_min, rd_width, rd_length) else: skeleton = Duplicator().run(binary) IJ.run(skeleton, "Skeletonize (2D/3D)", "") # Analyze the skeleton... status.showStatus("Setting up skeleton analysis...") skel = AnalyzeSkeleton_() skel.setup("", skeleton) status.showStatus("Analyzing skeleton...") skel_result = skel.run() status.showStatus("Computing graph based parameters...") branch_lengths = [] summed_lengths = [] graphs = skel_result.getGraph() for graph in graphs: summed_length = 0.0 edges = graph.getEdges() for edge in edges: length = edge.getLength() branch_lengths.append(length) summed_length += length summed_lengths.append(summed_length) output_parameters["branch length mean"] = eztables.statistical.average( branch_lengths) output_parameters["branch length median"] = eztables.statistical.median( branch_lengths) output_parameters["branch length stdevp"] = eztables.statistical.stdevp( branch_lengths) output_parameters[ "summed branch lengths mean"] = eztables.statistical.average( summed_lengths) output_parameters[ "summed branch lengths median"] = eztables.statistical.median( summed_lengths) output_parameters[ "summed branch lengths stdevp"] = eztables.statistical.stdevp( summed_lengths) branches = list(skel_result.getBranches()) output_parameters["network branches mean"] = eztables.statistical.average( branches) output_parameters["network branches median"] = eztables.statistical.median( branches) output_parameters["network branches stdevp"] = eztables.statistical.stdevp( branches) # Create/append results to a ResultsTable... status.showStatus("Display results...") if "Mito Morphology" in list(WindowManager.getNonImageTitles()): rt = WindowManager.getWindow( "Mito Morphology").getTextPanel().getOrCreateResultsTable() else: rt = ResultsTable() rt.incrementCounter() for key in output_order: rt.addValue(key, str(output_parameters[key])) # Add user comments intelligently if user_comment != None and user_comment != "": if "=" in user_comment: comments = user_comment.split(",") for comment in comments: rt.addValue(comment.split("=")[0], comment.split("=")[1]) else: rt.addValue("Comment", user_comment) rt.show("Mito Morphology") # Create overlays on the original ImagePlus and display them if 2D... if imp.getNSlices() == 1: status.showStatus("Generate overlays...") IJ.run(skeleton, "Green", "") IJ.run(binary, "Magenta", "") skeleton_ROI = ImageRoi(0, 0, skeleton.getProcessor()) skeleton_ROI.setZeroTransparent(True) skeleton_ROI.setOpacity(1.0) binary_ROI = ImageRoi(0, 0, binary.getProcessor()) binary_ROI.setZeroTransparent(True) binary_ROI.setOpacity(0.25) overlay = Overlay() overlay.add(binary_ROI) overlay.add(skeleton_ROI) imp.setOverlay(overlay) imp.updateAndDraw() # Generate a 3D model if a stack if imp.getNSlices() > 1: univ = Image3DUniverse() univ.show() pixelWidth = imp_calibration.pixelWidth pixelHeight = imp_calibration.pixelHeight pixelDepth = imp_calibration.pixelDepth # Add end points in yellow end_points = skel_result.getListOfEndPoints() end_point_list = [] for p in end_points: end_point_list.append( Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addIcospheres(end_point_list, Color3f(255.0, 255.0, 0.0), 2, 1 * pixelDepth, "endpoints") # Add junctions in magenta junctions = skel_result.getListOfJunctionVoxels() junction_list = [] for p in junctions: junction_list.append( Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addIcospheres(junction_list, Color3f(255.0, 0.0, 255.0), 2, 1 * pixelDepth, "junctions") # Add the lines in green graphs = skel_result.getGraph() for graph in range(len(graphs)): edges = graphs[graph].getEdges() for edge in range(len(edges)): branch_points = [] for p in edges[edge].getSlabs(): branch_points.append( Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addLineMesh(branch_points, Color3f(0.0, 255.0, 0.0), "branch-%s-%s" % (graph, edge), True) # Add the surface univ.addMesh(binary) univ.getContent("binary").setTransparency(0.5) # Perform any postprocessing steps... status.showStatus("Running postprocessing...") if postprocessor_path != None: if postprocessor_path.exists(): postprocessor_thread = scripts.run(postprocessor_path, True) postprocessor_thread.get() else: pass status.showStatus("Done analysis!")
from ij.gui import Roi, Overlay c = RConnection() x = c.eval("R.version.string") print x.asString() print "Loaded Package:", c.eval("library(Peaks)").asString() imp = IJ.getImage() roi = imp.getRoi() if roi.getType() == Roi.LINE: print "a line roi found" profile = roi.getPixels() c.assign("prof", profile) # pks = c.eval("SpectrumSearch(prof, sigma=1, threshold=25, background=TRUE, iterations=20, markov=TRUE, window=5)").asList() # pks = c.eval("SpectrumSearch(prof, sigma=3, threshold=25, background=TRUE, iterations=20, markov=TRUE, window=5)").asList() # pks = c.eval("SpectrumSearch(prof, sigma=3, threshold=2, background=TRUE, iterations=20, markov=TRUE, window=2)").asList() pks = c.eval("SpectrumSearch(prof, sigma=2, threshold=2, background=TRUE, iterations=20, markov=FALSE, window=2)").asList() pksX = pks[0].asIntegers() rois = [] print "Number of Peaks:", len(pksX) for i in pksX: #print "\t", roi.x1, i rois.append(PointRoi(roi.x1, roi.y1 + i)) ol = Overlay() for aroi in rois: ol.add(aroi) imp.setOverlay(ol) c.close()
zero = img.randomAccess().get().createVariable() # Run the difference of Gaussian cell = 30.0 # microns in diameter min_peak = 10.0 # min intensity for a peak to be considered dog = DogDetection( Views.extendValue(img, zero), img, [cal.pixelWidth, cal.pixelHeight], cell / 2, cell, DogDetection.ExtremaType.MAXIMA, #MAXIMA min_peak, False, DoubleType()) peaks = dog.getPeaks() roi = OvalRoi(0, 0, cell / cal.pixelWidth, cell / cal.pixelHeight) print('Number of cells = ', len(peaks)) p = zeros(img.numDimensions(), 'i') overlay = Overlay() imp.setOverlay(overlay) for peak in peaks: # Read peak coordinates into an array of integers peak.localize(p) if (boundRect.contains(p[0], p[1])): oval = OvalRoi(p[0], p[1], cell / cal.pixelWidth, cell / cal.pixelHeight) oval.setColor(Color.RED) overlay.add(oval)
impProc.flipVertical() impProc = impProc.rotateRight() impProc.smooth() impProc.setInterpolationMethod(ImageProcessor.NONE) impProc = impProc.resize(canvasWidth,canvasHeight) imp.setProcessor(impProc) imp.show() IJ.run(imp, "Rainbow RGB", ""); IJ.run(imp, "Canvas Size...", "width=800 height=1024 position=Top-Center zero"); testROI = Roi(0,canvasHeight,canvasWidth,6) testROI.setFillColor(Color.WHITE) imp.setRoi(testROI,True) overlay = Overlay(testROI) font = Font("SansSerif",Font.PLAIN,fontSize) # Write the EmissionWavelengths according # to the metadata read earlier. for i in xrange(1,len(pixelInt2[0]),tickInterval): pixelSize = (canvasWidth/(len(pixelInt2[0])*1.0)) calc = (pixelSize)*(i) roi = TextRoi(calc+(pixelSize*0.2),canvasHeight+10,str(emissionWL[i]),font) roi.setStrokeColor(Color(1.00, 1.00, 1.00)); overlay.add(roi) imp.setOverlay(overlay) imp.show() IJ.run(imp, "Calibration Bar...", "location=[Upper Right] fill=None label=White number=3 decimal=1 font=9 zoom=2 bold overlay");
gw = CellsSelection() gw.setTitle(imp.getTitle()) 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()
def run(imp, preprocessor_path, postprocessor_path, threshold_method, user_comment): output_parameters = {"image title" : "", "preprocessor path" : float, "post processor path" : float, "thresholding op" : float, "use ridge detection" : bool, "high contrast" : int, "low contrast" : int, "line width" : int, "minimum line length" : int, "mitochondrial footprint" : float, "branch length mean" : float, "branch length median" : float, "branch length stdevp" : float, "summed branch lengths mean" : float, "summed branch lengths median" : float, "summed branch lengths stdevp" : float, "network branches mean" : float, "network branches median" : float, "network branches stdevp" : float} output_order = ["image title", "preprocessor path", "post processor path", "thresholding op", "use ridge detection", "high contrast", "low contrast", "line width", "minimum line length", "mitochondrial footprint", "branch length mean", "branch length median", "branch length stdevp", "summed branch lengths mean", "summed branch lengths median", "summed branch lengths stdevp", "network branches mean", "network branches median", "network branches stdevp"] # Perform any preprocessing steps... status.showStatus("Preprocessing image...") if preprocessor_path != None: if preprocessor_path.exists(): preprocessor_thread = scripts.run(preprocessor_path, True) preprocessor_thread.get() imp = WindowManager.getCurrentImage() else: pass # Store all of the analysis parameters in the table if preprocessor_path == None: preprocessor_str = "" else: preprocessor_str = preprocessor_path.getCanonicalPath() if postprocessor_path == None: postprocessor_str = "" else: postprocessor_str = preprocessor_path.getCanonicalPath() output_parameters["preprocessor path"] = preprocessor_str output_parameters["post processor path"] = postprocessor_str output_parameters["thresholding op"] = threshold_method output_parameters["use ridge detection"] = str(use_ridge_detection) output_parameters["high contrast"] = rd_max output_parameters["low contrast"] = rd_min output_parameters["line width"] = rd_width output_parameters["minimum line length"] = rd_length # Create and ImgPlus copy of the ImagePlus for thresholding with ops... status.showStatus("Determining threshold level...") imp_title = imp.getTitle() slices = imp.getNSlices() frames = imp.getNFrames() output_parameters["image title"] = imp_title imp_calibration = imp.getCalibration() imp_channel = Duplicator().run(imp, imp.getChannel(), imp.getChannel(), 1, slices, 1, frames) img = ImageJFunctions.wrap(imp_channel) # Determine the threshold value if not manual... binary_img = ops.run("threshold.%s"%threshold_method, img) binary = ImageJFunctions.wrap(binary_img, 'binary') binary.setCalibration(imp_calibration) binary.setDimensions(1, slices, 1) # Get the total_area if binary.getNSlices() == 1: area = binary.getStatistics(Measurements.AREA).area area_fraction = binary.getStatistics(Measurements.AREA_FRACTION).areaFraction output_parameters["mitochondrial footprint"] = area * area_fraction / 100.0 else: mito_footprint = 0.0 for slice in range(binary.getNSlices()): binary.setSliceWithoutUpdate(slice) area = binary.getStatistics(Measurements.AREA).area area_fraction = binary.getStatistics(Measurements.AREA_FRACTION).areaFraction mito_footprint += area * area_fraction / 100.0 output_parameters["mitochondrial footprint"] = mito_footprint * imp_calibration.pixelDepth # Generate skeleton from masked binary ... # Generate ridges first if using Ridge Detection if use_ridge_detection and (imp.getNSlices() == 1): skeleton = ridge_detect(imp, rd_max, rd_min, rd_width, rd_length) else: skeleton = Duplicator().run(binary) IJ.run(skeleton, "Skeletonize (2D/3D)", "") # Analyze the skeleton... status.showStatus("Setting up skeleton analysis...") skel = AnalyzeSkeleton_() skel.setup("", skeleton) status.showStatus("Analyzing skeleton...") skel_result = skel.run() status.showStatus("Computing graph based parameters...") branch_lengths = [] summed_lengths = [] graphs = skel_result.getGraph() for graph in graphs: summed_length = 0.0 edges = graph.getEdges() for edge in edges: length = edge.getLength() branch_lengths.append(length) summed_length += length summed_lengths.append(summed_length) output_parameters["branch length mean"] = eztables.statistical.average(branch_lengths) output_parameters["branch length median"] = eztables.statistical.median(branch_lengths) output_parameters["branch length stdevp"] = eztables.statistical.stdevp(branch_lengths) output_parameters["summed branch lengths mean"] = eztables.statistical.average(summed_lengths) output_parameters["summed branch lengths median"] = eztables.statistical.median(summed_lengths) output_parameters["summed branch lengths stdevp"] = eztables.statistical.stdevp(summed_lengths) branches = list(skel_result.getBranches()) output_parameters["network branches mean"] = eztables.statistical.average(branches) output_parameters["network branches median"] = eztables.statistical.median(branches) output_parameters["network branches stdevp"] = eztables.statistical.stdevp(branches) # Create/append results to a ResultsTable... status.showStatus("Display results...") if "Mito Morphology" in list(WindowManager.getNonImageTitles()): rt = WindowManager.getWindow("Mito Morphology").getTextPanel().getOrCreateResultsTable() else: rt = ResultsTable() rt.incrementCounter() for key in output_order: rt.addValue(key, str(output_parameters[key])) # Add user comments intelligently if user_comment != None and user_comment != "": if "=" in user_comment: comments = user_comment.split(",") for comment in comments: rt.addValue(comment.split("=")[0], comment.split("=")[1]) else: rt.addValue("Comment", user_comment) rt.show("Mito Morphology") # Create overlays on the original ImagePlus and display them if 2D... if imp.getNSlices() == 1: status.showStatus("Generate overlays...") IJ.run(skeleton, "Green", "") IJ.run(binary, "Magenta", "") skeleton_ROI = ImageRoi(0,0,skeleton.getProcessor()) skeleton_ROI.setZeroTransparent(True) skeleton_ROI.setOpacity(1.0) binary_ROI = ImageRoi(0,0,binary.getProcessor()) binary_ROI.setZeroTransparent(True) binary_ROI.setOpacity(0.25) overlay = Overlay() overlay.add(binary_ROI) overlay.add(skeleton_ROI) imp.setOverlay(overlay) imp.updateAndDraw() # Generate a 3D model if a stack if imp.getNSlices() > 1: univ = Image3DUniverse() univ.show() pixelWidth = imp_calibration.pixelWidth pixelHeight = imp_calibration.pixelHeight pixelDepth = imp_calibration.pixelDepth # Add end points in yellow end_points = skel_result.getListOfEndPoints() end_point_list = [] for p in end_points: end_point_list.append(Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addIcospheres(end_point_list, Color3f(255.0, 255.0, 0.0), 2, 1*pixelDepth, "endpoints") # Add junctions in magenta junctions = skel_result.getListOfJunctionVoxels() junction_list = [] for p in junctions: junction_list.append(Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addIcospheres(junction_list, Color3f(255.0, 0.0, 255.0), 2, 1*pixelDepth, "junctions") # Add the lines in green graphs = skel_result.getGraph() for graph in range(len(graphs)): edges = graphs[graph].getEdges() for edge in range(len(edges)): branch_points = [] for p in edges[edge].getSlabs(): branch_points.append(Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth)) univ.addLineMesh(branch_points, Color3f(0.0, 255.0, 0.0), "branch-%s-%s"%(graph, edge), True) # Add the surface univ.addMesh(binary) univ.getContent("binary").setTransparency(0.5) # Perform any postprocessing steps... status.showStatus("Running postprocessing...") if postprocessor_path != None: if postprocessor_path.exists(): postprocessor_thread = scripts.run(postprocessor_path, True) postprocessor_thread.get() else: pass status.showStatus("Done analysis!")
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): title = inputImp.getTitle() title=title.replace('UV', 'SD') print title #trueColorImp= WindowManager.getImage(title) #print type( trueColorImp) # calculate are of roi stats=inputImp.getStatistics() inputRoiArea=stats.area print inputRoi # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 print x1 print y1 print x2 print y2 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) #duplicate.show() # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", ""); brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3") brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate=duplicator.run(croppedPlus) channels=ChannelSplitter().split(duplicate) redPlus=channels[0] red=ImgPlus(ImageJFunctions.wrapByte(redPlus)) redPlus.show() # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() # get the A channel APlus=substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') APlus.show() APlus.getProcessor().resetMinAndMax() APlus.updateAndDraw() AThresholded=threshold(APlus, -10, 50) # get the B channel BPlus=substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') BPlus.show() BPlus.getProcessor().resetMinAndMax() BPlus.updateAndDraw() BThresholded=threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator(); redMask = ic.run("AND create", AThresholded, BThresholded); IJ.run(redMask, "Divide...", "value=255"); #redMask.show() labPlus.close() # threshold the spots from the red channel thresholdedred=SpotDetectionGray(red, data, display, ops, False) display.createDisplay("thresholdedred", data.create(thresholdedred)) impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") # threshold the spots from the brightness channel thresholded=SpotDetectionGray(brightness, data, display, ops, False) display.createDisplay("thresholded", data.create(thresholded)) impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") # clear the region outside the roi clone=inputRoi.clone() clone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, clone) # create a hidden roi manager roim = RoiManager(True) # count the particlesimp.getProcessor().setColor(Color.green) countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity) # define a function to determine the percentage of pixels that are foreground in a binary image # inputs: # imp: binary image, 0=background, 1=foreground # roi: an roi def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return False else: return True allList=[] for roi in roim.getRoisAsArray(): allList.append(roi.clone()) # count particles that are red redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed) # count particles that are red blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed) print "Total particles: "+str(len(allList)) print "Filtered particles: "+str(len(redList)) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList] # create an overlay and add the rois overlay1=Overlay() inputRoi.setStrokeColor(Color.green) overlay1.add(inputRoi) [CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList] [CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList] def drawAllRoisOnImage(imp, mainRoi, redList, blueList): imp.getProcessor().setColor(Color.green) IJ.run(imp, "Line Width...", "line=3"); imp.getProcessor().draw(inputRoi) imp.updateAndDraw() IJ.run(imp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList] [CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList] imp.updateAndDraw() drawAllRoisOnImage(inputImp, inputRoi, redList, blueList) #drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList) # draw overlay #inputImp.setOverlay(overlay1) #inputImp.updateAndDraw() statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray()) print inputRoiArea areas=statsdict['Areas'] poreArea=0 for area in areas: poreArea=poreArea+area ATotal=0 ALevels=statsdict['ALevel'] for A in ALevels: ATotal=ATotal+A AAverage=ATotal/len(ALevels) BTotal=0 BLevels=statsdict['BLevel'] for B in BLevels: BTotal=BTotal+B BAverage=BTotal/len(BLevels) redTotal=0 redPercentages=statsdict['redPercentage'] for red in redPercentages: redTotal=redTotal+red redAverage=redTotal/len(redPercentages) pixwidth=inputImp.getCalibration().pixelWidth inputRoiArea=inputRoiArea/(pixwidth*pixwidth) print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
def batch_open_images(pathImage, file_typeImage, name_filterImage=None): if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([ full_path, os.path.basename(os.path.splitext(full_path)[0]) ]) Images = [] for img_path, file_name in path_to_Image: imp = IJ.openImage(img_path) maskimage = ops.run("create.img", imp) cursor = maskimage.localizingCursor() imp.show() IJ.run("Select None") overlay = imp.getOverlay() if overlay == None: overlay = Overlay() imp.setOverlay(overlay) else: overlay.clear() imp.updateAndDraw() impY = imp.getHeight() impX = imp.getWidth() print(impY, impX) rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.runCommand("reset") WaitForUserDialog("Select the landmark and the second point").show() rm.runCommand("Add") roi_points = rm.getRoisAsArray() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints print(xpoints, ypoints) print('Start Landmark', xpoints[0], ypoints[0]) fixedpointX = xpoints[0] fixedpointY = ypoints[0] print('End Landmark', xpoints[1], ypoints[1]) IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1]) gui = GenericDialog("Rotation Angle") gui.addNumericField("Choose Angle", 15, 0) gui.showDialog() if gui.wasOKed(): rotateangle = gui.getNextNumber() IJ.run("Rotate...", "angle=" + str(int(float(rotateangle)))) rm.runCommand("reset") overlay = imp.getOverlay() rm.runCommand("Add") roi_points = rm.getRoisAsArray() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints print(xpoints, ypoints) print('Rotated Start Landmark', xpoints[0], ypoints[0]) print('Rotated End Landmark', xpoints[1], ypoints[1]) slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20) intercept = fixedpointY - slope * fixedpointX print(fixedpointX, fixedpointY) print('Slope', slope, 'Intercept', intercept) XwY0 = -intercept / slope YxwY0 = slope * XwY0 + intercept XwYmax = (impY - intercept) / slope YxwYmax = slope * XwYmax + intercept YwX0 = intercept XywX0 = (YwX0 - intercept) / slope YwXmax = impX * slope + intercept XxwXmax = (YwXmax - intercept) / slope rm.runCommand("reset") if XwY0 > 0: lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0) lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax) overlay.add(lineROIA) overlay.add(lineROIB) if XwY0 < 0: lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0) lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax) overlay.add(lineROIA) overlay.add(lineROIB) while cursor.hasNext(): cursor.fwd() X = cursor.getDoublePosition(0) Y = cursor.getDoublePosition(1) if abs(Y - slope * X - intercept) <= 4: cursor.get().set(0) else: cursor.get().set(1) labeling = ops.labeling().cca(maskimage, StructuringElement.EIGHT_CONNECTED) # get the index image (each object will have a unique gray level) labelingIndex = labeling.getIndexImg() dataImg = ds.create(labelingIndex) location = ls.resolve( str(savedir) + '/' + file_name + '.' + file_type_image) dio.save(dataImg, location) imp.close()
def getRois(mask): mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE) composite = ThresholdToSelection().convert(mask) rois = ShapeRoi(composite).getRois() return rois def getRoi(mask): mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE) roi = ThresholdToSelection().convert(mask) return roi imp = IJ.getImage() cal = imp.getCalibration() ol = Overlay() proj_sca1 = maxProject(imp, channel_sca1) proj_hoescht = maxProject(imp, channel_hoescht) proj_opn = maxProject(imp, channel_opn) proj_gfp = maxProject(imp, channel_gfp) mask_sca1 = mask2D(proj_sca1, 1.0 / cal.pixelWidth, 6, AutoThresholder.Method.Otsu, min_sca1, False, False) #surrounding lumen mask_hoescht = mask2D(proj_hoescht, 1.5 / cal.pixelWidth, 5, AutoThresholder.Method.Otsu, min_hoescht, True, True) #Hoescht mask_opn = mask2D(proj_opn, 1.0 / cal.pixelWidth, 0, AutoThresholder.Method.MaxEntropy, min_opn, False, False) #surrounding lumen fragments
# Modifications # Date Who Ver What # ---------- --- ------ ------------------------------------------------- # 2014-11-25 JRM 1.1.00 Jython version of Create_Overlay.js from org.python.core import codecs codecs.setDefaultEncoding('utf-8') from ij import IJ, ImagePlus, WindowManager from ij.gui import Roi, TextRoi, Overlay, OvalRoi, Line, PolygonRoi from java.awt import Color, Font imp = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif") # create an overlay ol = Overlay() fnt = Font("SanSerif", Font.BOLD, 28) roi = TextRoi(10, 5, "This is an overlay", fnt) roi.setStrokeColor(Color.yellow) roi.setFillColor(Color(0,0,0,0.5)) ol.add(roi) roi = Roi(30,70,200,150) roi.setStrokeColor(Color.blue) roi.setFillColor(Color(0,0,1,0.3)) ol.add(roi) roi = OvalRoi(60,60,140,140) roi.setStrokeColor(Color.green) roi.setStrokeWidth(15) ol.add(roi)