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 draw_centers(data): pathname = data[1] filename = data[2] platename = data[3] print data[4] nx = int(data[4]) ny = int(data[5]) nx_com = int(data[6]) ny_com = int(data[7]) ax = int(data[8]) ay = int(data[9]) orientation = 2*math.pi * float(data[10]) / 360.0 line_dy = int(round(math.atan(orientation) * LINE_DX)) ax2 = ax - LINE_DX ay2 = ay - line_dy orientation_avg = 2*math.pi * float(data[11]) / 360.0 line_dy = int(round(math.atan(orientation_avg) * LINE_DX)) ax3 = ax - LINE_DX ay3 = ay - line_dy imp = IJ.openImage(os.path.join(pathname,filename)) roi_nucleus = PointRoi(nx,ny) roi_nucleus.setDefaultMarkerSize("Large") roi_nucleus.setStrokeColor(Color.CYAN) roi_nucleus_com = PointRoi(nx_com,ny_com) roi_nucleus_com.setDefaultMarkerSize("Large") roi_nucleus_com.setStrokeColor(Color.GREEN) roi_anchor = PointRoi(ax,ay) roi_anchor.setDefaultMarkerSize("Large") imp.getProcessor().drawRoi(roi_nucleus) imp.getProcessor().drawRoi(roi_nucleus_com) imp.getProcessor().drawRoi(roi_anchor) imp.setColor(Color.RED) imp.getProcessor().drawLine(ax,ay,ax2,ay2) imp.setColor(Color.WHITE) imp.getProcessor().drawLine(ax,ay,ax3,ay3) IJ.saveAsTiff(imp,os.path.join(pathname,filename))
def draw_classes(inputfile,data): pathname,filename = os.path.split(inputfile) # last subdir is for well ## TODO ## support multiple plates, read plate and well from csv well = os.path.basename(pathname) # create output directory outputdir = os.path.join(OUTPUTROOT,well) if not os.path.isdir(outputdir): os.makedirs(outputdir) # create output filename head,tail = os.path.splitext(filename) outputfilename = head + "_classes" + tail outputfilename = os.path.join(outputdir,outputfilename) print outputfilename imp = IJ.openImage(inputfile).duplicate() IJ.run(imp,"RGB Color","") for d in data: x = int(float(d[0])) y = int(float(d[1])) c = int(float(d[2])) classname = classes[str(c)] colorname = colors[classname] color = colormap[colorname] #print colorname roi = PointRoi(x,y) roi.setDefaultMarkerSize("Large") roi.setStrokeColor(colormap[colorname]) imp.getProcessor().drawRoi(roi) IJ.saveAs(imp,"png",outputfilename)
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 findEndPoints(imageID, maskID): endPoints1 = [] endPoints2 = [] imp = IJ.getImage() imp.setSlice(1); roiManager = RoiManager.getInstance2() rois = roiManager.getRoisAsArray() roisToBeRemoved = [] index = 0 for roi in rois: outerBounds = roi.getBounds() impMT, innerBounds = duplicateMaskInRoi(imp, roi) nr, endPoint1, endPoint2 = findEndPointsInSkeleton(impMT) if (nr==2): endPoint1.x = endPoint1.x + outerBounds.x + innerBounds.x - 1 endPoint1.y = endPoint1.y + outerBounds.y + innerBounds.y - 1 endPoint2.x = endPoint2.x + outerBounds.x + innerBounds.x - 1 endPoint2.y = endPoint2.y + outerBounds.y + innerBounds.y - 1 endPoints1.append(endPoint1) endPoints2.append(endPoint2) else: roisToBeRemoved.append(index) impMT.close() index = index + 1 if (len(roisToBeRemoved)>0): roiManager.setSelectedIndexes(roisToBeRemoved) roiManager.runCommand("Delete") roiManager.moveRoisToOverlay(WindowManager.getImage(maskID)) inputIMP = WindowManager.getImage(imageID) inputIMP.setOverlay(PointRoi([seq.x for seq in endPoints1], [seq.y for seq in endPoints1]), Color.magenta, 1, Color.magenta) otherPoints = PointRoi([seq.x for seq in endPoints2], [seq.y for seq in endPoints2]) otherPoints.setStrokeColor(Color.cyan) otherPoints.setFillColor(Color.cyan) inputIMP.getOverlay().add(otherPoints)
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())
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")
def processOneImage(inputDir): tmp = glob.glob(os.path.join(inputDir, "fibrone*")) fibronectin = tmp[0] tmp = glob.glob(os.path.join(inputDir, "nucleus*")) nucleus = tmp[0] tmp = glob.glob(os.path.join(inputDir, "actin*")) actin = tmp[0] # read sample name head,tail = os.path.split(inputDir) sample = tail.replace(".tif_Files","") # original images imp_fn_orig = IJ.openImage(fibronectin) imp_nuc_orig = IJ.openImage(nucleus) # work copies imp_fn = imp_fn_orig.duplicate() imp_nuc = imp_nuc_orig.duplicate() IJ.run(imp_fn,"Set Scale...", "distance=1 known=1 pixel=1 unit=pixels") IJ.run(imp_fn,"Gaussian Blur...","sigma=5") IJ.run(imp_fn,"Make Binary","") IJ.run(imp_nuc,"Set Scale...", "distance=1 known=1 pixel=1 unit=pixels") IJ.run(imp_nuc,"Gaussian Blur...","sigma=5") IJ.run(imp_nuc,"Make Binary","") # get moments of the fibronectin image moments_file = os.path.join(OUTPUT, sample + " moments.txt") printMoments(fibronectin, moments_file) moments = readMoments(moments_file) print moments.m00 sys.exit() # centroid of fibronectin anchor centers = getParticleCenters(imp_fn) cxfn = int(round(centers[0][0])) cyfn = int(round(centers[1][0])) fn_centroid_roi = PointRoi(cxfn,cyfn) fn_centroid_roi.setDefaultMarkerSize("Large") fn_centroid_roi.setStrokeColor(Color.CYAN) # center of mass of nucleus centers = getParticleCenters(imp_nuc) cxnuc = int(round(centers[2][0])) cynuc = int(round(centers[3][0])) nuc_com_roi = PointRoi(cxnuc,cynuc) nuc_com_roi.setDefaultMarkerSize("Large") # skeletonize fibronectin anchor to find its orientation IJ.run(imp_fn,"Skeletonize","") skel = AnalyzeSkeleton_() skel.setup("",imp_fn) skelResult = skel.run(skel.NONE, False, True, None, True, True) graph = skelResult.getGraph() print len(graph) print skelResult.getNumOfTrees() # find the longest graph graph = sorted(graph, key=lambda g: getGraphLength(g), reverse=True) graph = graph[0] edges = graph.getEdges() # find longest edge, the main axis of the anchor edges = sorted(edges, key=lambda edge: edge.getLength(), reverse=True) #for e in edges: # print e.getLength() v1long = edges[0].getV1() v2long = edges[0].getV2() x1 = v1long.getPoints()[0].x y1 = v1long.getPoints()[0].y x2 = v2long.getPoints()[0].x y2 = v2long.getPoints()[0].y anchor_roi = PointRoi(x1,y1) anchor_roi = anchor_roi.addPoint(x2,y2) # find top and bottom vertices of the graph vertices = graph.getVertices() vertices = sorted(vertices, key=lambda vertex: vertex.getPoints()[0].y) v1short = vertices[len(vertices)-1] v2short = vertices[0] x3 = v1short.getPoints()[0].x y3 = v1short.getPoints()[0].y x4 = v2short.getPoints()[0].x y4 = v2short.getPoints()[0].y anchor_roi = anchor_roi.addPoint(x3,y3) anchor_roi = anchor_roi.addPoint(x4,y4) # calculate angles a1 = math.atan(abs(float(y2-y1)/float(x2-x1))) / math.pi * 360 a2 = math.atan(abs(float(x4-x3)/float(y4-y3))) / math.pi * 360 amean = float((a1+a2)/2) dx = cxfn-cxnuc print sample,cxfn,cyfn,cxnuc,cynuc,dx,math.cos(amean)*dx,x1,y1,x2,y2,x3,y3,x4,y4,a1,a2 # create composite comp = ImagePlus("composite",imp_nuc_orig.getProcessor().convertToColorProcessor()) comp.getProcessor().setChannel(2,imp_fn_orig.getProcessor()) comp.getProcessor().setChannel(3,imp_fn.getProcessor()) comp.show() comp.getProcessor().drawRoi(fn_centroid_roi) comp.getProcessor().drawRoi(nuc_com_roi) comp.getProcessor().drawRoi(anchor_roi) comp.repaintWindow() IJ.saveAsTiff(comp, os.path.join(OUTPUT,sample + ".tif"))