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 generate_limit_labels(imp, limits, cb_fraction, params): """generate text ROIs in correct positions to label colorbar""" rois = [] w = imp.getWidth() h = imp.getHeight() txt_h_px = float(h) / 15 txt_sz_pt = int(round((18.0 / 24.0) * txt_h_px)) for limit in limits: roi = TextRoi(1, 1, str(round(limit, 3)), Font("SansSerif", Font.ITALIC, txt_sz_pt)) roi.setJustification(TextRoi.RIGHT) roi.setFillColor(Color.BLACK) roi.setStrokeColor(Color.WHITE) rois.append(roi) roim = RoiManager(False) roim.reset() imp.show() mbui.autoset_zoom(imp) for fridx in range(1, imp.getNSlices() + 1): imp.setPosition(fridx) roi_uu = rois[1].clone() xpos = w - cb_fraction * w - float(w) / 100 - rois[1].getFloatWidth() roi_uu.setLocation(xpos, 1) imp.setRoi(roi_uu) roim.addRoi(roi_uu) roi_ll = rois[0].clone() roi_ll.setLocation(xpos, h - rois[0].getFloatHeight()) imp.setRoi(roi_ll) roim.addRoi(roi_ll) roim.runCommand("Show All") FileSaver(imp).saveAsTiff( os.path.join(params.output_path, "overlaid curvature nudged labels.tif")) # nudge positions roim.reset() imp.killRoi() for fridx in range(1, imp.getNSlices() + 1): imp.setPosition(fridx) roi_uu = rois[1].clone() xpos = w - cb_fraction * w - float(w) / 100 roi_uu.setLocation(xpos, 1) imp.setRoi(roi_uu) roim.addRoi(roi_uu) roi_ll = rois[0].clone() roi_ll.setLocation(xpos, h - rois[0].getFloatHeight()) imp.setRoi(roi_ll) roim.addRoi(roi_ll) roim.runCommand("Show All") FileSaver(imp).saveAsTiff( os.path.join(params.output_path, "overlaid curvature.tif")) return imp
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 write_roi_numbers(ov, corners, L): roiID = 1 for [x, y] in corners: text = TextRoi(x, y, L, L, str(roiID), Font("Arial", Font.PLAIN, 400)) text.setJustification(1) text.setColor(Color.RED) ov.add(text) roiID += 1 return ov
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 write_roi_numbers(ov, corners, L): fontsize = int(L / 1.5) roiID = 1 for [x, y] in corners: text = TextRoi(x, y, L, L, str(roiID), Font("Arial", Font.BOLD, fontsize)) text.setJustification(2) text.setColor(Color.RED) ov.add(text) roiID += 1 return ov
rt = ResultsTable.getResultsTable() celli = 0 FONT = Font(Font.SANS_SERIF, Font.BOLD, 16) for cell in cells_hoescht_opn: area = cell.getStatistics().area * cal.pixelWidth * cal.pixelHeight if area >= MINA and area <= MAXA: cell.setStrokeColor(Color.MAGENTA) ol.add(cell) edm_sca1_gfp.setRoi(cell) dist = edm_sca1_gfp.getStatistics().mean * cal.pixelWidth row = rt.getCounter() rect = cell.getBounds() rt.setValue("Image", row, imp.getTitle()) rt.setValue("OPN+ Cell", row, celli) rt.setValue("X", row, (rect.x + rect.width / 2.0) * cal.pixelWidth) rt.setValue("Y", row, (rect.y + rect.height / 2.0) * cal.pixelHeight) rt.setValue( "OPN+ cell distance from SCA1+ GFP+ (" + u"\u00b5" + "m" + ")", row, dist) label = TextRoi(rect.x, rect.y - 16, str(celli), FONT) label.setStrokeColor(Color.MAGENTA) ol.add(label) celli += 1 rt.show("Results") imp.setOverlay(ol)
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"); # Saves the output file. IJ.saveAs(imp,"png",hyperspaceImage)
gfpSum += roiStatsGfp.mean * roiStatsGfp.area gfp.setStrokeColor(Color.MAGENTA) gfp.setPosition(0, z, 1) ol.add(gfp) gfpMean = gfpSum / gfpA if gfpA > 0 else 0 row = rt.getCounter() uni = row % 26 cha = chr(ord('A') + uni) name = "" while len(name) < (row + 1) / 26.0: name += cha label = TextRoi(name, cXbf - 20, cYbf + 20, FONT) label.setStrokeColor(Color.GREEN) label.setPosition(0, z, 1) ol.add(label) rt.setValue("Organoid", row, name) rt.setValue("X", row, cXbf * cal.pixelWidth) rt.setValue("Y", row, cYbf * cal.pixelHeight) rt.setValue("Area", row, roiStatsBF.area * cal.pixelWidth * cal.pixelHeight) rt.setValue("Contained Tomato Area", row, tomatoA * cal.pixelWidth * cal.pixelHeight) rt.setValue("Contained GFP Area", row, gfpA * cal.pixelWidth * cal.pixelHeight) rt.setValue("Contained GFP Mean", row, gfpMean)
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")
# ---------- --- ------ ------------------------------------------------- # 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) roi = Line(30,70,230,230)