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 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())
# In the differece of gaussian peak detection, the img acts as the interval # within which to look for peaks. The processing is done on the infinite imgE. dog = DogDetection(imgE, img, calibration, sigmaSmaller, sigmaLarger, extremaType, minPeakValue, normalizedMinPeakValue) peaks = dog.getPeaks() # Create a PointRoi from the DoG peaks, for visualization roi = PointRoi(0, 0) # A temporary array of integers, one per dimension the image has p = zeros(img.numDimensions(), 'i') # Load every peak as a point in the PointRoi for peak in peaks: # Read peak coordinates into an array of integers peak.localize(p) roi.addPoint(imp, p[0], p[1]) imp.setRoi(roi) # Now, iterate each peak, defining a small interval centered at each peak, # and measure the sum of total pixel intensity, # and display the results in an ImageJ ResultTable. table = ResultsTable() for peak in peaks: # Read peak coordinates into an array of integers peak.localize(p) # Define limits of the interval around the peak: # (sigmaSmaller is half the radius of the embryo) minC = [p[i] - sigmaSmaller for i in range(img.numDimensions())] maxC = [p[i] + sigmaSmaller for i in range(img.numDimensions())]
# of each pair (PointMatch) of points. That is, to the point from # the first image. PointMatch.apply(inliers, model) except NotEnoughDataPointsException, e: print e if modelFound: # Store inlier pointmatches: the spatially coherent subset roi1pm = PointRoi() roi1pm.setName("matches in cut1") roi2pm = PointRoi() roi2pm.setName("matches in cut2") for pm in inliers: p1 = pm.getP1() roi1pm.addPoint(p1.getL()[0], p1.getL()[1]) p2 = pm.getP2() roi2pm.addPoint(p2.getL()[0], p2.getL()[1]) roi_manager.addRoi(roi1pm) roi_manager.addRoi(roi2pm) # Register images # Transform the top-left and bottom-right corner of imp2 # (use applyInverse: the model describes imp1 -> imp2) x0, y0 = model.applyInverse([0, 0]) x1, y1 = model.applyInverse([imp2.getWidth(), 0]) x2, y2 = model.applyInverse([0, imp2.getHeight()]) x3, y3 = model.applyInverse([imp2.getWidth(), imp2.getHeight()]) xtopleft = min(x0, x1, x2, x3) ytopleft = min(y0, y1, y2, y3)
def process(srcDir, dstDir, currentDir, fileName, keepDirectories, Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist): IJ.run("Close All", "") # Opening the image IJ.log("Open image file:" + fileName) #imp = IJ.openImage(os.path.join(currentDir, fileName)) #imp = IJ.getImage() imp = BF.openImagePlus(os.path.join(currentDir, fileName)) imp = imp[0] # getDimensions(width, height, channels, slices, frames) IJ.log("Computing Max Intensity Projection") if imp.getDimensions()[3] > 1: imp_max = ZProjector.run(imp,"max") else: imp_max = imp ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2) IJ.log("Substract background") imp1, imp2 = back_substraction(ip1, ip2, radius_background) IJ.log("Finding Peaks") ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue) # Create a PointRoi from the DoG peaks, for visualization roi_1 = PointRoi(0, 0) roi_2 = PointRoi(0, 0) roi_3 = PointRoi(0, 0) roi_4 = PointRoi(0, 0) # A temporary array of integers, one per dimension the image has p_1 = zeros(ip1_1.numDimensions(), 'i') p_2 = zeros(ip2_1.numDimensions(), 'i') # Load every peak as a point in the PointRoi for peak in peaks_1: # Read peak coordinates into an array of integers peak.localize(p_1) roi_1.addPoint(imp1, p_1[0], p_1[1]) for peak in peaks_2: # Read peak coordinates into an array of integers peak.localize(p_2) roi_2.addPoint(imp2, p_2[0], p_2[1]) # Chose minimum distance in pixel #min_dist = 20 for peak_1 in peaks_1: peak_1.localize(p_1) for peak_2 in peaks_2: peak_2.localize(p_2) d1 = distance(p_1, p_2) if d1 < min_dist: roi_3.addPoint(imp1, p_2[0], p_2[1]) break for peak_2 in peaks_2: peak_2.localize(p_2) for peak_1 in peaks_1: peak_1.localize(p_1) d2 = distance(p_2, p_1) if d2 < min_dist: roi_4.addPoint(imp1, p_2[0], p_2[1]) break cal = imp.getCalibration() min_distance = str(round((cal.pixelWidth * min_dist),1)) table = ResultsTable() table.incrementCounter() table.addValue("Numbers of Neuron Markers", roi_1.getCount(0)) table.addValue("Numbers of Glioma Markers", roi_2.getCount(0)) table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0)) table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0)) #table.show("Results Analysis") saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) IJ.log("Saving to" + saveDir) table.save(os.path.join(saveDir, fileName + ".csv")) IJ.selectWindow("Log") IJ.saveAs("Text", os.path.join(saveDir, fileName + ".csv"));
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"))
# In the differece of gaussian peak detection, the img acts as the interval # within which to look for peaks. The processing is done on the infinite imgE. dog = DogDetection(imgE, img, calibration, sigmaSmaller, sigmaLarger, extremaType, minPeakValue, normalizedMinPeakValue) peaks = dog.getSubpixelPeaks() # Create a PointRoi from the DoG peaks, for visualization roi = PointRoi(0, 0) # A temporary array of integers, one per dimension the image has p = zeros(img.numDimensions(), 'd') # Load every peak as a point in the PointRoi for peak in peaks: # Read peak coordinates into an array of integers peak.localize(p) roi.addPoint(imp, int(p[0]), int(p[1])) imp.setRoi(roi) # Now, iterate each peak, defining a small interval centered at each peak, # and measure the sum of total pixel intensity, # and display the results in an ImageJ ResultTable. table = ResultsTable() for peak in peaks: # Read peak coordinates into an array of integers peak.localize(p) # Define limits of the interval around the peak: # (sigmaSmaller is half the radius of the embryo) minC = [int(p[i] - sigmaSmaller) for i in xrange(img.numDimensions())] maxC = [int(p[i] + sigmaSmaller) for i in xrange(img.numDimensions())]
def run(): IJ.run("Close All", "") IJ.log("\\Clear") IJ.log("Find_close_peaks") imp = IJ.run("Bio-Formats Importer") imp = IJ.getImage() Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist = getOptions() IJ.log("option used:" \ + "\n" + "channel 1:" + str(Channel_1) \ + "\n" + "channel 2:"+ str(Channel_2) \ + "\n" + "Radius Background:"+ str(radius_background) \ + "\n" + "Smaller Sigma:"+ str(sigmaSmaller) \ + "\n" + "Larger Sigma:"+str(sigmaLarger) \ + "\n" + "Min Peak Value:"+str(minPeakValue) \ + "\n" + "Min dist between peaks:"+str(min_dist)) IJ.log("Computing Max Intensity Projection") if imp.getDimensions()[3] > 1: imp_max = ZProjector.run(imp,"max") #imp_max = IJ.run("Z Project...", "projection=[Max Intensity]") #imp_max = IJ.getImage() else: imp_max = imp ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2) imp1, imp2 = back_substraction(ip1, ip2, radius_background) imp1.show() imp2.show() IJ.log("Finding Peaks") ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue) # Create a PointRoi from the DoG peaks, for visualization roi_1 = PointRoi(0, 0) roi_2 = PointRoi(0, 0) roi_3 = PointRoi(0, 0) roi_4 = PointRoi(0, 0) # A temporary array of integers, one per dimension the image has p_1 = zeros(ip1_1.numDimensions(), 'i') p_2 = zeros(ip2_1.numDimensions(), 'i') # Load every peak as a point in the PointRoi for peak in peaks_1: # Read peak coordinates into an array of integers peak.localize(p_1) roi_1.addPoint(imp1, p_1[0], p_1[1]) for peak in peaks_2: # Read peak coordinates into an array of integers peak.localize(p_2) roi_2.addPoint(imp2, p_2[0], p_2[1]) # Chose minimum distance in pixel #min_dist = 20 for peak_1 in peaks_1: peak_1.localize(p_1) for peak_2 in peaks_2: peak_2.localize(p_2) d1 = distance(p_1, p_2) if d1 < min_dist: roi_3.addPoint(imp1, p_2[0], p_2[1]) break for peak_2 in peaks_2: peak_2.localize(p_2) for peak_1 in peaks_1: peak_1.localize(p_1) d2 = distance(p_2, p_1) if d2 < min_dist: roi_4.addPoint(imp1, p_2[0], p_2[1]) break rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() rm.addRoi(roi_1) rm.addRoi(roi_2) rm.addRoi(roi_3) rm.addRoi(roi_4) rm.select(0) rm.rename(0, "ROI neuron") rm.runCommand("Set Color", "yellow") rm.select(1) rm.rename(1, "ROI glioma") rm.runCommand("Set Color", "blue") rm.select(2) rm.rename(2, "ROI glioma touching neurons") rm.runCommand("Set Color", "red") rm.select(3) rm.rename(3, "ROI neurons touching glioma") rm.runCommand("Set Color", "green") rm.runCommand(imp1, "Show All") #Change distance to be in um cal = imp.getCalibration() min_distance = str(round((cal.pixelWidth * min_dist),1)) table = ResultsTable() table.incrementCounter() table.addValue("Numbers of Neuron Markers", roi_1.getCount(0)) table.addValue("Numbers of Glioma Markers", roi_2.getCount(0)) table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0)) table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0)) table.show("Results Analysis")