def showimage(self): roim = RoiManager.getInstance() if roim is None: roim = RoiManager() IJ.run("Close All") IJ.run("Clear Results") try: roim.reset() except AttributeError: roim.runCommand("reset") obj = self.fcsimages[self.idximg][0] imgName = self.fcsimages[self.idximg][1] img = BF.openImagePlus(imgName)[0] img.setZ(obj[1][2]+1) img.setC(3) IJ.run(img, "Grays", ""); img.setC(1) img.show() #draw rois for i in range(1, len(obj)+1): PR = PointRoi(obj[i][0],obj[i][1]) try: PR.setSize(3) PR.setPointType(0) roim.addRoi(PR) except: roim.addRoi(PR) roim.runCommand('Show All with Labels')
def getSpots(imp, channel, detector_type, radius, threshold, overlay, roi_type="large", roi_color=ColorRGB("blue")): """ Performs the detection, adding spots to the image overlay :imp: The image (ImagePlus) being analyzed :channel: The target channel :detector_type: A string describing the detector: "LoG" or "DoG" :radius: Spot radius (NB: trackmate GUI accepts diameter) :threshold: Quality cutoff value :overlay: The image overlay to store spot (MultiPoint) ROIs :roi_type: A string describing how spot ROIs should be displayed :returns: The n. of detected spots """ settings = Settings() settings.setFrom(imp) settings.detectorFactory = (LogDetectorFactory() if "LoG" in detector_type else DogDetectorFactory()) settings.detectorSettings = { DK.KEY_DO_SUBPIXEL_LOCALIZATION: False, DK.KEY_DO_MEDIAN_FILTERING: True, DK.KEY_TARGET_CHANNEL: channel, DK.KEY_RADIUS: radius, DK.KEY_THRESHOLD: threshold, } trackmate = TrackMate(settings) if not trackmate.execDetection(): lservice.error(str(trackmate.getErrorMessage())) return 0 model = trackmate.model spots = model.getSpots() count = spots.getNSpots(False) ch_id = "Spots Ch%d" % channel if count > 0: roi = None cal = imp.getCalibration() t_pos = imp.getT() if (t_pos > 1): lservice.warn("Only frame %d was considered..." % t_pos) for spot in spots.iterable(False): x = cal.getRawX(spot.getFeature(spot.POSITION_X)) y = cal.getRawY(spot.getFeature(spot.POSITION_Y)) z = spot.getFeature(spot.POSITION_Z) if z == 0 or not cal.pixelDepth or cal.pixelDepth == 0: z = 1 else: z = int(z // cal.pixelDepth) imp.setPosition(channel, z, t_pos) if roi is None: roi = PointRoi(int(x), int(y), imp) else: roi.addPoint(imp, x, y) roi.setStrokeColor(colorRGBtoColor(roi_color)) if "large" in roi_type: roi.setPointType(3) roi.setSize(4) else: roi.setPointType(2) roi.setSize(1) overlay.add(roi, ch_id) return count
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 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 process_img(img_path): IJ.log('Processing {} ...'.format(img_path)) # open image imp = IJ.openImage(img_path) imp.show() w_big = imp.getWindow() w_big.setLocationAndSize(1050, 400, 500, 500) # read relative csv file rows (coordinates of centers) img_name, img_extension = os.path.splitext(img_path) marker_path = img_name + '.csv' if not os.path.exists(marker_path): root = os.path.dirname(marker_path) IJ.log('Creating corrected CSV files in {}...'.format(root)) mrk.markers_to_csv(root, y_inv_height=imp.height) markers = mrk.read_marker(marker_path, to_int=True) for cs in gen_cell_stacks(imp, markers, cube_roi_dim, scaleZ): # identify cell in original image imp.setSlice(cs.seed[2] + 1) point = PointRoi(cs.seed[0], cs.seed[1]) point.setSize(3) point.setColor(Color.RED) imp.setRoi(point) if discard_margin_cells: if not cs.onBorder: process_cell(cs) else: IJ.log('Skipped on border cell in seed ' + str(cs.seed)) else: process_cell(cs) c = raw_input( "Press enter to show the next cell or 'n' to go to the next image\n" ) cs.close() if c == 'n': IJ.log("Skipped remaining cells") break
def updatePointRoi(self): # Surround with try/except to prevent blocking # ImageJ's stack slice updater thread in case of error. try: # Update PointRoi self.imp.killRoi() point = self.nuclei[self.imp.getFrame()] # map 1-based slices # to 0-based nuclei Z coords if len(point) == 0: return IJ.log("Cell found in frame " + str(self.imp.getFrame())) # New empty PointRoi for the current slice roi = PointRoi(point[0], point[1]) # Style: large, red dots roi.setSize(4) # ranges 1-4 roi.setPointType(2) # 2 is a dot (filled circle) roi.setFillColor(Color.red) roi.setStrokeColor(Color.red) self.imp.setRoi(roi) except: IJ.error(sys.exc_info())
def updatePointRoi(self): # Surround with try/except to prevent blocking # ImageJ's stack slice updater thread in case of error. try: # Update PointRoi self.imp.killRoi() points = self.nuclei[ self.imp.getSlice() - 1] # map 1-based slices to 0-based nuclei Z coords if 0 == len(points): IJ.log("No points for slice " + str(self.imp.getSlice())) return roi = PointRoi() # Style: large, red dots roi.setSize(4) # ranges 1-4 roi.setPointType(2) # 2 is a dot (filled circle) roi.setFillColor(Color.red) roi.setStrokeColor(Color.red) # Add points for point in points: # points are floats roi.addPoint(self.imp, int(point[0]), int(point[1])) self.imp.setRoi(roi) except: IJ.error(sys.exc_info())
xmlfile = arg[0] ch = 1 #open xml file and parse it tree = ET.parse(xmlfile) root = tree.getroot() obj, imgName = getPosition(root) print imgName #open image img = BF.openImagePlus(imgName)[0] img.setZ(obj[1][2]+1) img.setC(int(ch)) img.show() #draw rois for i in range(1, len(obj)+1): PR = PointRoi(obj[i][0],obj[i][1]) try: PR.setSize(3) PR.setPointType(0) roim.addRoi(PR) except: roim.addRoi(PR) roim.runCommand('Show All with Labels')
def run(): mask_ip = impSkel.getProcessor() part_ip = impPart.getProcessor() if not mask_ip.isBinary(): error(impSkel.getTitle() + " is not a binary mask.") return # Mask grayscale image and skeletonize mask try: mask_pixels = mask_ip.getPixels() part_pixels = part_ip.getPixels() for i in xrange(len(part_pixels)): if mask_pixels[i] == 0: part_pixels[i] = 0 part_ip.setPixels(part_pixels) except IndexError: error("Chosen images are not the same size.") skeletonize(impSkel) # Get skeleton features end_points, junctions, junction_voxels, total_len = skeleton_properties(impSkel) if not end_points and not junction_voxels: error(impSkel.getTitle() + " does not seem a valid skeleton.") return # Retrieve centroids from IJ1 threshold_lower = get_threshold(impPart, thres_method) cx, cy, n_particles = get_centroids(impPart, threshold_lower) if None in (cx, cy): error("Verify parameters: No particles detected.") return # Loop through each centroids and categorize its position # according to its distance to skeleton features n_bp = n_tip = n_none = n_both = 0 overlay = cleanse_overlay(impPart.getOverlay()) for i in range(n_particles): j_dist = ep_dist = sys.maxint # Retrieve the distance between this particle and the closest junction voxel for jvoxel in junction_voxels: dist = distance(cx[i], cy[i], jvoxel.x, jvoxel.y) if (dist <= cutoff_dist and dist < j_dist): j_dist = dist # Retrieve the distance between this particle and the closest end-point for end_point in end_points: dist = distance(cx[i], cy[i], end_point.x, end_point.y) if (dist <= cutoff_dist and dist < ep_dist): ep_dist = dist roi_id = str(i).zfill(len(str(n_particles))) roi_name = "Unknown:" + roi_id roi_color = Color.ORANGE roi_type = 2 # dot # Is particle associated with neither junctions nor end-points? if j_dist > cutoff_dist and ep_dist > cutoff_dist: roi_name = "Unc:" + roi_id #n_none += 1 # Is particle associated with both? elif abs(j_dist - ep_dist) <= pixel_size(impPart) / 2: roi_name = "J+T:" + roi_id roi_color = Color.CYAN #roi_type = 1 # crosshair n_both += 1 # Is particle associated with an end-point? elif ep_dist < j_dist: roi_name = "Tip:" + roi_id roi_color = Color.GREEN #roi_type = 0 # hybrid n_tip += 1 # Is particle associated with a junction? elif ep_dist > j_dist: roi_name = "Junction:" + roi_id roi_color = Color.MAGENTA #roi_type = 3 # circle n_bp += 1 roi = PointRoi(cx[i], cy[i]) roi.setName(roi_name) roi.setStrokeColor(roi_color) roi.setPointType(roi_type) roi.setSize(2) # medium overlay.add(roi) # Display result impSkel.setOverlay(overlay) impPart.setOverlay(overlay) # Output some measurements if "table" in output: t = ResultsTable.getResultsTable() if "IJ1" in output else DefaultGenericTable() addToTable(t, "Part. image", "%s (%s)" % (impPart.getTitle(), impPart.getCalibration().getUnits())) addToTable(t, "Skel. image", "%s (%s)" % (impSkel.getTitle(), impSkel.getCalibration().getUnits())) addToTable(t, "Junction particles", n_bp) addToTable(t, "Tip particles", n_tip) addToTable(t, "J+T particles", n_both) addToTable(t, "Unc. particles", n_none) addToTable(t, "Junctions w/ particles", n_bp + n_both) addToTable(t, "Tips w/ particles", n_tip + n_both) addToTable(t, "Total skel. lenght", total_len) addToTable(t, "Total end points", len(end_points)) addToTable(t, "Total junctions", sum(junctions)) addToTable(t, "Unc. particles / Total skel. lenght)", n_none/total_len) addToTable(t, "Snap-to dist.", str(cutoff_dist) + impPart.getCalibration().getUnits()) addToTable(t, "Threshold", "%d (%s)" % (threshold_lower, thres_method)) showTable(t, "Results")