def analyze(imp, min_area): MAXSIZE = 1000000000000 MINCIRCULARITY = 0.0 MAXCIRCULARITY = 1. options = PA.SHOW_MASKS temp_results = ResultsTable() p = PA(options, PA.AREA + PA.MEAN, temp_results, min_area, MAXSIZE, MINCIRCULARITY, MAXCIRCULARITY) p.setHideOutputImage(True) p.analyze(imp) if temp_results.getCounter() == 0: areas = [] signals = [] else: areas = list(temp_results.getColumn(0)) signals = list(temp_results.getColumn(1)) count = len(areas) area = sum(areas) total = 0 if area > 0: total = sum([a*s for a,s in zip(areas, signals)]) / area return p.getOutputImage(), count, area, total
def run_straighten(roiWindowsize=4): """ Original straightening function based on Nick's macro. Used in final version. Returns coordinate string used to make centerline. """ IJ.run("Set Measurements...", "mean min center redirect=None decimal=3") IJ.runMacro("//setTool(\"freeline\");") IJ.run("Line Width...", "line=80") numPoints = 512 / roiWindowsize xvals = [] yvals = [] maxvals = [] counter = 0 for i in range(0, 512, roiWindowsize): IJ.run("Clear Results") IJ.makeRectangle(i, 0, roiWindowsize, 512) IJ.run("Measure") table = RT.getResultsTable() xvals.append(i + roiWindowsize / 2) yvals.append(RT.getValue(table, "YM", 0)) maxvals.append((RT.getValue(table, "Max", 0))) if maxvals[counter] == 0 and counter > 0: yvals[counter] = yvals[counter - 1] counter += 1 coords = "" for i in range(numPoints - 1): coords += str(xvals[i]) + ", " + str(yvals[i]) + ", " coords += str(xvals[numPoints - 1]) + ", " + str(yvals[numPoints - 1]) IJ.runMacro("makeLine(" + coords + ")") IJ.run("Straighten...", "line = 80") return coords
def run_straighten(roiWindowsize = 4): """ Original straightening function based on Nick's macro. Used in final version. Returns coordinate string used to make centerline. """ IJ.run("Set Measurements...", "mean min center redirect=None decimal=3") IJ.runMacro("//setTool(\"freeline\");") IJ.run("Line Width...", "line=80"); numPoints = 512/roiWindowsize xvals = [] yvals = [] maxvals = [] counter = 0 for i in range(0, 512, roiWindowsize): IJ.run("Clear Results") IJ.makeRectangle(i, 0, roiWindowsize, 512) IJ.run("Measure") table = RT.getResultsTable() xvals.append(i + roiWindowsize/2) yvals.append(RT.getValue(table, "YM", 0)) maxvals.append((RT.getValue(table, "Max", 0))) if maxvals[counter] == 0 and counter > 0: yvals[counter] = yvals[counter - 1] counter += 1 coords = "" for i in range(numPoints - 1): coords += str(xvals[i]) + ", " + str(yvals[i]) +", " coords += str(xvals[numPoints-1]) + ", " + str(yvals[numPoints-1]) IJ.runMacro("makeLine("+coords+")") IJ.run("Straighten...", "line = 80") return coords
def containsRoot_(self): IJ.run("Clear Results") IJ.run("Measure") table = RT.getResultsTable() if RT.getValue(table, "Max", 0) == 0: return False return True
def measure_growth(imgDir, filename = "Fiji_Growth.txt"): """ Collects measurement data in pixels and writes to a file. Uses straightened binary images""" f = open(imgDir + filename, 'w') f.write("Img number\tEnd point (pixels)\n") IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3") index = "000000000" filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif" while path.exists(filename): imp = IJ.openImage(filename) imp.show() IJ.run("Clear Results") for i in xrange(800): #hard coded to target length for now IJ.makeRectangle(i, 0, 1, 80) IJ.run("Measure") table = RT.getResultsTable() #print "i:", i, "counter:", table.getCounter() maxi = RT.getValue(table, "Max", i) if maxi == 0: f.write(str(int(index)) + "\t" + str(i) + "\n") break IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}") index = to_9_Digits(str(int(index)+1)) filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif" f.close()
def anaParticles(imp, minSize, maxSize, minCirc, bHeadless=True): """anaParticles(imp, minSize, maxSize, minCirc, bHeadless=True) Analyze particles using a watershed separation. If headless=True, we cannot redirect the intensity measurement to the original immage becuae it is never displayed. If we display the original, we can and get the mean gray level. We may then compute the particle contrast from the measured Izero value for the image. No ability here to draw outlines on the original.""" strName = imp.getShortTitle() imp.setTitle("original") ret = imp.duplicate() IJ.run(ret, "Enhance Contrast", "saturated=0.35") IJ.run(ret, "8-bit", "") IJ.run(ret, "Threshold", "method=Default white") IJ.run(ret, "Watershed", "") rt = ResultsTable() # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3" # N.B. redirect will not work without a displayed image, so we cannot use a gray level image if bHeadless == True: strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3" else: imp.show() strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3" IJ.run("Set Measurements...", strSetMeas) # note this doies not get passed directly to ParticleAnalyzer, so # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt # measurements=27355 # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS # didn't work reliably meas = 27355 pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0); pa.analyze(ret); rt.createTableFromImage(ret.getProcessor()) return [ret, rt]
def containsRoot_(self): IJ.run("Clear Results") IJ.run("Measure") table = RT.getResultsTable() if RT.getValue(table, "Max", 0) == 0: return False return True
def pixel_collector(rm, channel_imp, channel_name, impname, folder): # define new Results table rt = ResultsTable() IndRois = rm.getIndexes() for index in IndRois: ROI = rm.getRoi(index) ROI_name = ROI.getName() coords = ROI.getContainedPoints() row = 0 for pixel in coords: x_coord = pixel.getX() y_coord = pixel.getY() rt.setValue(ROI_name + "_X_pos", row, int(x_coord)) rt.setValue(ROI_name + "_Y_pos", row, int(y_coord)) pixel_2 = channel_imp.getProcessor().getPixel( int(x_coord), int(y_coord)) rt.setValue(ROI_name + "_" + channel_name, row, pixel_2) row = row + 1 rt.show("Results") rt.save(os.path.join(folder, impname + '_' + channel_name + "_pixels.csv")) print "Pixel collection done!"
def measure_growth(imgDir, filename="Fiji_Growth.txt"): """ Collects measurement data in pixels and writes to a file. Uses straightened binary images""" f = open(imgDir + filename, 'w') f.write("Img number\tEnd point (pixels)\n") IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3") index = "000000000" filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif" while path.exists(filename): imp = IJ.openImage(filename) imp.show() IJ.run("Clear Results") for i in xrange(800): #hard coded to target length for now IJ.makeRectangle(i, 0, 1, 80) IJ.run("Measure") table = RT.getResultsTable() #print "i:", i, "counter:", table.getCounter() maxi = RT.getValue(table, "Max", i) if maxi == 0: f.write(str(int(index)) + "\t" + str(i) + "\n") break IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}") index = to_9_Digits(str(int(index) + 1)) filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif" f.close()
def new_Table(): """Creates a new ResultsTable padded with float("nan"), ie, all empty cells will be filled with Java's String.valueOf(Double.NaN) """ new_rt = RT() new_rt.setNaNEmptyCells(True); new_rt.showRowNumbers(False); return new_rt
def geometrical_measure_3D(imp_label): # remove results table if exists: close_non_image_window("Results") # measure #imp_label.show() rt = ResultsTable.getResultsTable() IJ.run(imp_label, "3D Geometrical Measure", ""); rt = ResultsTable.getResultsTable() return rt
def geometrical_measure_3D(imp_label): # remove results table if exists: close_non_image_window("Results") # measure #imp_label.show() rt = ResultsTable.getResultsTable() IJ.run(imp_label, "3D Geometrical Measure", ""); rt = ResultsTable.getResultsTable() return rt
def writeCSV(filePath, results, header): """ Write a table as an csv file """ rt = ResultsTable() for i in range(len(results[1])): rt.incrementCounter() for j in range(len(results)): rt.addValue(str(header[j]), results[j][i]) rt.show("Results") rt.saveAs(filePath)
def showRoiSummary(table): res=ResultsTable() for i,val in table.items(): res.setValue('id',i,i+1) valInd=val.keys() valInd.remove('Class') for ind in valInd: res.setValue(ind,i,val[ind]) res.setValue('Class',i,val['Class']) res.show('[ROI Summary]'+imgName)
def writeCSV(filePath, results, header): """ Write a table as an csv file """ rt = ResultsTable() for i in range(len(results[1])): rt.incrementCounter() for j in range(len(results)): rt.addValue(str(header[j]), results[j][i]) rt.show("Results") rt.saveAs(filePath);
def measure(self): imp = IJ.openImage(self.filename) IJ.log("Input file: %s" % self.filename) ImageConverter(imp).convertToGray8() res = Auto_Threshold().exec(imp, self.myMethod, self.noWhite, self.noBlack, self.doIwhite, self.doIset, self.doIlog, self.doIstackHistogram) rt = ResultsTable() rt.showRowNumbers(False) pa = PA(self.options, PA.AREA + PA.PERIMETER + PA.CIRCULARITY, rt, self.MINSIZE, self.MAXSIZE) pa.analyze(imp) self.result = self.rtToResult(rt) self.mask = imp
def __localwand(self, x, y, ip, seuil, method, light): self.__image.killRoi() ip.snapshot() if method == "mean" : peak=ip.getPixel(x,y) tol = (peak - self.getMean())*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) #print "method=", method, tol, peak elif method == "background" : radius = self.getMinF()/4 bs = BackgroundSubtracter() #rollingBallBackground(ImageProcessor ip, double radius, boolean createBackground, boolean lightBackground, boolean useParaboloid, boolean doPresmooth, boolean correctCorners) bs.rollingBallBackground(ip, radius, False, light, False, True, False) peak=ip.getPixel(x,y) tol = peak*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) ip.reset() #print "method=", method, tol, radius, peak else : peak=ip.getPixel(x,y) tol = peak*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) #print "method=", method, tol peak=ip.getPixel(x,y) temproi=PolygonRoi(w.xpoints, w.ypoints, w.npoints, PolygonRoi.POLYGON) self.__image.setRoi(temproi) #self.__image.show() #time.sleep(1) #peakip=self.__image.getProcessor() #stats=peakip.getStatistics() temprt = ResultsTable() analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.INTEGRATED_DENSITY+Analyzer.FERET, temprt) analyser.measure() #temprt.show("temprt") rtValues=temprt.getRowAsString(0).split("\t") area=float(rtValues[1]) intDen=float(rtValues[4]) feret=float(rtValues[2]) mean=intDen/area #time.sleep(2) temprt.reset() self.__image.killRoi() return [peak, area, mean, intDen, feret]
def process(inputpath, outputpath): imp = IJ.openImage(inputpath) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) IJ.setThreshold(imp, t1, 255) #imp.show() #WaitForUserDialog("Title", "Look at image").show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager table = ResultsTable() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 50, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) imp.changes = False imp.close() areas = table.getColumn(0) summary = {} if areas: summary['Image'] = filename summary['Nuclei.count'] = len(areas) summary['Area.Covered'] = sum(areas) fieldnames = list(summary.keys()) with open(outputpath, 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', lineterminator='\n') if os.path.getsize(outputDirectory + "/" + outputname + ".csv") < 1: writer.writeheader() writer.writerow(summary)
def measure_roi_set(roi_set, imp, set_measure=MEAS_ALL) : """requires imp because it won't measure without one note.. side effects: ResultsTable and RoiManager cleared""" # imp.show() rt = ResultsTable.getResultsTable() rt.reset() rm = RoiManager.getRoiManager() rm.reset() if roi_set is not None : for roi in roi_set : add_roi(roi) rm.setSelectedIndexes([x for x in range(rm.getCount())]) setMeasurementInt(set_measure) print("before rm measure") # IJ.setActiveImage(imp) # IJ.selectWindow(imp.getTitle()) # imp.show() try : # input() # for roi in roi_set : # imp. rm.runCommand(imp, "Measure") except : input() print("after rm measure") results = rt_to_col_dict() # imp.hide() return results
def delete(imp, roiMan, roiTotal): # set results table rt = ResultsTable.getResultsTable() # set up analyzer analyzer = Analyzer(imp, 1, rt) totalPixels = 0 # Set the color and line options for erasing IJ.run("Colors...", "foreground=black background=black selection=magenta") if roiMan is not None: # Iterate through the ROIs for roi in xrange(roiTotal): # Select the ROI roiMan.select(roi) selectRoi = roiMan.getRoi(roi) # measure analyzer.measure() meas = rt.getRowAsString(0) newLine = meas.split(" ", 1) pixels = float(newLine[1]) totalPixels = totalPixels + pixels # Tag the ROI IJ.run(imp, "Fill", "slice") # end for loop return totalPixels else: return 0
def run(): global srcFile, ext, numberOfWidthMeasurements IJ.run("Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction display redirect=None decimal=3"); IJ.setForegroundColor(255,255,255); IJ.setBackgroundColor(0,0,0); IJ.run("Options...", "iterations=1 count=1 black"); table = ResultsTable() srcDir = srcFile.getAbsolutePath() for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Check for file extension if not filename.endswith(ext): continue # Check for file name pattern process(srcDir, root, filename, table, numberOfWidthMeasurements) table.save(os.path.join(srcDir, 'Results.xls'))
def roiAnalysisToWrite(self, roiTableName): #I can't figure out the syntax to preallocate memory, #this will not scale to many speckles try: RT = ResultsTable.getResultsTable(roiTableName) headings = RT.getHeadings() labelCol = RT.getColumnAsVariables(headings[0]) headers = headings[1:] numCols = len(headers) numRows = len(labelCol) out = [] for col in range(numCols): out.append([]) column = RT.getColumnAsVariables(headers[col]) for row in range(numRows): out[col].append(column[row].getValue()) outT = [] for i in range(numRows): lis = [] lis.append(labelCol[i].getString()) for j in range(numCols): lis.append(out[j][i]) outT.append(lis) return outT except: print("failed roi read") return []
def relabel(): import re from ij.measure import ResultsTable rt = ResultsTable.getResultsTable() nResults = rt.size() for result in range(nResults): oldLabel = rt.getLabel(result) delimiters = [] keywords = ["series"] for keyword in keywords: if keyword in oldLabel: delimiters.append(oldLabel.index(keyword)) channel = oldLabel[0:2] try: series = "FOV" + oldLabel[(delimiters[0] + 7):(delimiters[0] + 9)] except IndexError: series = "FOV?" foundColons = [m.start() for m in re.finditer(':', oldLabel)] cell = oldLabel[foundColons[0] + 1:foundColons[1]] newLabel = channel + "_" + series + "_" + cell rt.setLabel(newLabel, result) rt.show("Results")
def __NbFoci(self): self.__boolFoci=True self.__image.killRoi() self.__image.setRoi(self.__contour) self.__ip=self.__image.getProcessor() rt=ResultsTable.getResultsTable() rt.reset() mf=MaximumFinder() mf.findMaxima(self.__ip, self.__noise, 0, MaximumFinder.LIST, True, False) self.__listMax[:]=[] #feret=self.getFercoord() #xc=feret[0]-((feret[0]-feret[2])/2.0) #yc=feret[1]-((feret[1]-feret[3])/2.0) #print xc, yc xc=self.getXC() yc=self.getYC() #print xc, yc for i in range(rt.getCounter()): x=int(rt.getValue("X", i)) y=int(rt.getValue("Y", i)) size=self.__localwand(x, y, self.__ip, self.__seuilPeaks, self.__peaksMethod, self.__light) coord=[(1, xc, x), (1, yc, y)] d=self.distMorph(coord,"Euclidean distance") d=( d / (self.getMaxF()/2) )*100 self.__listMax.append((x, y, size[0], size[1], size[2], size[3], size[4], d)) rt.reset()
def opencsv(self, name): # Return if the csv object was not set. # if self.trackscsv == None: return None TODO: some errorchecking for false csv input. # Open the csv file and return it as ResultsTable object. try: csv = IJ.getFilePath("Choose the {} file".format(name)) if csv.endswith(".csv"): rt = ResultsTable.open(csv) else: IJ.log("{} was not a .csv file".format(csv)) raise ValueError columns = rt.getHeadings() table = [{column: rt.getValue(column, row) for column in columns} for row in range(rt.size())] if rt.columnExists("Label"): for i in range(len(table)): table[i]["Label"] = rt.getStringValue("Label", i) IJ.log("Read {} rows in {}.".format(len(table), name)) return table except Exception as ex: IJ.log("Something in opencsv() went wrong: {}".format( type(ex).__name__, ex.args))
def make_nucs(hseg): """given an hseg, assumed to have a nuc_bin_imp, creates the nuc""" rm = RoiManager.getRoiManager() rm.reset() if UPDATE1: IJ.run(hseg.nuc_bin_imp, "Invert", "") rt = ResultsTable.getResultsTable() rt.reset() IJ.run(hseg.nuc_bin_imp, "Analyze Particles...", "add") rois = rm.getRoisAsArray() problem_nucs = [] for roi in rois: nuc_cent = roi_cent(roi, integer=True) found_cell = False for cell in hseg.cells.values(): if cell.roi.contains(*nuc_cent): cell.add_nuc(roi) found_cell = True break if not found_cell: IJ.log('Nuc not in any cell for hemisegment {}'.format(hseg.name)) problem_nucs.append(roi) return problem_nucs
def getTable(): ''' Check if a table exists otherwise open a new one''' ## Check if we can get a table window if IJ.getFullVersion() >= "1.53g": # try to get any active table tableWindow = WindowManager.getActiveTable( ) # this function requires 1.53g (or at least not working with 1.53c), return None if no table else: # Fallback on fetching either a window called Annotations or Annotations.csv as in previous plugin version win = WindowManager.getWindow("Annotations") win2 = WindowManager.getWindow( "Annotations.csv") # upon saving it adds this extension if win: tableWindow = win elif win2: tableWindow = win2 else: tableWindow = None ## If a table window then get its table, otherwise new table. In this case, its name is set later return tableWindow.getResultsTable() if tableWindow else ResultsTable()
def main(): features = ["Area"] numberOfClusters = 2 features, numberOfClusters = getArguments(features, numberOfClusters) rt = RT.getResultsTable() if (rt.size() < 2): exit("No data found") attributes = featuresToAttributes(features) data = readDataFromResultsTable(attributes, rt) clusterer = createClusterer(numberOfClusters) clusterer.buildClusterer(data) (mu1, sig1, mu2, sig2, prior1, prior2) = getClusterInformationFrom(clusterer) threshold = intersection(mu2, sig2, mu1, sig1) print(clusterer.toString()) print "intersection at: ", threshold if (mu1 > mu2): mu1, sig1, mu2, sig2, prior1, prior2 = mu2, sig2, mu1, sig1, prior2, prior1 writeToTable(mu1, sig1, prior1, mu2, sig2, prior2, threshold)
def getColumnIndex(column): rt = ResultsTable.getResultsTable() headings = rt.getHeadings() for i, heading in enumerate(headings, start=1): if heading == column: return i return None
def create_nucs(self) : """ """ for cell in self.cells() : cell._nucs = [] rm = RoiManager.getRoiManager() rm.reset() IJ.run(self.nuc_bin(), "Invert", "") rt = ResultsTable.getResultsTable() rt.reset() IJ.run(self.nuc_bin(), "Analyze Particles...", "add") rois = rm.getRoisAsArray() IJ.run(self.nuc_bin(),"Remove Overlay", ""); problem_nucs = [] for roi in rois : nuc_cent = futils.roi_cent(roi, integer=True) found_cell = False for cell in self.cells() : if cell.roi().contains(*nuc_cent) : cell.add_nuc(roi) found_cell = True break if not found_cell : self.exper.log('Nuc not in any cell for hemisegment {}'.format(self.name)) problem_nucs.append(roi) return problem_nucs
def nuclei_processor(imp_particles, thresh_type, folder, impname, channel_name): rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() # define a results table rt = ResultsTable.getResultsTable() imp_particles.show() # generate thresholded image for ROI nuclei = imp_particles.duplicate() nuclei.show() IJ.run("Gaussian Blur...", "sigma=3") IJ.setAutoThreshold(nuclei, thresh_type) IJ.run("Convert to Mask") IJ.run("Fill Holes") # IJ.run("Watershed") # select thresholded image (to set ROIs) IJ.run( "Set Measurements...", "area mean standard min area_fraction limit display add redirect=[" + imp_particles.title + "] decimal=3") IJ.run("Analyze Particles...", "size=30-Infinity show=Outlines display clear add") # get the ROI manager and save rm.runCommand( "save selected", os.path.join(folder, impname + '_' + channel_name + "_ROIs.zip"))
def linkSpots(): rt = ResultsTable.getResultsTable() X = rt.getColumn(ResultsTable.X_CENTROID) Y = rt.getColumn(ResultsTable.Y_CENTROID) D = rt.getColumn(ResultsTable.FERET) SLICE = rt.getColumn(ResultsTable.SLICE) spotsByScale = getRoisBySlice(SLICE) print(spotsByScale) ## set objects of spots i scale 1 to the id of the spot spots = spotsByScale[1] for spot in spots: spot['object']=spot['id'] for s in range(2, len(spotsByScale)+1): spots = spotsByScale[s] for spot in spots: spot['object']=spot['id'] # initially set the object to which the spot belong to the spot id spotsLastScale = spotsByScale[s-1] minDist = float("inf") minObject = None for spotLastScale in spotsLastScale: # for each spot on the next scale deltaX = X[spotLastScale['id']]-X[spot['id']] deltaY = Y[spotLastScale['id']]-Y[spot['id']] dist = math.sqrt((deltaX * deltaX) + (deltaY*deltaY)) print("spot", spot['id'], "spot s-1", spotLastScale['id'], dist) if (dist<(D[spot['id']])/2.0): if (dist<minDist): minDist = dist minObject = spotLastScale['object'] print('hit', minDist, minObject) if minObject is not None: spot['object'] = minObject print("minObject", minObject) return spotsByScale
def run_comdet(image): IJ.run( image, "Detect Particles", " two=[Detect in both channels independently] ch1a=" + str(ch1size) + " ch1s=" + str(ch1thresh) + " ch2a=" + str(ch2size) + " ch2s=" + str(ch2thresh) + " calculate max=" + str(coloc) + " add=Nothing") rt = ResultsTable.getResultsTable() return rt
def intensity_measure_3D(imp_intens, imp_label): imp_intens.show() imp_label.show() IJ.run(imp_intens, "3D Intensity Measure", "objects=[%s] signal=[%s]" % (imp_label.getTitle(), imp_intens.getTitle()) ); imp_intens.hide() imp_label.hide() rt = ResultsTable.getResultsTable() return rt
def intensity_measure_3D(imp_intens, imp_label): imp_intens.show() imp_label.show() IJ.run(imp_intens, "3D Intensity Measure", "objects=[%s] signal=[%s]" % (imp_label.getTitle(), imp_intens.getTitle()) ); imp_intens.hide() imp_label.hide() rt = ResultsTable.getResultsTable() return rt
def analyzeImage(passImage, passModel, passChannel, passProbability, passPixels, passOutput): retResults = list() windows = set() # Register current window registerWindow(passImage.title, windows) # Extract the requested channel IJ.run("Z Project...", "projection=[Max Intensity]") registerWindow("MAX_" + passImage.title, windows) IJ.run("Duplicate...", "title=temp") registerWindow("temp", windows) # Apply WEKA training model to image wekaSeg = WekaSegmentation(WindowManager.getCurrentImage()) wekaSeg.loadClassifier(passModel) wekaSeg.applyClassifier(True) # Extract first slice of probability map wekaImg = wekaSeg.getClassifiedImage() wekaImg.show() registerWindow("Probability maps", windows) IJ.setSlice(1) IJ.run("Duplicate...", "title=temp2") registerWindow("temp2", windows) # Apply threshold and save IJ.setThreshold(passProbability, 1, "Black & White") fileParts = passImage.getTitle().split(".") IJ.save( os.path.join( passOutput, "{0}-probmap.png".format(fileParts[0], '.'.join(fileParts[1:])))) # Perform particle analysis and save IJ.run("Analyze Particles...", "size={0}-Infinity show=Outlines pixel clear".format(passPixels)) registerWindow("Drawing of temp2", windows) IJ.save( os.path.join( passOutput, "{0}-particles.png".format(fileParts[0], '.'.join(fileParts[1:])))) # Get measurements tableResults = ResultsTable.getResultsTable() for rowIdx in range(tableResults.size()): retResults.append(tableResults.getRowAsString(rowIdx).split()) retResults[-1].insert( 0, WindowManager.getCurrentImage().getCalibration().unit) retResults[-1].append( float(retResults[-1][4]) / float(retResults[-1][3])) # Close windows closeWindows(windows) return retResults
def auto_resize_angle_measure(img, two_sarcomere_size): """Resizes and measures angle of offset for img based on T-tubules.""" # Run Fast Fourier Transform on Image to get Power Spectral Density IJ.run(img, "FFT", "") # Select PSD image. fft_title = "FFT of " + img.getTitle() fft_img = WindowManager.getImage(fft_title) # Threshold the image and create binary mask. IJ.setThreshold(151, 255) #IJ.setThreshold(135, 255) IJ.run(fft_img, "Convert to Mask", "") # Set measurements for fitting an ellipse and fit them to data. IJ.run(fft_img, "Set Measurements...", "area centroid fit redirect=None decimal=2") if dev_options: args = "size=10-Infinity show=Ellipses display" else: args = "size=10-Inifinity" IJ.run(fft_img, "Analyze Particles...", args) results = ResultsTable.getResultsTable() angle_column = results.getColumnIndex("Angle") area_column = results.getColumnIndex("Area") centroid_x_column = results.getColumnIndex("X") centroid_y_column = results.getColumnIndex("Y") # Sort by area since we need the largest two ellipses. results.sort("Area") # Grab info for the largest two ellipses. areas = results.getColumnAsDoubles(area_column) angles = results.getColumnAsDoubles(angle_column) c_xs = results.getColumnAsDoubles(centroid_x_column) c_ys = results.getColumnAsDoubles(centroid_y_column) # Calculate offset angle from main ellipse. rotation_angle = angles[-1] - 90. # Measure distance between centroids of two largest ellipses using distance measurement tool to get spatial frequency of T-tubules. # Note: This needs to be in pixels since the filter size is in pixels. c_x_0 = c_xs[-1] c_y_0 = c_ys[-1] c_x_1 = c_xs[-2] c_y_1 = c_ys[-2] dist_gap = ((c_x_0 - c_x_1)**2 + (c_y_0 - c_y_1)**2)**0.5 old_two_sarcomere_size = 2 * fft_img.getDimensions()[0] / dist_gap # Resize based on measured two sarcomere size resize_ratio = float(two_sarcomere_size) / float(old_two_sarcomere_size) old_width = img.width old_height = img.height new_width = resize_ratio * old_width new_height = resize_ratio * old_height resize_args = "width={} height={} depth=1 constrain average interpolation=Bicubic".format( new_width, new_height) IJ.run(img, "Size...", resize_args) return rotation_angle
def show_as_table(title, data, order=[]): """Helper function to display group and data information as a ResultsTable""" table = ResultsTable() for d in data: table.incrementCounter() order = [k for k in order] order.extend([k for k in d.keys() if not d in order]) for k in order: table.addValue(k, d[k]) table.show(title)
def getColumn(aC): rt = ResultsTable.getResultsTable() anIndex = getColumnIndex(aC) column = [] for i in range(0, rt.size()): columns = rt.getRowAsString(i).split('\t') v = float(columns[anIndex]) column.append(v) return column
def analyzeParticles(imp, minsize, maxsize, mincirc, maxcirc, filename='Test.czi', addROIManager=True, headless=True, exclude=True): if addROIManager is True: if exclude is False: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ if exclude is True: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_MANAGER \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES if addROIManager is False: if exclude is False: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ if exclude is True: options = PA.SHOW_ROI_MASKS \ + PA.SHOW_RESULTS \ + PA.DISPLAY_SUMMARY \ + PA.ADD_TO_OVERLAY \ + PA.EXCLUDE_EDGE_PARTICLES measurements = PA.STACK_POSITION \ + PA.LABELS \ + PA.AREA \ + PA.RECT \ results = ResultsTable() p = PA(options, measurements, results, minsize, maxsize, mincirc, maxcirc) p.setHideOutputImage(True) particlestack = ImageStack(imp.getWidth(), imp.getHeight()) for i in range(imp.getStackSize()): imp.setSliceWithoutUpdate(i + 1) ip = imp.getProcessor() #IJ.run(imp, "Convert to Mask", "") p.analyze(imp, ip) mmap = p.getOutputImage() particlestack.addSlice(mmap.getProcessor()) return particlestack, results
def measureSkeletonTotalLength(imp, root): IJ.run(imp,"Analyze Skeleton (2D/3D)", "prune=none") totalLength = 0 nBranches = 0 rt = ResultsTable.getResultsTable() avgLengths = rt.getColumn(rt.getColumnIndex("Average Branch Length")) for i in range(len(avgLengths)): totalLength = totalLength + rt.getValue("# Branches", i) * rt.getValue("Average Branch Length", i) nBranches = nBranches + rt.getValue("# Branches", i) print root,",",imp.getTitle(),",",totalLength,",",nBranches
def __Measures(self): self.__boolmeasures=True if (self.__contour is not None) and (self.__contour.getType() not in [9,10]): self.__image.killRoi() self.__image.setRoi(self.__contour) self.__ip=self.__image.getProcessor() self.__rt= ResultsTable() analyser= Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt) analyser.measure() #self.__rt.show("myRT") else: self.__rt = ResultsTable() analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt) analyser.measure() #self.__rt.show("myRT") maxValues=self.__rt.getRowAsString(0).split("\t") heads=self.__rt.getColumnHeadings().split("\t") for val in heads: self.__rt.setValue(val, 0, Float.NaN)
def countParticles(imp, roim, minSize, maxSize, minCircularity, maxCircularity): # Create a table to store the results table = ResultsTable() # Create the particle analyzer pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, minSize, maxSize, minCircularity, maxCircularity) #pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, 10, Double.POSITIVE_INFINITY, 0.5, 1.0) #pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN, table, 5, 6, 0.5, 1.0) pa.setRoiManager(roim) pa.setHideOutputImage(True) if pa.analyze(imp): print "All ok" else: print "There was a problem in analyzing", blobs areas = table.getColumn(0) intensities = table.getColumn(1) if ( (areas!=None) and (intensities!=None)): for area, intensity in zip(areas,intensities): print str(area)+": "+str(intensity)
def getParticleCenters(imp): # Create a table to store the results rt = ResultsTable() paOpts = PA.SHOW_OUTLINES \ + PA.INCLUDE_HOLES \ + PA.EXCLUDE_EDGE_PARTICLES measurements = PA.CENTROID + PA.CENTER_OF_MASS MINSIZE = 1000 MAXSIZE = Double.POSITIVE_INFINITY pa = PA(paOpts,measurements, rt, MINSIZE, MAXSIZE) pa.setHideOutputImage(True) if not pa.analyze(imp): print "There was a problem in analyzing", imp # The measured centroids are listed in the first column of the results table, as a float array: centroids_x = rt.getColumn(rt.X_CENTROID) centroids_y = rt.getColumn(rt.Y_CENTROID) coms_x = rt.getColumn(rt.X_CENTER_OF_MASS) coms_y = rt.getColumn(rt.Y_CENTER_OF_MASS) return (centroids_x,centroids_y, coms_x, coms_y)
def __init__(self): self.imp = None self.preview = None self.createMainWindow() self.cells = None self.files = [] self.results = ResultsTable() ImagePlus.addImageListener(self) self.selectInputDir() self.selectOutputDir() self.pairs = [] self.methods = [] self.processNextFile()
def analyse(imp, root, filename, thresholds): closeAllImageWindows() imp.show() print "" print(imp.getTitle()) print "**********************************" IJ.run("Set Measurements...", "integrated redirect=None decimal=2"); # get image calibration info IJ.run(imp, "Properties...", "unit=pixel pixel_width=1 pixel_height=1"); # convert to 8-bit IJ.setMinAndMax(imp, 0, 65535); IJ.run(imp, "8-bit", ""); thresholds = [(x / 65535 * 255) for x in thresholds] # Nuclei #closeAllNoneImageWindows() iChannel = 1 imp.setSlice(iChannel) IJ.run(imp, "Gaussian Blur...", "sigma=2 slice"); IJ.setThreshold(imp, thresholds[iChannel-1], 1000000000) IJ.run(imp, "Convert to Mask", "method=Default background=Dark only black"); IJ.run(imp, "Measure", ""); rt = ResultsTable.getResultsTable() values = rt.getColumnAsDoubles(rt.getColumnIndex("RawIntDen")) print("Area Nuclei (pixel^2) =",values[-1]/255) # Dots #closeAllNoneImageWindows() iChannel = 3 imp.setSlice(iChannel) IJ.run(imp, "Gaussian Blur...", "sigma=1 slice"); IJ.run(imp, "Find Maxima...", "noise="+str(thresholds[iChannel-1])+" output=Count"); rt = ResultsTable.getResultsTable() values = rt.getColumnAsDoubles(rt.getColumnIndex("Count")) print("Number of Dots =",values[-1])
def straighten_roi_rotation(roiWindowsize = 8): """ Root straightening function that rotates ROI to follow root slope. Does not work properly. """ IJ.run("Set Measurements...", "mean standard min center redirect=None decimal=3") IJ.runMacro("//setTool(\"freeline\");") IJ.run("Line Width...", "line=80"); #numPoints = 512/roiWindowsize xvals = [] yvals = [] maxvals = [] counter = 0 maxIters = 800/roiWindowsize minIters = 10 imp = IJ.getImage().getProcessor() rm = RoiManager() if find_first_pixel(0,imp) == None or find_last_pixel(0,imp)[1] == None: return y = (find_first_pixel(0,imp)[1]+find_last_pixel(0,imp)[1])/2 roi = roiWindow_(imp, center = (roiWindowsize/2,y), width = roiWindowsize, height = 512) xvals.append(roiWindowsize/2) yvals.append(y) maxvals.append(0) roi.findTilt_() i = 0 while i < maxIters and roi.containsRoot_(): roi.advance_(roiWindowsize) IJ.run("Clear Results") IJ.run("Measure") table = RT.getResultsTable() x = RT.getValue(table, "XM", 0) y = RT.getValue(table, "YM", 0) if imp.getPixel(int(x),int(y)) != 0: xvals.append(x) yvals.append(y) maxvals.append((RT.getValue(table, "Max", 0))) #roi.advance_(roiWindowsize) print "here" roi.unrotateRoot_() IJ.run("Clear Results") IJ.run("Measure") roi.restoreCenter_(RT.getValue(table, "XM", 0), RT.getValue(table, "YM", 0)) #exit(1) sleep(.5) roi.findTilt_() i += 1 coords = "" for i in range(len(xvals)-1): coords += str(xvals[i]) + ", " + str(yvals[i]) +", " coords += str(xvals[len(xvals)-1]) + ", " + str(yvals[len(xvals)-1]) IJ.runMacro("makeLine("+coords+")") IJ.run("Straighten...", "line = 80")
def anaParticles(imp, minSize, maxSize, minCirc): strName = imp.getShortTitle() imp.setTitle("original") ret = imp.duplicate() IJ.run(ret, "Enhance Contrast", "saturated=0.35") IJ.run(ret, "8-bit", "") IJ.run(ret, "Threshold", "method=Default white") IJ.run(ret, "Watershed", "") rt = ResultsTable() # strSetMeas = "area mean modal min center perimeter bounding fit shape feret's redirect='original' decimal=3" # N.B. redirect will not work without a displayed image, so we cannot use a gray level image strSetMeas = "area mean modal min center perimeter bounding fit shape feret's decimal=3" IJ.run("Set Measurements...", strSetMeas) # note this doies not get passed directly to ParticleAnalyzer, so # I did this, saved everything and looked for the measurement value in ~/Library/Preferences/IJ_Prefs.txt # measurements=27355 # meas = Measurements.AREA + Measurements.CIRCULARITY + Measurements.PERIMETER + Measurements.SHAPE_DESCRIPTORS # didn't work reliably meas = 27355 pa = ParticleAnalyzer(0, meas, rt, minSize, maxSize, minCirc, 1.0); pa.analyze(ret); rt.createTableFromImage(ret.getProcessor()) return [ret, rt]
def run(): srcDir = srcFile.getAbsolutePath() IJ.run("Set Measurements...", "integrated limit redirect=None decimal=3") for dirName, subdirs, filenames in os.walk(srcDir): if len(subdirs)==0: finalResults = [] for filename in filenames: # Check for file extension if not filename.endswith(ext): continue process(srcDir, dirName, filename) rt = ResultsTable.getResultsTable() colRaw = rt.getColumnIndex("IntDen") colRatio = rt.getColumnIndex("RawIntDen") finalResults.append(rt.getColumn(colRaw)) finalResults.append(rt.getColumn(colRatio)) with open(os.path.join(dirName, dirName+'.csv'), 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=",") for row in zip(*finalResults): writer.writerow(row)
def process(srcDir, currentDir, fileName): image = IJ.openImage(os.path.join(currentDir, fileName)) IJ.run("Clear Results") #set lowerbound threshold here IJ.setThreshold(image, 200, 10000) # Change (1,25) below to (1,n+1) where n is the number of frames for slice in range(1,(image.getNSlices()+1),1): image.setSlice(slice) IJ.run(image, "Select All", "") IJ.run(image, "Measure", "") rt = ResultsTable.getResultsTable() # this line calculates the baseline baseline = (rt.getValue("IntDen",1) + rt.getValue("IntDen",2) + rt.getValue("IntDen",3))/3.0 for result in range(0,rt.getCounter()): cur_intensity = rt.getValue("IntDen",result) ratio = cur_intensity/baseline rt.setValue("RawIntDen",result,ratio) rt.updateResults() image.close()
options = "radius=%d cutoff=%d percentile=%f" % (radius, cutoff, percentile) thread = thr.currentThread() original_name = thread.getName() thread.setName("Run$_my_batch_process") Macro.setOptions(thr.currentThread(), options) pt = IJ.runPlugIn(imp, "de.embl.cmci.pt3d.Dot_Detector_3D", "") impdimA = imp.getDimensions() ims = imp.createEmptyStack() for i in range(impdimA[3]): ims.addSlice(None, ByteProcessor(impdimA[0], impdimA[1])) imp2 = ImagePlus("test", ims) nSlices = imp2.getNSlices() rt = ResultsTable.getResultsTable() xindex = rt.getColumnIndex("x") yindex = rt.getColumnIndex("y") zindex = rt.getColumnIndex("z") xA = rt.getColumn(xindex) yA = rt.getColumn(yindex) zA = rt.getColumn(zindex) neighbornumA = NeighborChecker(xA, yA, zA, True) for i in range(len(xA)): print xA[i], yA[i], zA[i], " .. Neighbor", neighbornumA[i] # if xA[i] > 0: if neighbornumA[i] == 0: cslice=Math.round(zA[i])+1 if cslice > 0 and cslice <= nSlices:
from ij import IJ from ij.measure import ResultsTable # Get current ImagePlus image = IJ.getImage() IJ.run("Clear Results") IJ.setThreshold(200, 10000) for slice in range(1,image.getNSlices()+1,1): image.setSlice(slice) IJ.run("Select All") IJ.run("Measure") rt = ResultsTable.getResultsTable() baseline = (rt.getValue("IntDen",0) + rt.getValue("IntDen",1) + rt.getValue("IntDen",2) + rt.getValue("IntDen",3))/4.0 for result in range(0,rt.getCounter()): cur_intensity = rt.getValue("IntDen",result) ratio = cur_intensity/baseline rt.setValue("RawIntDen",result,ratio) rt.updateResults()
binorg = binimp.duplicate() if VERBOSE: binorg.show() # Count nucleus setting MAXSIZE = imp3.getWidth()*imp3.getHeight(); MINSIZE = 100; #options = PA.SHOW_ROI_MASKS \ # + PA.EXCLUDE_EDGE_PARTICLES \ # + PA.INCLUDE_HOLES \ # + PA.SHOW_RESULTS \ options = PA.INCLUDE_HOLES \ + PA.CLEAR_WORKSHEET \ # + PA.SHOW_RESULTS \ rt = ResultsTable() p = PA(options, PA.AREA + PA.STACK_POSITION, rt, MINSIZE, MAXSIZE) p.setHideOutputImage(True) # Morphological dilate binner.setup('dilate', None) clusters = 0 initialCells = 0 # dilate by 'SAMPLEITER' for i in range(SAMPLEITER+1): p.analyze(binimp) cellcounts = rt.getCounter() if i == 0:
def process(self,imp): # extract nucleus channel, 8-bit and twice binned imp.setC(self.nucleusChannel) ip = imp.getChannelProcessor().duplicate() ip = ip.convertToByteProcessor() ip = ip.bin(4) nucleus = ImagePlus("nucleus_channel", ip) # threshold image and separate clumped nuclei IJ.run(nucleus, "Auto Threshold", "method=Otsu white setthreshold show"); IJ.run(nucleus, "Make Binary", "thresholded remaining black"); IJ.run(nucleus, "Watershed", ""); directory = imp.getTitle() directory = directory.replace(" ", "_")\ .replace(",", "_")\ .replace("#", "_series")\ .replace("...", "")\ .replace(".","_") directory = os.path.join(self.exportDir, directory) sliceDirectory = os.path.join(directory, "slices") print directory print sliceDirectory if not os.path.exists(sliceDirectory): os.makedirs(sliceDirectory) # Create a table to store the results table = ResultsTable() # Create a hidden ROI manager, to store a ROI for each blob or cell #roim = RoiManager(True) # remove small particles and border particles pa = ParticleAnalyzer(\ ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,\ Measurements.CENTER_OF_MASS,\ table,\ self.minArea, self.maxArea,\ 0.0,1.0) if pa.analyze(nucleus): print "All ok, number of particles: ", table.size() else: print "There was a problem in analyzing", imp, nucleus table.save(os.path.join(directory, "rt.csv")) # read the center of mass coordinates cmx = table.getColumn(0) cmy = table.getColumn(1) if self.debug: imp.show() i=0 for i in range(0, min(self.nCells,table.size())): # ROI around the cell cmx = table.getValue("XM",i) cmy = table.getValue("YM",i) x = 4 * cmx - (self.boxSize - 1) / 2 y = 4 * cmy - (self.boxSize - 1) / 2 if (x < self.edge or y < self.edge or x > imp.getWidth() - self.edge or y > imp.getHeight() - self.edge): continue roi = Roi(x,y,self.boxSize,self.boxSize) imp.setRoi(roi, False) cellStack = ImageStack(self.boxSize, self.boxSize) for z in range(1, imp.getNSlices() + 1): imp.setSlice(z) for c in range(1, imp.getNChannels() + 1): imp.setC(c) # copy ROI to stack imp.copy() impSlice = imp.getClipboard() cellStack.addSlice(impSlice.getProcessor()) if self.slices: sliceTitle = "cell_%s_z%s_c%s" % (str(i).zfill(4), str(z).zfill(3), str(c)) print sliceTitle IJ.saveAsTiff(impSlice, os.path.join(sliceDirectory, sliceTitle)) impSlice.close() title = "cell_" + str(i).zfill(4) cell = ImagePlus(title, cellStack) # save ROI image IJ.saveAsTiff(cell, os.path.join(directory, title)) cell.close() if self.debug: imp.updateAndDraw() wait = Wait("particle done") wait.show()
def updatepressed(event): self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.run("Threshold...") IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #for i in range(rm.getCount()) : # rm.select(i) # rm.runCommand("Set Color", "0000FF", 2) IJ.resetThreshold(self.__image) rt.show("tempRT") areas=rt.getColumn(ResultsTable.AREA) means=rt.getColumn(ResultsTable.MEAN) majors=rt.getColumn(ResultsTable.MAJOR) minors=rt.getColumn(ResultsTable.MINOR) #print 0 if self.__slidersDict["Area_max"].getMaximum() < int(max(areas)+1): # print 1 self.__slidersDict["Area_max"].setMaximum(int(max(areas))+1) if self.__slidersDict["Area_min"].getMaximum() < int(max(areas)+1): # print 2 self.__slidersDict["Area_min"].setMaximum(int(max(areas))+1) if self.__slidersDict["Mean_max"].getMaximum() < int(max(means)+1): # print 3 self.__slidersDict["Mean_max"].setMaximum(int(max(means))+1) if self.__slidersDict["Mean_min"].getMaximum() < int(max(means)+1): # print 4 self.__slidersDict["Mean_min"].setMaximum(int(max(means))+1) if self.__slidersDict["Major_max"].getMaximum() < int(max(majors)): # print 5 self.__slidersDict["Major_max"].setMaximum(int(max(majors))+1) if self.__slidersDict["Major_min"].getMaximum() < int(max(majors)+1): # print 6 self.__slidersDict["Major_min"].setMaximum(int(max(majors))+1) if self.__slidersDict["Minor_max"].getMaximum() < int(max(minors)+1): # print 7 self.__slidersDict["Minor_max"].setMaximum(int(max(minors))+1) if self.__slidersDict["Minor_min"].getMaximum() < int(max(minors)+1): # print 8 self.__slidersDict["Minor_min"].setMaximum(int(max(minors))+1) if self.__slidersDict["AR_max"].getMaximum() < int((max(majors)+1)/min(minors)+1): # print 9 self.__slidersDict["AR_max"].setMaximum(int((max(majors)+1)/(min(minors)))) if self.__slidersDict["AR_min"].getMaximum() < int((max(majors)+1)/min(minors)): # print 10 self.__slidersDict["AR_min"].setMaximum(int((max(majors)+1)/(min(minors)))) #print 11 for sb in self.__slidersDict.values(): sb.repaint() #rm.runCommand("reset") #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()
class MandersPlugin(ImageListener, WindowAdapter): def __init__(self): self.imp = None self.preview = None self.createMainWindow() self.cells = None self.files = [] self.results = ResultsTable() ImagePlus.addImageListener(self) self.selectInputDir() self.selectOutputDir() self.pairs = [] self.methods = [] self.processNextFile() def selectInputDir(self): inputDialog = DirectoryChooser("Please select a directory contaning your images") inputDir = inputDialog.getDirectory() for imageFile in os.listdir(inputDir): self.files.append(inputDir + imageFile) def selectOutputDir(self): outputDialog = DirectoryChooser("Please select a directory to save your results") self.outputDir = outputDialog.getDirectory() def closeImage(self): if self.imp is not None: self.imp.close() self.imp = None if self.preview is not None: self.preview.close() self.preview = None def openImage(self, imageFile): try: images = BF.openImagePlus(imageFile) self.imp = images[0] except UnknownFormatException: return None if self.imp.getNChannels() < 2: IJ.error("Bad image format", "Image must contain at lease 2 channels!") return None if not self.pairs or \ not self.methods: self.getOptionsDialog(self.imp) title = self.imp.title self.imp.title = title[:title.rfind('.')] return self.imp def getOptionsDialog(self, imp): thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData", "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"] gd = GenericDialog("Please select channels to collocalize") for i in range(1, imp.getNChannels() + 1): gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None") gd.showDialog() if gd.wasCanceled(): self.exit() channels = [] for i in range(1, imp.getNChannels() + 1): method = gd.getNextChoice() self.methods.append(method) if method != "None": channels.append(i) for x in channels: for y in channels: if x < y: self.pairs.append((x, y)) def processNextFile(self): if self.files: imageFile = self.files.pop(0) return self.processFile(imageFile) else: return False def processFile(self, imageFile): imp = self.openImage(imageFile) if imp is not None: cell = Cell(imp.NSlices, 1) self.cells = DelegateListModel([]) self.cells.append(cell) self.showMainWindow(self.cells) if self.checkbox3D.isSelected(): self.displayImage(imp) else: self.displayImage(imp, False) self.preview = self.previewImage(imp) self.displayImage(self.preview) return True else: return self.processNextFile() def displayImage(self, imp, show = True): imp.setDisplayMode(IJ.COMPOSITE) enhancer = ContrastEnhancer() enhancer.setUseStackHistogram(True) splitter = ChannelSplitter() for c in range(1, imp.getNChannels() + 1): imp.c = c enhancer.stretchHistogram(imp, 0.35) if show: imp.show() def previewImage(self, imp): roi = imp.getRoi() splitter = ChannelSplitter() channels = [] for c in range(1, imp.getNChannels() + 1): channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c)) projector = ZProjector(channel) projector.setMethod(ZProjector.MAX_METHOD) projector.doProjection() channels.append(projector.getProjection()) image = RGBStackMerge.mergeChannels(channels, False) image.title = imp.title + " MAX Intensity" image.luts = imp.luts imp.setRoi(roi) return image def getCroppedChannels(self, imp, cell): splitter = ChannelSplitter() imp.setRoi(None) if cell.mode3D: cropRoi = cell.getCropRoi() else: cropRoi = cell.roi if cropRoi is None: return None crop = cropRoi.getBounds() channels = [] for c in range(1, imp.getNChannels() + 1): slices = ImageStack(crop.width, crop.height) channel = splitter.getChannel(imp, c) for z in range(1, channel.getSize() + 1): zslice = channel.getProcessor(z) zslice.setRoi(cropRoi) nslice = zslice.crop() if cell.mode3D: oroi = cell.slices[z - 1].roi else: oroi = cell.roi if oroi is not None: roi = oroi.clone() bounds = roi.getBounds() roi.setLocation(bounds.x - crop.x, bounds.y - crop.y) nslice.setColor(Color.black) nslice.fillOutside(roi) slices.addSlice(nslice) channels.append(ImagePlus("Channel %i" % c, slices)) return channels def getThreshold(self, imp, method): thresholder = Auto_Threshold() duplicator = Duplicator() tmp = duplicator.run(imp) return thresholder.exec(tmp, method, False, False, True, False, False, True) def getContainer(self, impA, impB): imgA = ImagePlusAdapter.wrap(impA) imgB = ImagePlusAdapter.wrap(impB) return DataContainer(imgA, imgB, 1, 1, "imageA", "imageB") def getManders(self, imp, cell): ### Crop channels according to cell mask channels = self.getCroppedChannels(imp, cell) if channels is None: return None ### Calculate channel thresholds thrs = [] thrimps = [] for c, method in enumerate(self.methods): if method != "None": thr, thrimp = self.getThreshold(channels[c], method) else: thr, thrimp = None, None thrs.append(thr) thrimps.append(thrimp) ### Calculate manders colocalization manders = MandersColocalization() raws = [] thrds = [] for chA, chB in self.pairs: container = self.getContainer(channels[chA - 1], channels[chB - 1]) img1 = container.getSourceImage1() img2 = container.getSourceImage2() mask = container.getMask() cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor()) rtype = img1.randomAccess().get().createVariable() raw = manders.calculateMandersCorrelation(cursor, rtype) rthr1 = rtype.copy() rthr2 = rtype.copy() rthr1.set(thrs[chA - 1]) rthr2.set(thrs[chB - 1]) cursor.reset() thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above) raws.append(raw) thrds.append(thrd) return (channels, thrimps, thrs, raws, thrds) def saveMultichannelImage(self, title, channels, luts): tmp = RGBStackMerge.mergeChannels(channels, False) tmp.luts = luts saver = FileSaver(tmp) saver.saveAsTiffStack(self.outputDir + title + ".tif") tmp.close() def createMainWindow(self): self.frame = JFrame('Select cells and ROIs', defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE ) self.frame.setLayout(GridBagLayout()) self.frame.addWindowListener(self) self.frame.add(JLabel("Cells"), GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(5, 2, 2, 0), 0, 0 )) self.cellList = JList(DelegateListModel([]), selectionMode = ListSelectionModel.SINGLE_SELECTION, cellRenderer = MyRenderer(), selectedIndex = 0, valueChanged = self.selectCell ) self.frame.add(JScrollPane(self.cellList), GridBagConstraints(0, 1, 1, 5, .5, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(0, 2, 2, 0), 0, 0 )) self.frame.add(JButton('Add cell', actionPerformed = self.addCell), GridBagConstraints(1, 2, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell), GridBagConstraints(1, 4, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 5, 0, 5), 0, 0 )) self.frame.add(JLabel("Slices"), GridBagConstraints(0, 6, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(5, 2, 2, 0), 0, 0 )) self.sliceList = JList(DelegateListModel([]), selectionMode = ListSelectionModel.SINGLE_SELECTION, cellRenderer = MyRenderer(), selectedIndex = 0, valueChanged = self.selectSlice ) self.frame.add(JScrollPane(self.sliceList), GridBagConstraints(0, 7, 1, 5, .5, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(0, 2, 2, 0), 0, 0 )) self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice), GridBagConstraints(1, 8, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) self.frame.add(JButton('Done', actionPerformed = self.doneSelecting), GridBagConstraints(1, 10, 1, 2, 0, .25, GridBagConstraints.CENTER, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D) self.frame.add(self.checkbox3D, GridBagConstraints(0, 13, 2, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0 )) def showMainWindow(self, cells = None): if cells is not None: self.cellList.model = cells if cells: self.cellList.selectedIndex = 0 self.frame.pack() self.frame.visible = True def hideMainWindow(self): self.frame.visible = False def closeMainWindow(self): self.frame.dispose() def toggle3D(self, event): mode3D = self.checkbox3D.isSelected() if mode3D: self.sliceList.enabled = True if self.imp is not None: self.imp.show() if self.preview is not None: self.preview.hide() else: self.sliceList.enabled = False if self.preview is None: self.preview = self.previewImage(self.imp) self.displayImage(self.preview) else: self.preview.show() if self.imp is not None: self.imp.hide() selectedCell = self.cellList.selectedIndex if selectedCell >= 0: cell = self.cells[selectedCell] self.sliceList.model = cell.slices self.sliceList.selectedIndex = 0 def addCell(self, event): size = len(self.cells) if (size > 0): last = self.cells[size - 1] n = last.n + 1 else: n = 1 self.cells.append(Cell(self.imp.NSlices, n)) self.cellList.selectedIndex = size def removeCell(self, event): selected = self.cellList.selectedIndex if selected >= 0: self.cells.remove(self.cells[selected]) if (selected >= 1): self.cellList.selectedIndex = selected - 1 else: self.cellList.selectedIndex = 0 def selectCell(self, event): selected = self.cellList.selectedIndex if selected >= 0: cell = self.cells[selected] self.sliceList.model = cell.slices self.sliceList.selectedIndex = 0 else: self.sliceList.model = DelegateListModel([]) if self.preview is not None: self.preview.setRoi(cell.roi) def selectSlice(self, event): selectedCell = self.cellList.selectedIndex selectedSlice = self.sliceList.selectedIndex if selectedCell >= 0 and selectedSlice >= 0: cell = self.cells[selectedCell] image = self.imp mode3D = self.checkbox3D.isSelected() if image is not None and cell is not None and mode3D: roi = cell.slices[selectedSlice].roi if (image.z - 1 != selectedSlice): image.z = selectedSlice + 1 image.setRoi(roi, True) if self.preview is not None and not mode3D: self.preview.setRoi(cell.roi, True) def updateSlice(self, event): if self.checkbox3D.isSelected(): self.updateSlice3D(self.imp) else: self.updateSlice2D(self.preview) def updateSlice3D(self, imp): selectedCell = self.cellList.selectedIndex selectedSlice = self.sliceList.selectedIndex if selectedCell >= 0 and selectedSlice >= 0 and imp is not None: cell = self.cells[selectedCell] impRoi = imp.getRoi() if cell is not None and impRoi is not None: index = selectedSlice + 1 roi = ShapeRoi(impRoi, position = index) cell.mode3D = True cell.name = "Cell %i (3D)" % cell.n cell.slices[selectedSlice].roi = roi if (index + 1 <= len(cell.slices)): imp.z = index + 1 self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell)) self.sliceList.repaint(self.sliceList.getCellBounds(selectedSlice, selectedSlice)) def updateSlice2D(self, imp): selectedCell = self.cellList.selectedIndex if selectedCell >= 0 and imp is not None: cell = self.cells[selectedCell] impRoi = imp.getRoi() if cell is not None and impRoi is not None: roi = ShapeRoi(impRoi, position = 1) cell.mode3D = False cell.name = "Cell %i (2D)" % cell.n cell.roi = roi self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell)) def imageOpened(self, imp): pass def imageClosed(self, imp): pass def imageUpdated(self, imp): if self.checkbox3D.isSelected(): if imp is not None: selectedCell = self.cellList.selectedIndex selectedSlice = imp.z - 1 if imp == self.imp and selectedSlice != self.sliceList.selectedIndex: self.sliceList.selectedIndex = selectedSlice def doneSelecting(self, event): oluts = self.imp.luts luts = [] channels = [] for c, method in enumerate(self.methods): if method != "None": luts.append(oluts[c]) channels.append(c) for cell in self.cells: manders = self.getManders(self.imp, cell) if manders is not None: chimps, thrimps, thrs, raws, thrds = manders index = self.cells.index(cell) + 1 title = "Cell_%i-" % index + self.imp.title self.saveMultichannelImage(title, chimps, oluts) title = "Cell_%i_thrd-" % index + self.imp.title self.saveMultichannelImage(title, thrimps, luts) self.results.incrementCounter() row = self.results.getCounter() - 1 for i, thr in enumerate(thrs): if thr is not None: self.results.setValue("Threshold %i" % (i + 1), row, int(thr)) for i, pair in enumerate(self.pairs): self.results.setValue("%i-%i M1 raw" % pair, row, float(raws[i].m1)) self.results.setValue("%i-%i M2 raw" % pair, row, float(raws[i].m2)) self.results.setValue("%i-%i M1 thrd" % pair, row, float(thrds[i].m1)) self.results.setValue("%i-%i M2 thrd" % pair, row, float(thrds[i].m2)) self.closeImage() if not self.processNextFile(): print "All done - happy analysis!" self.results.show("Manders collocalization results") self.exit() def windowClosing(self, e): print "Closing plugin - BYE!!!" self.exit() def exit(self): ImagePlus.removeImageListener(self) self.closeImage() self.closeMainWindow()
class Morph(object): """ Fourni les mesures principales pour l'analyse des cellules bacteriennes: proprietes: 1-MaxFeret 2-MinFeret 3-AngleFeret 4-XFeret 5-YFeret 6-Area 7-Mean 8-StdDev 9-IntDen 10-Kurt 11-Skew 12-Angle 13-Major 14-Minor 15-Solidity 16-AR 17-Round 18-Circ. 19-XM 20-YM 21-X 22-Y 23-FerCoord: tuple contenant x1, y1, x2, y2 du MaxFeret 24-Fprofil: list contenant les valeurs du profil le long de MaxFeret 25-FerAxis: Line ROI 26-MidAxis: Polyline ROI de l'axe median par skeletonize 27-MidProfil: list contenant les valeurs du profil le long de MidAxis 28-nb Foci 29-ListFoci: liste des positions des foci par cellule 30-ListAreaFoci: liste des area des foci 31-ListPeaksFoci: liste des int max des foci 32-ListMeanFoci liste des int mean des foci toute les proprietes mettent a jour l'image cible par: object.propriete=imp Methodes: getFeretSegments(n segments) getMidSegments(n segments, radius, tool 0= ligne perpendiculaire, 1= cercle, 2= ligne tangente) selectInitRoi: active la ROI initiale Statics: distMorph(liste de coordonees a mesurer= (coefficient, valeur initiale, valeur finale)) setteurs: setImage(ImagePlus) setImageMeasures(imagePlus) met a jours les mesures avec imagePlus setImageMidprofil(imagePlus) met a jours le profil avec imagePlus setLineWidth(width) afecte la largeur de ligne pour le profil pour Fprofile et MidProfil defaut = 0 setshowFprof(True) affiche le graphique de profil Fprofil defaut = False setMidParams(longueur mesurer l'angle de l'extremite en pixels defaut=10, coefficient pour prolonger et trouver l'intersection avec le contour defaut=1.3 """ def __Measures(self): self.__boolmeasures=True if (self.__contour is not None) and (self.__contour.getType() not in [9,10]): self.__image.killRoi() self.__image.setRoi(self.__contour) self.__ip=self.__image.getProcessor() self.__rt= ResultsTable() analyser= Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt) analyser.measure() #self.__rt.show("myRT") else: self.__rt = ResultsTable() analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.ELLIPSE+Analyzer.FERET+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MEDIAN+Analyzer.MIN_MAX+Analyzer.MODE+Analyzer.RECT+Analyzer.SHAPE_DESCRIPTORS+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, self.__rt) analyser.measure() #self.__rt.show("myRT") maxValues=self.__rt.getRowAsString(0).split("\t") heads=self.__rt.getColumnHeadings().split("\t") for val in heads: self.__rt.setValue(val, 0, Float.NaN) #self.__rt.show("myRT") # calculate the 1/2 , 1/4 ... 1/n positions for a liste while 1/n >= 1 returns a dict = 0: (0, [0, 0, pos(1/2)]) 1: (1, [-1, -0.5, -pos(1/4)], [0, 0, pos(1/2)], [1, 0.5, pos(1/2)]) def __Centers(self, line) : L=len(line) l2=L//2 l=L pos={} for i in range(self.log2(L)) : l = l//2 pos[i]=l l=L dicPos={} jtot=1 for i in range(self.log2(L)) : s=[] j=1 while (l2-j*pos[i])>0 or (l2+j*pos[i])<L : s.append((-j,(l2-j*pos[i]))) s.append((j,(l2+j*pos[i]))) j=j+1 s.append((0,l2)) s.sort() if ((len(s)+1)*pos[i]-L)//pos[i] > 0 : del s[0] del s[-1] else : pass if len(s) - 1 != 0 : jtot= (( len(s) - 1 ) / 2.00)+1 else : jtot=1 centers=[[v[0], v[0]/jtot, v[1]] for v in s] dicPos[i]=(i, centers) del(s) return dicPos #calculate angle from the center of the midline to ends def __flexAngle(self) : try : p1 = self.__midLine[0] p3 = self.__midLine[-1] except AttributeError : self.__midline() p1 = self.__midLine[0] p3 = self.__midLine[-1] icenter = self.__midCenters[0][1][0][2] p2 = self.__midLine[icenter] #xpoints = (429,472,466) #ypoints = (114,133,99) xpoints = [int(p1[0]), int(p2[0]), int(p3[0])] ypoints = [int(p1[1]), int(p2[1]), int(p3[1])] #print ypoints #return "" r = PolygonRoi(xpoints, ypoints, 3, Roi.ANGLE) return r.getAngle() def __NbFoci(self): self.__boolFoci=True self.__image.killRoi() self.__image.setRoi(self.__contour) self.__ip=self.__image.getProcessor() rt=ResultsTable.getResultsTable() rt.reset() mf=MaximumFinder() mf.findMaxima(self.__ip, self.__noise, 0, MaximumFinder.LIST, True, False) self.__listMax[:]=[] #feret=self.getFercoord() #xc=feret[0]-((feret[0]-feret[2])/2.0) #yc=feret[1]-((feret[1]-feret[3])/2.0) #print xc, yc xc=self.getXC() yc=self.getYC() #print xc, yc for i in range(rt.getCounter()): x=int(rt.getValue("X", i)) y=int(rt.getValue("Y", i)) size=self.__localwand(x, y, self.__ip, self.__seuilPeaks, self.__peaksMethod, self.__light) coord=[(1, xc, x), (1, yc, y)] d=self.distMorph(coord,"Euclidean distance") d=( d / (self.getMaxF()/2) )*100 self.__listMax.append((x, y, size[0], size[1], size[2], size[3], size[4], d)) rt.reset() def __FeretAxis(self): __boolFL=True if (self.__contour is not None) and (self.__contour.getType() in range(1,11)): self.__image.killRoi() self.__image.setRoi(self.__contour) if self.__contour.getType() in [1,5,9,10]: self.__polygon=self.__contour.getPolygon() else: self.__polygon=self.__contour.getFloatPolygon() points = self.__polygon.npoints self.__polx = self.__polygon.xpoints self.__poly = self.__polygon.ypoints diameter=0.0 for i in range(points): for j in range(i, points): dx=self.__polx[i]-self.__polx[j] dy=self.__poly[i]-self.__poly[j] d=math.sqrt(dx*dx+dy*dy) if d>diameter: diameter=d i1=i i2=j tempDictY={ self.__poly[i1]:(self.__polx[i1],self.__poly[i1],self.__polx[i2],self.__poly[i2]), self.__poly[i2]:(self.__polx[i2],self.__poly[i2],self.__polx[i1],self.__poly[i1]) } minY=min((self.__poly[i1],self.__poly[i2])) maxY=max((self.__poly[i1],self.__poly[i2])) lineTuple=tempDictY[maxY] self.__x1=lineTuple[0] self.__y1=lineTuple[1] self.__x2=lineTuple[2] self.__y2=lineTuple[3] self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2) elif (self.__contour is not None) and (self.__contour.getType()==0): self.__x2=self.__contour.getBounds().x self.__y2=self.__contour.getBounds().y self.__x1=self.__contour.getBounds().x+self.__contour.getBounds().width self.__y1=self.__contour.getBounds().y+self.__contour.getBounds().height self.__line= Line(self.__x1,self.__y1,self.__x2,self.__y2) else: self.__x1="NaN" self.__y1="NaN" self.__x2="NaN" self.__y2="NaN" self.__fprofArray="NaN" def __FeretProfile(self): """ genere le profile le long du diametre de Feret """ self.__line.setWidth(self.__lw) self.__image.setRoi(self.__line, True) self.__fprof= ProfilePlot(self.__image) self.__fprofArray=self.__fprof.getProfile() if self.__showFpro: self.__fprof.createWindow() self.__image.killRoi() self.__line.setWidth(0) self.__image.setRoi(self.__contour) return self.__fprofArray def __midline(self): debug=False #print "line 251", self.__boolML if self.__boolML : ordpoints=self.__midLine[:] npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) return polyOrd #if self.getMaxF()<15 : return None #self.__FeretAxis() #return self.__line self.__boolML=True self.__image.killRoi() self.__image.setRoi(self.__contour) boundRect=self.__contour.getBounds() boundRoi=Roi(boundRect) xori=boundRect.x yori=boundRect.y wori=boundRect.width hori=boundRect.height ip2 = ByteProcessor(self.__image.getWidth(), self.__image.getHeight()) ip2.setColor(255) ip2.setRoi(self.__contour) ip2.fill(self.__contour) skmp=ImagePlus("ip2", ip2) skmp.setRoi(xori-1,yori-1,wori+1,hori+1) ip3=ip2.crop() skmp3=ImagePlus("ip3", ip3) skmp3.killRoi() #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l287") #------------------------------------------------------------- IJ.run(skmp3, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l294") #------------------------------------------------------------- IJ.run(skmp3, "BinaryConnectivity ", "white") ip3.setThreshold(3,4, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(skmp3, "Convert to Mask", "") #------------------------------------------------------------- if debug : skmp3.show() IJ.showMessage("imp3 l302") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : skmp3.updateAndDraw() skmp3.show() IJ.showMessage("imp3 l308") #------------------------------------------------------------- rawPoints=[] w=ip3.getWidth() h=ip3.getHeight() rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] tempbouts=[val for val in rawPoints if val[2]==2] if len(tempbouts)!=2 : return None # test #if len(tempbouts)!=2 : # # IJ.run(skmp3, "BinaryConnectivity ", "white") # ip3.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) # IJ.run(skmp3, "Convert to Mask", "") # #------------------------------------------------------------- # if debug==debug : # skmp3.updateAndDraw() # skmp3.show() # IJ.showMessage("if test l 328") ##------------------------------------------------------------- # rawPoints=[(x+xori,y+yori,self.__sommeVals(x,y,ip3)) for x in range(w) for y in range(h) if ip3.getPixel(x,y)==255] # tempbouts=[val for val in rawPoints if val[2]==2] ip3.setRoi(boundRect) if rawPoints==[]: return None npoints=len(rawPoints) xpoints=[point[0] for point in rawPoints] ypoints=[point[1] for point in rawPoints] valpoints=[point[2] for point in rawPoints] bouts={} if tempbouts==[]: return None if tempbouts[0][1]>tempbouts[1][1]: bouts["A"]=tempbouts[0] bouts["B"]=tempbouts[1] else: bouts["A"]=tempbouts[1] bouts["B"]=tempbouts[0] rawPoints.remove(bouts["A"]) rawPoints.remove(bouts["B"]) rawPoints.append(bouts["B"]) tempList=[val for val in rawPoints] p=bouts["A"] Dist={} ordPoints=[] for j in range(len(rawPoints)): Dist.clear() for i in range(len(tempList)): dx=p[0]-tempList[i][0] dy=p[1]-tempList[i][1] d=math.sqrt(dx*dx+dy*dy) Dist[d]=tempList[i] distList=Dist.keys() mind=min(distList) nextpoint=Dist[mind] ordPoints.append(nextpoint) tempList.remove(nextpoint) p=nextpoint ordPoints.insert(0, bouts["A"]) npoints=len(ordPoints) if npoints < 4 : return None xpoints=[point[0] for point in ordPoints] ypoints=[point[1] for point in ordPoints] polyOrd1=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) f=min(self.__midParams[0], len(xpoints)//2) angleA1=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[1],ypoints[1]) angleA2=polyOrd1.getAngle(xpoints[1],ypoints[1], xpoints[2],ypoints[3]) angleA = (angleA1+angleA2)/2.00 angleA=polyOrd1.getAngle(xpoints[0],ypoints[0], xpoints[f],ypoints[f]) angleA=angleA*(math.pi/180) angleB1=polyOrd1.getAngle(xpoints[-2],ypoints[-2], xpoints[-1],ypoints[-1]) angleB2=polyOrd1.getAngle(xpoints[-3],ypoints[-3], xpoints[-2],ypoints[-2]) angleB = (angleB1+angleB2)/2.00 angleB=polyOrd1.getAngle(xpoints[-f],ypoints[-f], xpoints[-1],ypoints[-1]) angleB=angleB*(math.pi/180) coef=self.__midParams[1] xa = xpoints[0]-coef*f*math.cos(angleA) ya = ypoints[0]+coef*f*math.sin(angleA) xb = xpoints[-1]+coef*f*math.cos(angleB) yb = ypoints[-1]-coef*f*math.sin(angleB) lineA=Line(xpoints[0],ypoints[0], xa, ya) lineB=Line(xpoints[-1],ypoints[-1], xb, yb) lineA.setWidth(0) lineB.setWidth(0) lineA.setStrokeWidth(0) lineB.setStrokeWidth(0) ip2.setColor(0) ip2.fill() ip2.setColor(255) ip2.setRoi(lineA) lineA.drawPixels(ip2) ip2.setRoi(lineB) lineB.drawPixels(ip2) ip2.setRoi(self.__contour) ip2.setColor(0) ip2.fillOutside(self.__contour) ip2=ip2.crop() imb=ImagePlus("new-ip2", ip2) #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l416") #------------------------------------------------------------- w2=ip2.getWidth() h2=ip2.getHeight() ip4 = ByteProcessor(w2+2, h2+2) im4=ImagePlus("im4", ip4) for i in range(w2): for j in range(h2): ip4.set(i+1,j+1,max([ip2.getPixel(i,j),ip3.getPixel(i,j)])) #im4.show() #------------------------------------------------------------- if debug : im4.show() IJ.showMessage("im4 l430") #------------------------------------------------------------- im4.killRoi() #IJ.run(im4, "Skeletonize (2D/3D)", "") #IJ.run(skmp3, "Skeletonize", "") #------------------------------------------------------------- if debug : imb.show() IJ.showMessage("imb l300") #------------------------------------------------------------- #IJ.run(skmp3, "Skeletonize", "") ip4=im4.getProcessor() rawPoints2=[] w4=ip4.getWidth() h4=ip4.getHeight() rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] # test if len(self.__MidBouts)!=2 : IJ.run(im4, "BinaryConnectivity ", "white") ip4.setThreshold(3,3, ImageProcessor.BLACK_AND_WHITE_LUT) IJ.run(im4, "Convert to Mask", "") rawPoints2=[(x+xori-2,y+yori-2,self.__sommeVals(x,y,ip4)) for x in range(w4) for y in range(h4) if ip4.getPixel(x,y)==255] self.__MidBouts=[val for val in rawPoints2 if val[2]==2] ordpoints=[] p0=self.__MidBouts[0] rawPoints2.remove(p0) c=0 while p0!=self.__MidBouts[1]: if c<len(rawPoints2): point=rawPoints2[c] else: break if abs(point[0]-p0[0])<2 and abs(point[1]-p0[1])<2: p0=point ordpoints.append(point) rawPoints2.remove(point) c=0 else: c=c+1 ordpoints.insert(0, self.__MidBouts[0]) self.__midLine=ordpoints[:] self.__midCenters = self.__Centers(self.__midLine) npoints=len(ordpoints) xpoints=[point[0] for point in ordpoints] ypoints=[point[1] for point in ordpoints] polyOrd=PolygonRoi(xpoints, ypoints, npoints, PolygonRoi.POLYLINE) #print self.__midLine #print self.__MidBouts #print xpoints #print ypoints return polyOrd def __sommeVals(self, x, y, ip): return (ip.getPixel(x,y)+ip.getPixel(x-1,y-1)+ip.getPixel(x,y-1)+ip.getPixel(x+1,y-1)+ip.getPixel(x-1,y)+ip.getPixel(x+1,y)+ip.getPixel(x-1,y+1)+ip.getPixel(x,y+1)+ip.getPixel(x+1,y+1))/255 def __localwand(self, x, y, ip, seuil, method, light): self.__image.killRoi() ip.snapshot() if method == "mean" : peak=ip.getPixel(x,y) tol = (peak - self.getMean())*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) #print "method=", method, tol, peak elif method == "background" : radius = self.getMinF()/4 bs = BackgroundSubtracter() #rollingBallBackground(ImageProcessor ip, double radius, boolean createBackground, boolean lightBackground, boolean useParaboloid, boolean doPresmooth, boolean correctCorners) bs.rollingBallBackground(ip, radius, False, light, False, True, False) peak=ip.getPixel(x,y) tol = peak*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) ip.reset() #print "method=", method, tol, radius, peak else : peak=ip.getPixel(x,y) tol = peak*seuil w = Wand(ip) w.autoOutline(x, y, tol, Wand.EIGHT_CONNECTED) #print "method=", method, tol peak=ip.getPixel(x,y) temproi=PolygonRoi(w.xpoints, w.ypoints, w.npoints, PolygonRoi.POLYGON) self.__image.setRoi(temproi) #self.__image.show() #time.sleep(1) #peakip=self.__image.getProcessor() #stats=peakip.getStatistics() temprt = ResultsTable() analyser = Analyzer(self.__image, Analyzer.AREA+Analyzer.INTEGRATED_DENSITY+Analyzer.FERET, temprt) analyser.measure() #temprt.show("temprt") rtValues=temprt.getRowAsString(0).split("\t") area=float(rtValues[1]) intDen=float(rtValues[4]) feret=float(rtValues[2]) mean=intDen/area #time.sleep(2) temprt.reset() self.__image.killRoi() return [peak, area, mean, intDen, feret] def __MidProfil(self): if not self.__boolML : self.__midline() ip=self.__image.getProcessor() line=Line(self.__midLine[0][0],self.__midLine[0][1],self.__midLine[-1][0],self.__midLine[-1][1]) line.setWidth(self.__lw) self.__MprofArray=[] self.__MprofArray[:]=[] for i in range(0,len(self.__midLine)-1): templine=Line(self.__midLine[i][0],self.__midLine[i][1],self.__midLine[i+1][0],self.__midLine[i+1][1]) templine.setWidth(self.__lw) self.__image.setRoi(templine) #time.sleep(0.5) temprof= ProfilePlot(self.__image) temparray=temprof.getProfile() self.__MprofArray+=temparray templine.setWidth(0) #if self.__showMidpro: self.__fprof.createWindow() return def getFeretSegments(self, n): self.__boolFS=True if(not self.__boolFL): self.__FeretAxis() radius=self.getMinF() lsegment=self.__line.getLength()/((n-1)*2) xo=self.__x1 yo=self.__y1 xf=self.__x2 yf=self.__y2 angle1=self.getAngF()*(math.pi/180) angle2=self.getAngF()*(math.pi/180)+(math.pi/2) avancex=(lsegment*2)*math.cos(angle1) avancey=(lsegment*2)*math.sin(angle1) delta90x=(radius)*math.cos(angle2) delta90y=(radius)*math.sin(angle2) self.__line.setWidth(int(lsegment*2)) #self.__image.setRoi(self.__line) tempcontour=self.__contour.clone() shapeContour=ShapeRoi(tempcontour) segsRoi=[] for i in range(n): tempLine=Line(xo-delta90x, yo+delta90y, xo+delta90x, yo-delta90y) tempLine.setWidth(int(lsegment*2)) poly=tempLine.getPolygon() roipol=PolygonRoi(poly, Roi.POLYGON) shapePoly= ShapeRoi(roipol) interShape=shapePoly.and(shapeContour) segsRoi.append(interShape.shapeToRoi()) xo=xo+avancex yo=yo-avancey #self.__image.setRoi(self.__contour, True) #time.sleep(0) self.__line.setWidth(0) #self.__image.setRoi(tempcontour) #self.__image.updateAndDraw() return segsRoi # return Roi array def getMidSegments(self, n=10, r=5, tool=0): self.__boolMS=True if(not self.__boolML): self.__midline() lsegment=int(len(self.__midLine)/n) if lsegment<2:lsegment=2 ls2=int(len(self.__midLine)/(2*n)) if ls2<1: ls2=1 ip=self.__image.getProcessor() #print(len(self.__midLine), lsegment, ls2) xo=self.__MidBouts[0][0] yo=self.__MidBouts[0][1] xf=self.__MidBouts[1][0] yf=self.__MidBouts[1][1] line1=Line(xo,yo,xf,yf) line1.setWidth(0) angles=[line1.getAngle(self.__midLine[i][0], self.__midLine[i][1], self.__midLine[i+lsegment][0], self.__midLine[i+lsegment][1]) for i in range(0,len(self.__midLine)-lsegment,lsegment)] points=[self.__midLine[i] for i in range(0,len(self.__midLine),lsegment)] lastangle=line1.getAngle(self.__midLine[-ls2][0],self.__midLine[-ls2][1],self.__midLine[-1][0],self.__midLine[-1][1]) angles.append(lastangle) tempcontour=self.__contour.clone() shapeContour=ShapeRoi(tempcontour) angles=[angle*(math.pi/180)+(math.pi/2) for angle in angles] line1.setWidth((ls2+1)*2) segsRoi=[] linesRois=[] cRois=[] for i in range(len(angles)): x=points[i][0] y=points[i][1] cRois.append(PointRoi(x,y)) if tool==0: # ligne perpendiculaire d'epaiseur (ls2+1)*2 line1.setWidth((ls2+1)*2) x1=x+r*math.cos(angles[i]) y1=y-r*math.sin(angles[i]) x2=x-r*math.cos(angles[i]) y2=y+r*math.sin(angles[i]) #print(x, y, x1, y1, x2, y2) tempLine=Line(x1,y1,x2,y2) linesRois.append(tempLine) tempLine.setWidth((ls2+1)*2) #self.__image.setRoi(tempLine, True) #time.sleep(0.3) poly=tempLine.getPolygon() roipol=PolygonRoi(poly, Roi.POLYGON) shapePoly= ShapeRoi(roipol) elif tool==1: #r1=r*0.7 x1=x+r y1=y-r x2=x-r y2=y+r ellipse=EllipseRoi(x1, y1, x2, y2, 1) linesRois.append(ellipse) #print(x, y, x1, y1, x2, y2) #self.__image.setRoi(ellipse, True) shapePoly= ShapeRoi(ellipse) #time.sleep(0.3) else: x1=x y1=y line1.setWidth(r) if (i+1)<len(points): x2=points[i+1][0] y2=points[i+1][1] else: #x1=x+lsegment*math.cos(angles[i]-(math.pi/2)) #y1=y-lsegment*math.sin(angles[i]-(math.pi/2)) x2=x+lsegment*math.cos(angles[i]-(math.pi/2)) y2=y-lsegment*math.sin(angles[i]-(math.pi/2)) #x2=xf #y2=yf tempLine=Line(x1,y1,x2,y2) linesRois.append(tempLine) tempLine.setWidth(r) #self.__image.setRoi(tempLine, True) #time.sleep(0.5) poly=tempLine.getPolygon() roipol=PolygonRoi(poly, Roi.POLYGON) shapePoly= ShapeRoi(roipol) interShape=shapePoly.and(shapeContour) interRoi=interShape.shapeToRoi() segsRoi.append(interShape.shapeToRoi()) line1.setWidth(0) return (segsRoi, linesRois, cRois) def selectInitRoi(self): self.__image.killRoi() self.__image.setRoi(self.__contour) time.sleep(0) @staticmethod def distMorph(coord,distmethod="Euclidean distance"): if distmethod == "Euclidean distance" : s=[val[0]*(val[2]-val[1])*(val[2]-val[1]) for val in coord] #print s #print sum(s) return math.sqrt(sum(s)) if distmethod == "Logarithm distance" : s=[val[0]*abs(math.log(val[2]/val[1])) for val in coord] return sum(s) @staticmethod def log2(n) : return math.log(n)/math.log(2) def Out(self): print("out") #------ end methodes--------------- #------ constructeur ------------- def __init__(self, imp, roi): self.__lw=0 self.__showFpro=False self.__Feret=[] self.__image=imp self.__cal=imp.getCalibration() self.__contour=roi.clone() self.__boolmeasures=False self.__boolFP=False self.__boolFL=False self.__boolML=False self.__boolMP=False self.__boolFS=False self.__boolMS=False self.__boolFoci=False self.__midParams=[10, 1.3] self.__listMax=[] self.__noise=150 self.__seuilPeaks=0.75 self.__peaksMethod="mean" self.__light=False self.__distot=0.00 self.__flexangle=0.00 #print "dropbox MorphoBactProject" #---------- end constructor--------- #---------- getteurs---------------- def getMaxF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Feret", 0) def getMinF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("MinFeret", 0) def getXF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("FeretX", 0) def getYF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("FeretY", 0) def getAngF(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("FeretAngle", 0) def getArea(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Area", 0) def getMean(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Mean", 0) def getKurt(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Kurt", 0) def getSkew(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Skew", 0) def getIntDen(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("IntDen", 0) def getStdDev(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("StdDev", 0) def getAngle(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Angle", 0) def getMajor(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Major", 0) def getMinor(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Minor", 0) def getSolidity(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Solidity", 0) def getAR(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("AR", 0) def getRound(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Round", 0) def getCirc(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Circ.", 0) def getXM(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("XM",0) def getYM(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("YM",0) def getXC(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("X",0) def getYC(self): if(not self.__boolmeasures): self.__Measures() return self.__rt.getValue("Y",0) def getNfoci(self): if(not self.__boolFoci):self.__NbFoci() return len(self.__listMax) def getListFoci(self): if(not self.__boolFoci):self.__NbFoci() xy=[] for val in self.__listMax: xy.append((val[0], val[1])) return xy def getListPeaksFoci(self): if(not self.__boolFoci):self.__NbFoci() peaks=[] for val in self.__listMax: peaks.append(val[2]) return peaks def getListAreaFoci(self): if(not self.__boolFoci):self.__NbFoci() areas=[] for val in self.__listMax: areas.append(val[3]) return areas def getListMeanFoci(self): if(not self.__boolFoci):self.__NbFoci() means=[] for val in self.__listMax: means.append(val[4]) return means def getListIntDenFoci(self): if(not self.__boolFoci):self.__NbFoci() ints=[] for val in self.__listMax: ints.append(val[5]) return ints def getListFeretFoci(self): if(not self.__boolFoci):self.__NbFoci() ferets=[] for val in self.__listMax: ferets.append(val[6]) return ferets def getListDistsFoci(self): if(not self.__boolFoci):self.__NbFoci() dists=[] for val in self.__listMax: dists.append(val[7]) return dists def getFercoord(self): """ FerCoord: tuple contenant x1, y1, x2, y2 du MaxFeret """ if (not self.__boolFL): self.__FeretAxis() return (self.__x1,self.__y1,self.__x2,self.__y2) def getFprofil(self): """ Fprofil: list contenant les valeurs du profil le long de MaxFeret """ if (not self.__boolFL): self.__FeretAxis() self.__FeretProfile() return self.__fprofArray def getFerAxis(self): """ FerAxis: Line ROI """ if(not self.__boolFL): self.__FeretAxis() return self.__line def getMidAxis(self): """ MidAxis: Polyline ROI de l'axe median par skeletonize """ if(not self.__boolML): return self.__midline() def getMidSegs(self, n, r, tool): """ Rois des segments 0 = rois , 1 = points, 2 = lines ou ellipses """ if(not self.__boolMS): return self.getMidSegments(n, r, tool) def getMidProfil(self): """ MidProfil: list contenant les valeurs du profil le long de MidAxis """ self.__MidProfil() return self.__MprofArray def getMidPoints(self) : """ MidPoints : list of two extreme points of mid Axis """ if(not self.__boolML): self.__midline() return self.__MidBouts def getCenters(self) : if(not self.__boolML): self.__midline() return self.__midCenters def getFlexAngle(self) : return self.__flexAngle() #------ setteurs -------- def setImage(self, imp): self.__image=imp def setImageMeasures(self, imp): self.__image=imp self.__Measures() def setImageFprofil(self, imp): self.__image=imp self.__FeretProfile() def setImageMidprofil(self, imp): self.__image=imp self.__MidProfil() def setLineWidth(self, lw): self.__lw=lw def setshowFpro(self, fpshow): self.__showFpro=fpshow def setMidParams(self, lseg, coeff): self.__midParams[:]=[] self.__midParams.append(lseg) self.__midParams.append(coeff) def setNoise(self, noise): self.__noise=noise def setSeuilPeaks(self, seuil): self.__seuilPeaks=seuil def setpeaksMethod(self, method): self.__peaksMethod=method def setlight(self, light): self.__light=light #------- properties ----------------------- MaxFeret=property(getMaxF, setImageMeasures, doc="caliper max Feret=") MinFeret=property(getMinF, setImageMeasures, doc="caliper min Feret=") AngleFeret=property(getAngF, setImageMeasures, doc="angle Feret=") XFeret=property(getXF, setImageMeasures, doc="X Feret=") YFeret=property(getYF, setImageMeasures, doc="Y Feret=") Area=property(getArea, setImageMeasures, doc="Area=") Mean=property(getMean, setImageMeasures, doc="Mean=") Kurt=property(getKurt, setImageMeasures, doc="Kurtosis=") Skew=property(getSkew, setImageMeasures, doc="Skewness=") IntDen=property(getIntDen, setImageMeasures, doc="Integrated Intensity=") StdDev=property(getStdDev, setImageMeasures, doc="Standard Deviation=") Angle=property(getAngle, setImageMeasures, doc="Angle=") Major=property(getMajor, setImageMeasures, doc="Major ellipse axis=") Minor=property(getMinor, setImageMeasures, doc="Minor ellipse axis=") Solidity=property(getSolidity, setImageMeasures, doc="Solidity area/convexHull=") AR=property(getAR, setImageMeasures, doc="Major axis/Minor axis=") Round=property(getRound, setImageMeasures, doc="Area/(pi*Major*Major)=1/AR=") Circ=property(getCirc, setImageMeasures, doc="(4*pi*Area)/(perimeter*perimeter)=") XM=property(getXM, setImageMeasures, doc="X center of Mass=") YM=property(getYM, setImageMeasures, doc="Y center of Mass=") XC=property(getXC, setImageMeasures, doc="X of centroid=") YC=property(getYC, setImageMeasures, doc="Y of centroid=") NFoci=property(getNfoci, setImageMeasures, doc="nb foci in the roi=") ListFoci=property(getListFoci, setImageMeasures, doc="list of foci coordinates=") ListPeaksFoci=property(getListPeaksFoci, setImageMeasures, doc="list of foci peaks=") ListAreaFoci=property(getListAreaFoci, setImageMeasures, doc="list of foci areas=") ListMeanFoci=property(getListMeanFoci, setImageMeasures, doc="list of foci means=") ListIntDenFoci=property(getListIntDenFoci, setImageMeasures, doc="list of foci IntDen=") ListFeretFoci=property(getListFeretFoci, setImageMeasures, doc="list of foci Ferets=") ListDistsFoci=property(getListDistsFoci, setImageMeasures, doc="list of foci distances=") FerCoord=property(getFercoord, doc="x1, y1, x2, y2 of Feret diameter =") Fprofil=property(getFprofil, setImageFprofil, doc="Profil along Feret diameter") # return array values FerAxis=property(getFerAxis, doc="ROI along Feret diameter") # return Roi MidAxis=property(getMidAxis, doc="ROI along the median axis") # return Roi MidProfil=property(getMidProfil, setImageMidprofil, doc="profile values of mid axis") # return array values MidPoints=property(getMidPoints, doc= "extreme points of mid line") Centers=property(getCenters, doc= "list of positions (tuples) of 1/2 of the midaxis, 1/4, 1/8 ...") # return a list of tuples FlexAngle=property(getFlexAngle, doc="angle of the center of midline to ends")
loadmethod = "de.embl.cmci.io.ResultsTableLoader" # Path to the partcile analysis results path = "/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/coords.csv" # Path to the binary image, to be plotted with area. # binimgpath = '/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/mask10frames.tif' binimgpath = "/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/mask20framesOrg.tif" # binimgpath = '/Users/miura/Dropbox/people/Giogia_Stefano/toJoe/mask_z4_furrowSeg1.0.6_threshOffest5e-04_closingSize3_200f.tif' imp = IJ.openImage(binimgpath) # paOpt = PA.CLEAR_WORKSHEET +\ paOpt = PA.SHOW_OUTLINES + PA.EXCLUDE_EDGE_PARTICLES # +\ # PA.INCLUDE_HOLES #+ \ # PA.SHOW_RESULTS measOpt = PA.AREA + PA.CENTROID + PA.SLICE # + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY rt = ResultsTable() MINSIZE = 2 MAXSIZE = 10000 pa = PA(paOpt, measOpt, rt, MINSIZE, MAXSIZE) pa.setHideOutputImage(True) # pa.processStack = True for i in range(imp.getStackSize()): imp.setSlice(i + 1) pa.analyze(imp) # pa.getOutputImage().show() rt.show("cells") # rt = ResultsTable.open2(path) dotlinker = DotLinker(loadmethod, rt) # better there is a constructor also with linkkost function object. dotlinker.setTrajectoryThreshold(5) dotlinker.setShowTrackTable(False)
# Process list of images for (counter, f) in enumerate(files): # Display progress IJ.showStatus("Processing file "+ str(counter+1) +"/"+ str(len(files))) # Open each image and process it imp = IJ.openImage(f) myRoutines(imp) # Save processed image in out_dir (enforcing .tif extension) newpath = os.path.splitext(out_dir + imp.getTitle())[0] +".tif" IJ.saveAsTiff(imp, newpath) imp.close() # Log paths of processed files csvWriter.writerow([f, newpath]) # Display CSV log csvFile.close() rt = ResultsTable.open(csvPath) rt.show("_ProcessedFileList.csv") # Proudly inform that processing terminated if IJ.showMessageWithCancel("All done","Reveal output directory?"): Utils.revealFile(out_dir); else: # Inform no filtered files were found IJ.error("No matches for the selected extension(s).")