def measure_rm(img_path, roi_path): imp = IJ.openImage(img_path) img_dir = imp.getOriginalFileInfo().directory img_file = imp.getOriginalFileInfo().fileName ip = imp.getProcessor() cal = Calibration(imp) rm = RoiManager() rm = RoiManager.getInstance() rm.runCommand("Open", roi_path) roi_array = rm.getRoisAsArray() moptions = Measurements.MEAN | Measurements.AREA for roi in roi_array: roi_name = roi.getName() ip.setRoi(roi) stat = ImageStatistics.getStatistics(ip, moptions, cal) IJ.log(img_dir + "\t" + img_file + "\t" + roi_name + "\t" + str(stat.pixelCount) + "\t" + str(stat.pixelCount * stat.umean) + "\t" + str(stat.umean)) rm.runCommand("delete")
def measureTumor(original, locations): '''Returns the area from the original image with the highest kurtosis which generally corresponds to the most in focus image. Also saves an image corresponding to a mask of the measurement.''' # Prevent ROI manager from appearing roiM = RoiManager(True) ParticleAnalyzer.setRoiManager(roiM) # Locate particles above a minimum size and with a desired circularity IJ.run(locations, "Analyze Particles...", "size=" + str(minimumCancerArea) +"-" + str(maxCancerArea) +" circularity=" + str(circularityCutoff) + "-1.00 show=Nothing exclude add stack"); # Choose ROI with the highest kurtosis maxKurtosis = None area = None selectedROI = None for roi in roiM.getRoisAsArray(): original.setRoi(roi) stats = original.getStatistics(Measurements.KURTOSIS, Measurements.AREA) currentKurtosis = stats.kurtosis if currentKurtosis > maxKurtosis: maxKurtosis = stats.kurtosis area = stats.area selectedROI = roi original.killRoi() # Remove the remaining ROI roiM.runCommand("Reset") return (area, selectedROI)
def resetpressed(event): self.__ranges.clear() self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() 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() #rm.runCommand("Show All") #rm.runCommand("Select All") #rm.runCommand("Set Color", "blue") IJ.resetThreshold(self.__image) keys=self.__slidersDict.keys() for k in keys: if k.endswith("min"): self.__slidersDict[k].setValue(0) self.__slidersDict[k].repaint() else: self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum()) self.__slidersDict[k].repaint()
def load_qcd_edges2(input_file_path): """load edges from roi *.zip file""" if os.path.isfile(input_file_path): roim = RoiManager(False) roim.runCommand("Open", input_file_path) edges = roim.getRoisAsArray() roim.close() else: edges = load_qcd_edges(os.path.splitext(input_file_path)[0] + '.json') return edges
def apply_roi_arr(func): rm = RoiManager() rm = rm.getInstance() roi_arr = rm.getRoisAsArray() # => list result_list = [] for roi in roi_arr: result = func(roi) if result is not None: result_list.append(result) return result_list
def perform_manual_qc(imp, rois, important_channel=1): """given cell rois generated by automatic methods, allow user to delete/add/redraw as appropriate""" for ch in range(imp.getNChannels()): imp.setC(ch + 1) sat_frac = 0.99 if (ch + 1) == important_channel else 0.01 IJ.run(imp, "Enhance Contrast", "saturated={}".format(sat_frac)) imp.setC(important_channel) IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") for roi in rois: roim.addRoi(roi) auto_rois_only = rois while not proceed: dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual correction of segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T). " ) dialog.addMessage("Delete and redraw cells as appropriate. ") dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added. " ) dialog.showDialog() if dialog.wasCanceled(): print("Manual segmentation canceled") return auto_rois_only elif dialog.wasOKed(): if roim.getCount() == 0: rois = [] confirm_dialog = GenericDialog("Continue?") confirm_dialog.addMessage( "No rois selected in this FOV. Are you sure you want to proceed?" ) confirm_dialog.setOKLabel("Yes, proceed") confirm_dialog.setCancelLabel("No, not yet") confirm_dialog.showDialog() if confirm_dialog.wasOKed(): proceed = True else: rois = roim.getRoisAsArray() proceed = True roim.reset() roim.close() for ch in range(imp.getNChannels()): imp.setC(ch + 1) IJ.run(imp, "Enhance Contrast", "saturated={}".format(0.35)) imp.setC(important_channel) return rois
def generate_cell_rois(seg_binary_imp): """generate rois from which cell shape information will be gleaned""" seg_binary_imp.killRoi() mxsz = seg_binary_imp.width * seg_binary_imp.height roim = RoiManager(False) pa_options = ParticleAnalyzer.AREA | ParticleAnalyzer.PERIMETER | ParticleAnalyzer.SHAPE_DESCRIPTORS pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, pa_options, None, 1000, mxsz) pa.setRoiManager(roim) roim.reset() pa.analyze(seg_binary_imp) rois = roim.getRoisAsArray() roim.reset() roim.close() return rois
def get_no_nuclei_fully_enclosed(roi, full_nuclei_imp, overlap_threshold=0.65): """for a given cell roi and ImagePlus with binary nuclei, return how many nuclei lie ENTIRELY within the cell""" bbox = roi.getBounds() full_nuclei_imp.setRoi(roi) cropped_nuc_imp = full_nuclei_imp.crop() roi.setLocation(0, 0) cropped_nuc_imp.setRoi(roi) cropped_nuc_imp.killRoi() roim = RoiManager(False) mxsz = cropped_nuc_imp.getWidth() * cropped_nuc_imp.getHeight() pa = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, None, 0, mxsz) pa.setRoiManager(roim) pa.analyze(cropped_nuc_imp) cell_imp = IJ.createImage("Cell binary", cropped_nuc_imp.getWidth(), cropped_nuc_imp.getHeight(), 1, 8) IJ.run(cell_imp, "Select All", "") IJ.run(cell_imp, "Set...", "value=0 slice") cell_imp.setRoi(roi) IJ.run(cell_imp, "Set...", "value=255 slice") no_enclosed_nuclei = 0 for idx, nuc_roi in enumerate(roim.getRoisAsArray()): test_imp = Duplicator().run(cell_imp) test_imp.setRoi(nuc_roi) IJ.run(test_imp, "Set...", "value=255 slice") test_imp.killRoi() IJ.run(test_imp, "Create Selection", "") IJ.run(test_imp, "Make Inverse", "") test_roi = test_imp.getRoi() test_roi_stats = test_roi.getStatistics() cell_roi_stats = roi.getStatistics() nuc_roi_stats = nuc_roi.getStatistics() if test_roi_stats.area < ( cell_roi_stats.area + (1 - overlap_threshold) * nuc_roi_stats.area ): # i.e. if more than (100*overlap_threshold)% of nucleus is inside cell... no_enclosed_nuclei += 1 test_imp.changes = False test_imp.close() roi.setLocation(bbox.getX(), bbox.getY()) cropped_nuc_imp.changes = False cropped_nuc_imp.close() cell_imp.changes = False cell_imp.close() return no_enclosed_nuclei
def save_roi_set(imp=IJ.getImage()): img_dir, name = get_file_info() roi_dir = make_roi_dir(img_dir, name) roi_path = make_roi_path(roi_dir, name) Roi.setColor(Color.blue) rm = RoiManager().getInstance() rm.deselect() rm.runCommand("Save", roi_path) ol = imp.getOverlay() if ol is None: ol = Overlay() for roi in rm.getRoisAsArray(): ol.add(roi) imp.setOverlay(ol) rm.runCommand("delete") ol.setStrokeColor(Color.blue) Roi.setColor(Color.yellow)
def manual_analysis(imp, file_name, output_folder): """perform analysis based on manually drawn cells""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T)") dialog.addMessage( "You can see what you've added so far if you check \"show all\" on the ROI manager" ) dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added") dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") elif dialog.wasOKed(): rois = roim.getRoisAsArray() roim.reset() roim.close() out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats return None
def RoiSelection(): true=1 false=0 IJ.run("Invert", "stack"); IJ.run("Fill Holes", "stack"); IJ.run("Create Selection"); rm = RoiManager() rm.runCommand("add") rm.runCommand("split") #number_selected=rm.getCount() IJ.run("Select None"); rm.runCommand("deselect") #rm.select(0) #print number_selected roi_array=rm.getRoisAsArray() max_roi=None max_points=-1 for roi in roi_array: polygon=roi.getPolygon() if polygon is not None: number_of_points = polygon.npoints if max_points < number_of_points: max_points=number_of_points max_roi=roi #print max_points #sorted_roi_array=sorted(roi_array, key=methodcaller('getLength'), reverse=True) #length_array=[] #index=0 #for roi in roi_array: # index=index+1 # length_array.append((index,roi.getLength())) #sorted_length_array=sorted(length_array, key=itemgetter(0)) rm.runCommand("Select All") rm.runCommand("Delete") #for roi in roi_array: interpolated_polygon=max_roi.getInterpolatedPolygon(20,True) roi_polygon=PolygonRoi(interpolated_polygon,Roi.POLYGON) rm.addRoi(roi_polygon)
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): # set calibration detectionParameters.setCalibration(inputImp) # calculate area of roi stats = inputImp.getStatistics() inputRoiArea = stats.area # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1 = long(inputRec.getX()) y1 = long(inputRec.getY()) x2 = x1 + long(inputRec.getWidth()) - 1 y2 = y1 + long(inputRec.getHeight()) - 1 # crop the roi interval = FinalInterval(array([x1, y1, 0], 'l'), array([x2, y2, 2], 'l')) #cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) cropped = ops.image().crop(inputDataset.getImgPlus(), interval) datacropped = data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus = IJ.getImage() # instantiate the duplicator and the substackmaker classes duplicator = Duplicator() substackMaker = SubstackMaker() # duplicate the roi duplicate = duplicator.run(croppedPlus) # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", "") brightnessPlus = substackMaker.makeSubstack(duplicate, "3-3") brightness = ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate = duplicator.run(croppedPlus) channels = ChannelSplitter().split(duplicate) redPlus = channels[0] red = ImgPlus(ImageJFunctions.wrapByte(redPlus)) # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus = IJ.getImage() croppedPlus.changes = False croppedPlus.close() # get the A channel APlus = substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') #APlus.show() APlus.getProcessor().resetMinAndMax() #APlus.updateAndDraw() AThresholded = threshold(APlus, -10, 50) # get the B channel BPlus = substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') #BPlus.show() BPlus.getProcessor().resetMinAndMax() #BPlus.updateAndDraw() BThresholded = threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator() redMask = ic.run("AND create", AThresholded, BThresholded) IJ.run(redMask, "Divide...", "value=255") labPlus.close() fast = True # threshold the spots from the red channel if (fast == False): thresholdedred = SpotDetectionGray(red, data, display, ops, "triangle") impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") else: impthresholdedred = SpotDetection2(redPlus) # threshold the spots from the brightness channel if (fast == False): thresholded = SpotDetectionGray(brightness, data, display, ops, "triangle") impthresholded = ImageJFunctions.wrap(thresholded, "wrapped") else: impthresholded = SpotDetection2(brightnessPlus) # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred) roim = RoiManager(True) # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean > detectionParameters.porphyrinRedPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean > detectionParameters.porphyrinRedPercentage): return False else: return True roiClone = inputRoi.clone() roiClone.setLocation(0, 0) Utility.clearOutsideRoi(impthresholded, roiClone) impthresholded.show() countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \ detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity) uvPoreList = [] for roi in roim.getRoisAsArray(): uvPoreList.append(roi.clone()) #allList=uvPoreList+closedPoresList+openPoresList # count particles that are porphyrins (red) porphyrinList = CountParticles.filterParticlesWithFunction( redMask, uvPoreList, isRed) # count particles that are visible on uv but not porphyrins sebumList = CountParticles.filterParticlesWithFunction( redMask, uvPoreList, notRed) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [ roi.setLocation(roi.getXBase() + x1, roi.getYBase() + y1) for roi in uvPoreList ] # draw the ROIs on to the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3") inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1") [ CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList ] [ CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList ] inputImp.updateAndDraw() # calculate stats for the UV visible particles detectionParameters.setCalibration(APlus) statsDictUV = CountParticles.calculateParticleStatsUV( APlus, BPlus, redMask, roim.getRoisAsArray()) totalUVPoreArea = 0 for area in statsDictUV['Areas']: totalUVPoreArea = totalUVPoreArea + area averageUVPoreArea = totalUVPoreArea / len(statsDictUV['Areas']) poreDiameter = 0 for diameter in statsDictUV['Diameters']: poreDiameter = poreDiameter + diameter poreDiameter = poreDiameter / len(statsDictUV['Diameters']) redTotal = 0 for red in statsDictUV['redPercentage']: redTotal = redTotal + red redAverage = redTotal / len(statsDictUV['redPercentage']) statslist = [len(porphyrinList), 100 * redAverage] statsheader = [Messages.Porphyrins, Messages.PercentageRedPixels] print("Roi Area: " + str(inputRoiArea)) print("Total Pore Area: " + str(totalUVPoreArea)) print("Average Pore Area: " + str(averageUVPoreArea)) print str(len(uvPoreList)) + " " + str(len(porphyrinList)) + " " + str( len(sebumList)) + " " + str( 100 * totalUVPoreArea / inputRoiArea) + " " + str(100 * redAverage) print "cp min circularity" + str( detectionParameters.closedPoresMinCircularity) + ":" + str( detectionParameters.closedPoresMinSize) # close the thresholded image impthresholded.changes = False impthresholded.close() return uvPoreList, statslist, statsheader
display.createDisplay("log", data.create(ImgPlus(log))) otsu=ops.run("threshold", ops.create( dimensions2D, BitType()), imgBgs, Otsu()) display.createDisplay("thresholded", data.create(ImgPlus(otsu))) ''' #Utility.clearOutsideRoi(imp, clone) IJ.run(imp, "Auto Local Threshold", "method=MidGrey radius=15 parameter_1=0 parameter_2=0 white"); IJ.run(imp, "Fill Holes", ""); IJ.run(imp, "Close-", ""); IJ.run(imp, "Watershed", ""); iplus.updateAndDraw() # create a hidden roi manager roim = RoiManager(True) # count the particles countParticles(iplus, roim, 10, 200, 0.5, 1.0) [truecolor1.getProcessor().draw(roi) for roi in roim.getRoisAsArray()] truecolor1.updateAndDraw() #Prefs.blackBackground = False; #IJ.run("Make Binary", ""); #IJ.run("LoG 3D"); #IJ.run("Duplicate...", "title="+"test") #IJ.run("RGB Stack"); #IJ.run("Convert Stack to Images");
preview.show() rm = RoiManager() dialog = WaitForUserDialog("Action required", "Please select regions of interest in this image. Click OK when done.") dialog.show() rm.close() splitter = ChannelSplitter() imp1 = ImagePlus("CH1", splitter.getChannel(image, imageA)) imp2 = ImagePlus("CH2", splitter.getChannel(image, imageB)) title = image.getTitle() title = title[:title.rfind('.')] image.close() preview.close() ch1 = ImagePlusAdapter.wrap(imp1) ch2 = ImagePlusAdapter.wrap(imp2) for roi in rm.getRoisAsArray(): container = createContainer(roi, ch1, ch2) img1 = container.getSourceImage1() img2 = container.getSourceImage2() mask = container.getMask() thr1, thrimp1 = calculateThreshold(imp1, roi, methods[0]) thr2, thrimp2 = calculateThreshold(imp2, roi, methods[1]) 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(thr1) rthr2.set(thr2)
image_title = img.getShortTitle() # make paths for moving when done. full_img_path_orig = os.path.join(blinded_base, image_title + ".tif") full_img_path_done = os.path.join(data, image_title + ".tif") # get roi manager roim = RoiManager().getRoiManager() # make savepaths for csv and rois roimsave = os.path.join(data, image_title + "_rois.zip") csvsave = os.path.join(data, image_title + "_data.csv") csv_ = [["image", "roi_name", "uncalibrated_length"]] for roi, _ in enumerate(roim.getRoisAsArray()): target = roim.getRoi(roi) csv_.append([image_title, target.getName(), target.getLength()]) # write and save csv with open(csvsave, "w") as c: writer = csv.writer(c) for l in csv_: writer.writerow(l) # save rois roim.runCommand("Deselect") roim.runCommand("Save", roimsave) # close both roim.close()
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 StackCells(swing.JFrame): def __init__(self): swing.JFrame.__init__(self, title="Stack Cells") self.__impD = IJ.getImage() self.setDefaultCloseOperation(swing.JFrame.DISPOSE_ON_CLOSE) self.__n=0 self.__widthl = "11" self.__iplist = [] self.__init = False self.__initDIA = False self.__initFLUO = False self.__skip = False self.__avg = True self.__mosa = True self.__maxfinder = True self.__appmedian = True self.__fire = True self.__align = True self.__alignC = False self.__enlarge = True self.__measures = True self.__sens = [] self.__listrois = [] self.__cellsrois = [] self.__Cutoff = 0 self.__labels = [] self.__maxraf = 100.0 self.__minraf = 0.0 self.__conEllipses = False self.__dictCells = {} self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() self.run() def run(self) : self.size=(1100, 400) self.contentPane.layout = awt.BorderLayout() self.__display = swing.JTextField(preferredSize=(400, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__setDisplay() line = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) northpanel1=swing.JPanel(awt.FlowLayout(awt.FlowLayout.LEFT)) northpanel1.setBorder(line) northpanel1.add(self.__display) new = swing.JButton("New", size=(100, 70), actionPerformed=self.__new) northpanel1.add(new) add = swing.JButton("Add", size=(100, 70), actionPerformed=self.__add) northpanel1.add(add) roiman = swing.JButton("Add Roi manager", size=(100, 70), actionPerformed= self.__addroi) northpanel1.add(roiman) end = swing.JButton("End", size=(100, 70), actionPerformed= self.__end) northpanel1.add(end) #grid = awt.GridLayout() #grid.setRows(2) #northpanel=swing.JPanel(grid) #northpanel.add(northpanel1) #northpanel2=swing.JPanel(awt.FlowLayout(awt.FlowLayout.LEFT)) grid0 = awt.GridLayout() grid0.setRows(6) northpanel2=swing.JPanel(grid0) northpanel2.setBorder(line) label=swing.JLabel("Label2") label.setText("Line width ?") northpanel2.add(label) self.__display2 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display2.text = "11" northpanel2.add(self.__display2) label=swing.JLabel("Label3") label.setText("Noise for peaks ?") northpanel2.add(label) self.__display3 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display3.text = "100" northpanel2.add(self.__display3) label=swing.JLabel("Label4") label.setText("Fluo threshold ?") northpanel2.add(label) self.__display4 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display4.text = "170" northpanel2.add(self.__display4) #northpanel3=swing.JPanel(awt.FlowLayout(awt.FlowLayout.LEFT)) #northpanel3.setBorder(line) label=swing.JLabel("Label5") label.setText("Min of length ?") northpanel2.add(label) self.__display5 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display5.text = "50" northpanel2.add(self.__display5) label=swing.JLabel("Label6") label.setText("Max of length ?") northpanel2.add(label) self.__display6 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display6.text = "500" northpanel2.add(self.__display6) dia = swing.JButton("DIA", size=(100, 70), actionPerformed= self.__dia) northpanel2.add(dia) fluo = swing.JButton("FLUO", size=(100, 70), actionPerformed= self.__fluo) northpanel2.add(fluo) southpanel=swing.JPanel(awt.FlowLayout(awt.FlowLayout.RIGHT)) southpanel.setBorder(line) help = swing.JButton("Help", size=(100, 70), actionPerformed=self.__help) self.__label=swing.JLabel("Label") southpanel.add(self.__label) close = swing.JButton("Close", size=(100, 70), actionPerformed=self.__close) southpanel.add(help) southpanel.add(close) grid = awt.GridLayout() grid.setRows(4) checkpanel=swing.JPanel(grid) checkpanel.setBorder(line) self.__box0=swing.JCheckBox(actionPerformed=self.__boxaction0) self.__box0.setText("Skip failed ROIs") self.__box0.setSelected(False) self.__box1=swing.JCheckBox(actionPerformed=self.__boxaction1) self.__box1.setText("Mosaic") self.__box1.setSelected(True) self.__box2=swing.JCheckBox(actionPerformed=self.__boxaction2) self.__box2.setText("Mean Projection") self.__box2.setSelected(True) self.__box3=swing.JCheckBox(actionPerformed=self.__boxaction3) self.__box3.setText("Max Finder") self.__box3.setSelected(True) self.__box4=swing.JCheckBox(actionPerformed=self.__boxaction4) self.__box4.setText("Median filter") self.__box4.setSelected(True) self.__box5=swing.JCheckBox(actionPerformed=self.__boxaction5) self.__box5.setText("Fire LUT") self.__box5.setSelected(True) self.__box6=swing.JCheckBox(actionPerformed=self.__boxaction6) self.__box6.setText("Auto Align Left") self.__box6.setSelected(True) self.__box7=swing.JCheckBox(actionPerformed=self.__boxaction7) self.__box7.setText("Auto Enlarge") self.__box7.setSelected(True) self.__box8=swing.JCheckBox(actionPerformed=self.__boxaction8) self.__box8.setText("Measures") self.__box8.setSelected(True) self.__box9=swing.JCheckBox(actionPerformed=self.__boxaction9) self.__box9.setText("Auto Align Center") self.__box9.setSelected(False) self.__box10=swing.JCheckBox(actionPerformed=self.__boxaction10) self.__box10.setText("Use ellipses") self.__box10.setSelected(False) checkpanel.add(self.__box0) checkpanel.add(self.__box1) checkpanel.add(self.__box2) checkpanel.add(self.__box3) checkpanel.add(self.__box4) checkpanel.add(self.__box5) checkpanel.add(self.__box6) checkpanel.add(self.__box7) checkpanel.add(self.__box8) checkpanel.add(self.__box9) checkpanel.add(self.__box10) grid = awt.GridLayout() grid.setRows(10) checkpanel2=swing.JPanel(grid) checkpanel2.setBorder(line) label=swing.JLabel("Label7") label.setText("Max of Solidity") checkpanel2.add(label) self.__display7 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display7.text = "1" checkpanel2.add(self.__display7) label=swing.JLabel("Label8") label.setText("Min of Solidity") checkpanel2.add(label) self.__display8 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display8.text = "0" checkpanel2.add(self.__display8) label=swing.JLabel("Label9") label.setText("Max of Area") checkpanel2.add(label) self.__display9 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display9.text = "1447680" checkpanel2.add(self.__display9) label=swing.JLabel("Label10") label.setText("Min of Area") checkpanel2.add(label) self.__display10 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display10.text = "1" checkpanel2.add(self.__display10) label=swing.JLabel("Label11") label.setText("Max of Circ") checkpanel2.add(label) self.__display11 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display11.text = "1" checkpanel2.add(self.__display11) label=swing.JLabel("Label12") label.setText("Min of Circ") checkpanel2.add(label) self.__display12 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display12.text = "0" checkpanel2.add(self.__display12) label=swing.JLabel("Label13") label.setText("Max of AR") checkpanel2.add(label) self.__display13 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display13.text = "1392" checkpanel2.add(self.__display13) label=swing.JLabel("Label14") label.setText("Min of AR") checkpanel2.add(label) self.__display14 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display14.text = "1" checkpanel2.add(self.__display14) label=swing.JLabel("Label15") label.setText("Max of Feret") checkpanel2.add(label) self.__display15 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display15.text = "1392" checkpanel2.add(self.__display15) label=swing.JLabel("Label16") label.setText("Min of Feret") checkpanel2.add(label) self.__display16 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display16.text = "1" checkpanel2.add(self.__display16) label=swing.JLabel("Label17") label.setText("Max of Mean") checkpanel2.add(label) self.__display17 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display17.text = "65535" checkpanel2.add(self.__display17) label=swing.JLabel("Label18") label.setText("Min of Mean") checkpanel2.add(label) self.__display18 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display18.text = "0" checkpanel2.add(self.__display18) label=swing.JLabel("Label19") label.setText("max ratio Axis/Feret") checkpanel2.add(label) self.__display19 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display19.text = str(self.__maxraf) checkpanel2.add(self.__display19) label=swing.JLabel("Label20") label.setText("Min ratio Axis/Feret") checkpanel2.add(label) self.__display20 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display20.text = str(self.__minraf) checkpanel2.add(self.__display20) label=swing.JLabel("Label21") label.setText("Max MinFeret") checkpanel2.add(label) self.__display21 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display21.text = "1392" checkpanel2.add(self.__display21) label=swing.JLabel("Label22") label.setText("Min MinFeret") checkpanel2.add(label) self.__display22 = swing.JTextField(preferredSize=(50, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__display22.text = "1" checkpanel2.add(self.__display22) self.contentPane.add(northpanel1, awt.BorderLayout.NORTH) self.contentPane.add(checkpanel, awt.BorderLayout.WEST) self.contentPane.add(northpanel2, awt.BorderLayout.CENTER) self.contentPane.add(southpanel, awt.BorderLayout.SOUTH) self.contentPane.add(checkpanel2, awt.BorderLayout.EAST) def __close(self, event): self.oked = True time.sleep(0.01) self.dispose() def __new(self, event): self.__init = True self.__n += 1 self.__name = "stackcells"+str(self.__n) self.__display.text = self.__name self.__sens[:] = [] self.__listrois[:] = [] self.__iplist[:] = [] self.__cellsrois[:] = [] self.__labels[:] = [] def __add(self, event): if ( not self.__init) : IJ.showMessage("", "please start a new stack") return if ( not self.__initDIA) : IJ.showMessage("", "please select an image for DIA") return if ( not self.__initFLUO) : IJ.showMessage("", "please select an image for FLUO") return self.__widthl = self.__display2.getText() roi = self.__impD.getRoi() if roi == None : IJ.showMessage("", "No selection") return if roi.getType() in [6,7] : nslice = self.__impD.getCurrentSlice() self.__impF.setSlice(nslice) self.__impF.setRoi(roi) elif roi.getType() in [2,4] : nslice = self.__impD.getCurrentSlice() self.__impF.setSlice(nslice) m=Morph(self.__impF, roi) m.setMidParams(10, 2) roi=m.MidAxis if roi == None : self.__display.text = "roi fail" if not self.__skip : IJ.showMessage("", "failed roi, please draw it as polyline") return #if roi.getType() != 6 : self.__impF.setRoi(roi) else : IJ.showMessage("", "This selection is not yet allowed") return self.__impF.setRoi(roi) straightener = Straightener() new_ip = straightener.straighten(self.__impF, roi, int(self.__widthl)) self.__iplist.append(new_ip) self.__labels.append(self.__isF.getShortSliceLabel(nslice)) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) +" width="+str(new_ip.getWidth())+ " height="+ str(new_ip.getHeight()) roi.setPosition(self.__impD.getCurrentSlice()) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() self.__rm.add(self.__impD, roi, len(self.__iplist)) self.__cellsrois.append((roi, self.__impD.getCurrentSlice())) #self.__rm.runCommand("Show All") IJ.selectWindow(self.__impD.getTitle()) def __end(self, event): if len(self.__iplist)==0 : IJ.showMessage("", "Stack is empty") return self.__ipw=[ ip.getWidth() for ip in self.__iplist ] self.__iph=[ ip.getHeight() for ip in self.__iplist ] maxw=max(self.__ipw) maxh=max(self.__iph) if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in self.__iplist ] else : resizelist = [] for ip in self.__iplist : tempip = ShortProcessor(maxw, maxh) tempip.copyBits(ip, 0, 0, Blitter.COPY) resizelist.append(tempip) ims = ImageStack(maxw, maxh) #for ip in resizelist : ims.addSlice("", ip) for i in range(len(resizelist)) : ims.addSlice(self.__labels[i], resizelist[i]) self.__impRes = ImagePlus(self.__name, ims) self.__impRes.show() self.__sens = [1 for i in range(len(self.__iplist)) ] if self.__appmedian : IJ.run(self.__impRes, "Median...", "radius=1 stack") if self.__align : self.__falign() if self.__avg : self.__favg() if self.__mosa : self.__fmosa() if self.__maxfinder : self.__fmaxfinder() if self.__fire : IJ.run(self.__impRes, "Fire", "") if self.__measures : self.__fmeasures() self.__sens[:] = [] self.__listrois[:] = [] self.__iplist[:] = [] self.__cellsrois[:] = [] self.__ipw[:] = [] self.__iph[:] = [] self.__init = False def __dia(self, event): IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") #IJ.run("Properties...", "channels=1 slices=1 frames=20 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000 frame=[1 sec] origin=0,0"); self.__impD = IJ.getImage() self.__isD = self.__impD.getImageStack() self.__display.text = "DIA="+self.__impD.getTitle() self.__initDIA = True def __fluo(self, event): IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") self.__impF = IJ.getImage() self.__isF = self.__impF.getImageStack() self.__display.text = "FLUO="+self.__impF.getTitle() self.__initFLUO = True def __addroi(self, event) : if ( not self.__init) : IJ.showMessage("", "please start a new stack") return if ( not self.__initDIA) : IJ.showMessage("", "please select an image for DIA") return if ( not self.__initFLUO) : IJ.showMessage("", "please select an image for FLUO") return twres = TextWindow("measures-"+self.__name, "label\tname\tsol\tarea\tcirc\tAR\tFeret\taxis\traf\tdMajor\tdFeret\tdArea", "", 300, 450) tab="\t" self.__widthl = self.__display2.getText() IJ.selectWindow(self.__impF.getTitle()) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() if self.__impF.getImageStackSize() > 1 : roisarray =[(roi, self.__rm.getSliceNumber(roi.getName())) for roi in self.__rm.getRoisAsArray()] else : roisarray =[(roi, 1) for roi in self.__rm.getRoisAsArray()] self.__rm.runCommand("reset") #self.__rm.runCommand("Delete") IJ.selectWindow(self.__impF.getTitle()) self.__maxraf=float(self.__display19.text) self.__minraf=float(self.__display20.text) count=1 for roielement in roisarray : roi = roielement[0] pos = roielement[1] lab = self.__impF.getImageStack().getShortSliceLabel(pos) if lab==None : lab=str(pos) if self.__conEllipses : IJ.selectWindow(self.__impF.getTitle()) self.__impF.setSlice(pos) self.__impF.setRoi(roi) self.__rm.runCommand("Add") IJ.run(self.__impF, "Fit Ellipse", "") ellipse=self.__impF.getRoi() params = ellipse.getParams() ferets = ellipse.getFeretValues() imp2 = Duplicator().run(self.__impF,pos,pos) IJ.run(imp2, "Rotate... ", "angle="+str(ferets[1])+" grid=0 interpolation=Bilinear enlarge slice") temproi=Roi((imp2.getWidth()-ferets[0])/2.0,(imp2.getHeight()-ferets[2])/2.0,ferets[0],ferets[2]) imp2.setRoi(temproi) imp3 = Duplicator().run(imp2,1,1) ip3=imp3.getProcessor() if int(self.__display5.text) < ip3.getWidth() < int(self.__display6.text) : self.__iplist.append(ip3) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) fer=Line(params[0],params[1],params[2],params[3]) self.__cellsrois.append((fer, pos)) self.__labels.append(self.__isF.getShortSliceLabel(pos)) m=Morph(self.__impF, roi) twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(fer.getLength())+tab+str(1)+tab+str(0)+tab+str(0)+tab+str(0)) self.__dictCells[count]=(str(roi.getName()), lab, roi) count=count+1 continue if roi.getType() in [6,7] : self.__impF.setSlice(pos) self.__impF.setRoi(roi) self.__rm.runCommand("Add") elif roi.getType() in [2,4] : self.__impF.setSlice(pos) self.__impF.setRoi(roi) m=Morph(self.__impF, roi) m.setMidParams(10, 2) midroi=m.MidAxis if midroi == None : continue raf = m.MaxFeret/midroi.getLength() if (self.__maxraf < raf) or (raf < self.__minraf) : continue maxsol = float(self.__display7.text) minsol = float(self.__display8.text) maxarea = float(self.__display9.text) minarea = float(self.__display10.text) maxcirc = float(self.__display11.text) mincirc = float(self.__display12.text) maxar = float(self.__display13.text) minar = float(self.__display14.text) maxfer = float(self.__display15.text) minfer = float(self.__display16.text) maxmean = float(self.__display17.text) minmean = float(self.__display18.text) maxmferet = float(self.__display21.text) minmferet = float(self.__display22.text) testsol = (minsol< m.Solidity < maxsol) testarea = (minarea< m.Area < maxarea) testcirc = (mincirc< m.Circ < maxcirc) testar = (minar< m.AR < maxar) testfer = (minfer< m.MaxFeret < maxfer) testmean = (minmean < m.Mean < maxmean) testmferet = (minmferet < m.MinFeret < maxmferet) #print minmferet , m.MinFeret , maxmferet test = (testsol+testarea+testcirc+testar+testfer+testmean+testmferet)/7 if test : fmaj, ffmx, fa =[],[],[] for r in m.getMidSegments(10, 40, 0) : if r == None : continue m2=Morph(self.__impF, r) fmaj.append(m2.Major) ffmx.append(m2.MaxFeret) fa.append(m2.Area) diffmajor, diffferet, diffarea = 0,0,0 if len(fa) > 4 : medfmaj = self.listmean(fmaj[1:-1]) medffmx = self.listmean(ffmx[1:-1]) medfa = self.listmean(fa[1:-1]) diffmajor = (max(fmaj[1:-1])-medfmaj)/medfmaj diffferet = (max(ffmx[1:-1])-medffmx)/medffmx diffarea = (max(fa[1:-1])-medfa)/medfa twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea)) #print lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea) self.__impF.setRoi(roi) self.__rm.runCommand("Add") self.__impF.killRoi() self.__impF.setRoi(midroi) #self.__dictCells[str(roi.getName())]=(str(roi.getName()), lab, roi) self.__dictCells[count]=(str(roi.getName()), lab, roi) count=count+1 else : #print "test falls" continue else : print "out loop" continue straightener = Straightener() new_ip = straightener.straighten(self.__impF, midroi, int(self.__widthl)) if int(self.__display5.text) < new_ip.getWidth() < int(self.__display6.text) : self.__iplist.append(new_ip) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) #print "add", roi.getName(), roi.getType() self.__cellsrois.append((midroi, pos)) self.__labels.append(self.__isF.getShortSliceLabel(pos)) #roisarray=self.__rm.getRoisAsArray() #self.__rm.runCommand("reset") #self.__rm.runCommand("Delete") self.__impD.killRoi() self.__impF.killRoi() IJ.selectWindow(self.__impD.getTitle()) def __boxaction0(self, event): self.__skip = event.getSource().isSelected() def __boxaction1(self, event): self.__mosa = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction2(self, event): self.__avg = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction3(self, event): self.__maxfinder = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction4(self, event): self.__appmedian = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction5(self, event): self.__fire = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction6(self, event): self.__align = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction7(self, event): self.__enlarge = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction8(self, event): self.__measures = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction9(self, event): self.__alignC = event.getSource().isSelected() #self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) def __boxaction10(self, event): self.__conEllipses = event.getSource().isSelected() def __favg(self) : zp = ZProjector(self.__impRes) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() imp = zp.getProjection() imp.show() if self.__fire : IJ.run(imp, "Fire", "") def __fmosa(self) : mm = MontageMaker() imp = mm.makeMontage2(self.__impRes, 1, self.__impRes.getStackSize(), 1, 1, self.__impRes.getStackSize(), 1, 0, False) imp.setTitle("MONTAGE"+self.__name) imp.show() if self.__fire : IJ.run(imp, "Fire", "") def __fmaxfinder(self) : #stack = self.__impRes.getStack() self.__impD.killRoi() self.__impF.killRoi() stack = self.__impF.getStack() n_slices = stack.getSize() #newstack=ImageStack(self.__impRes.getWidth(), self.__impRes.getHeight()) newstack=ImageStack(self.__impF.getWidth(), self.__impF.getHeight()) noise = self.__display3.text for index in range(1,n_slices+1): IJ.selectWindow(self.__impF.getTitle()) self.__impF.setSlice(index) ip = self.__impF.getProcessor() mf=MaximumFinder() ipmax = mf.findMaxima(ip, int(noise), 0, 0, False, False) newstack.addSlice("", ipmax) newimage=ImagePlus("max points"+self.__name, newstack) newimage.show() newimage.updateAndDraw() listip = [] maxh=self.__impRes.getHeight() for roi in self.__cellsrois : straightener = Straightener() newimage.setSlice(roi[1]) newimage.setRoi(roi[0]) #listip.append(straightener.straighten(newimage, roi[0], int(self.__widthl))) listip.append(straightener.straighten(newimage, roi[0], maxh)) ipw=[ ip.getWidth() for ip in listip ] iph=[ ip.getHeight() for ip in listip ] maxw=max(ipw) maxh=max(iph) if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in listip ] elif self.__alignC : resizelist = [] for ip in listip : tempip = ByteProcessor(maxw, maxh) tempip.copyBits(ip, 0, 0, Blitter.COPY) resizelist.append(tempip) else : resizelist = [] for ip in listip : tempip = ByteProcessor(maxw, maxh) tempip.copyBits(ip, 0, 0, Blitter.COPY) resizelist.append(tempip) ims = ImageStack(maxw, maxh) #for ip in resizelist : ims.addSlice("", ip) for i in range(len(resizelist)) : ims.addSlice(self.__labels[i], resizelist[i]) self.__impMax = ImagePlus(self.__name+"-max", ims) self.__impMax.show() stack = self.__impMax.getStack() # get the stack within the ImagePlus n_slices = stack.getSize() for index in range(1, n_slices+1): self.__impMax.killRoi() self.__impMax.setSlice(index) roi = self.__listrois[index-1] if self.__sens[index-1]<0 : self.__impMax.setRoi(roi) ip1 = self.__impMax.getProcessor() ip1.flipHorizontal() self.__impMax.killRoi() self.__impMax.updateAndDraw() ip = self.__impMax.getProcessor() for i in range(ip.getWidth()*ip.getHeight()) : if ip.getf(i) > 0 : ip.setf(i, 255) #else : ip.setf(i, 0) IJ.run(self.__impMax, "8-bit", "") IJ.run(self.__impMax, "Options...", "iterations=2 count=1 black edm=Overwrite do=Close stack") IJ.run(self.__impMax, "Ultimate Points", "stack") self.__impMax.updateAndDraw() def __falign(self) : #self.__impRes=IJ.getImage() stack = self.__impRes.getStack() # get the stack within the ImagePlus n_slices = stack.getSize() # get the number of slices ic = ImageCalculator() w = self.__impRes.getWidth() h = self.__impRes.getHeight() self.__sens[:] = [] self.__listrois[:] = [] for index in range(1, n_slices+1): self.__impRes.setSlice(index) ip1 = stack.getProcessor(index) imp1 = ImagePlus("imp1-"+str(index), ip1) imp1sqr = ic.run("Multiply create 32-bit", imp1, imp1) IJ.setThreshold(imp1sqr, 1, 4294836225) IJ.run(imp1sqr, "Create Selection", "") roi = imp1sqr.getRoi() rect=roi.getBounds() roi = Roi(rect) self.__listrois.append(roi) ipsqr = imp1sqr.getProcessor() is1 = ipsqr.getStatistics() self.__impRes.killRoi() if is1.xCenterOfMass > w/2.00 : self.__impRes.setRoi(roi) ip1 = self.__impRes.getProcessor() ip1.flipHorizontal() self.__impRes.killRoi() self.__sens.append(-1) else : self.__sens.append(1) self.__impRes.updateAndDraw() def __fmeasures(self) : self.__Cutoff = float(self.__display4.text) nslices = self.__impRes.getImageStackSize() rt = ResultsTable() rt.show("RT-"+self.__name) twpoints = TextWindow("points-"+self.__name, "index\tlabel\tname\tx\ty\taxis\tcellw\tcellh", "", 200, 450) twlabels = TextWindow("labels-"+self.__name, "index\tlabel\tname\tnpoints", "", 200, 450) isres = self.__impRes.getImageStack() for index in range(1, nslices+1): self.__impRes.setSlice(index) self.__impRes.killRoi() roi = self.__listrois[index-1] self.__impRes.setRoi(roi) analyser= Analyzer(self.__impRes, Analyzer.LABELS+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MIN_MAX+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, rt) analyser.measure() rt.show("RT-"+self.__name) rect=roi.getBounds() ip = self.__impRes.getProcessor() xCoord = [] yCoord = [] currentPixel = [] m00 = 0.00 m10 = 0.00 m01 = 0.00 mc20 = 0.00 mc02 = 0.00 mc11 = 0.00 mc30 = 0.00 mc03 = 0.00 mc21 = 0.00 mc12 = 0.00 mc40 = 0.00 mc04 = 0.00 mc31 = 0.00 mc13 = 0.00 mm20 = 0.00 mm02 = 0.00 mm11 = 0.00 mm30 = 0.00 mm03 = 0.00 mm21 = 0.00 mm12 = 0.00 mm40 = 0.00 mm04 = 0.00 mm31 = 0.00 mm13 = 0.00 for y in range(rect.y, rect.y+rect.height, 1) : for x in range(rect.x, rect.x+rect.width, 1) : xCoord.append(x+0.5) yCoord.append(y+0.5) #pixel=ip.getf(x,y)-self.__Cutoff pixel = ip.getPixelValue(x,y)-self.__Cutoff if pixel < 0 : pixel = 0 currentPixel.append(pixel) m00 += currentPixel[-1] m10 += currentPixel[-1]*xCoord[-1] m01 += currentPixel[-1]*yCoord[-1] xm = m10/(m00+0.00000001) ym = m01/(m00+0.00000001) xc = rect.width/2.00 yc = rect.height/2.00 for i in range(rect.width*rect.height) : xcrel = xCoord[i]-xc ycrel = yCoord[i]-yc #mc20 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc) #mc02 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc) #mc11 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc) # #mc30 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc) #mc03 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc) #mc21 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(yCoord[i]-yc) #mc12 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)*(yCoord[i]-yc) # #mc40 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc) #mc04 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc) #mc31 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)*(yCoord[i]-yc) #mc13 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc) mc20 += currentPixel[i]*xcrel*xcrel mc02 += currentPixel[i]*ycrel*ycrel mc11 += currentPixel[i]*xcrel*ycrel mc30 += currentPixel[i]*xcrel*xcrel*xcrel mc03 += currentPixel[i]*ycrel*ycrel*ycrel mc21 += currentPixel[i]*xcrel*xcrel*ycrel mc12 += currentPixel[i]*xcrel*ycrel*ycrel mc40 += currentPixel[i]*xcrel*xcrel*xcrel*xcrel mc04 += currentPixel[i]*ycrel*ycrel*ycrel*ycrel mc31 += currentPixel[i]*xcrel*xcrel*xcrel*ycrel mc13 += currentPixel[i]*xcrel*ycrel*ycrel*ycrel for i in range(rect.width*rect.height) : mm20 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm) mm02 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym) mm11 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym) mm30 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm) mm03 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym) mm21 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(yCoord[i]-ym) mm12 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)*(yCoord[i]-ym) mm40 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm) mm04 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym) mm31 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)*(yCoord[i]-ym) mm13 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym) xxcVar = mc20/m00 yycVar = mc02/m00 xycVar = mc11/m00 xcSkew = mc30/(m00 * math.pow(xxcVar,(3.0/2.0))) ycSkew = mc03/(m00 * math.pow(yycVar,(3.0/2.0))) xcKurt = mc40 / (m00 * math.pow(xxcVar,2.0)) - 3.0 ycKurt = mc04 / (m00 * math.pow(yycVar,2.0)) - 3.0 ecc = (math.pow((mc20-mc02),2.0)+(4.0*mc11*mc11))/m00 xxmVar = mm20/m00 yymVar = mm02/m00 xymVar = mm11/m00 xmSkew = mm30/(m00 * math.pow(xxmVar,(3.0/2.0))) ymSkew = mm03/(m00 * math.pow(yymVar,(3.0/2.0))) xmKurt = mm40 / (m00 * math.pow(xxmVar,2.0)) - 3.0 ymKurt = mm04 / (m00 * math.pow(yymVar,2.0)) - 3.0 ecm = (math.pow((mm20-mm02),2.0)+(4.0*mm11*mm11))/m00 rt.addValue("xxcVar", xxcVar) rt.addValue("yycVar", yycVar) rt.addValue("xycVar", xycVar) rt.addValue("xcSkew", xcSkew) rt.addValue("ycSkew", ycSkew) rt.addValue("xcKurt", xcKurt) rt.addValue("ycKurt", ycKurt) rt.addValue("Ecc", ecc) rt.addValue("xxmVar", xxmVar) rt.addValue("yymVar", yymVar) rt.addValue("xymVar", xymVar) rt.addValue("xmSkew", xmSkew) rt.addValue("ymSkew", ymSkew) rt.addValue("xmKurt", xmKurt) rt.addValue("ymKurt", ymKurt) rt.addValue("Ecm", ecm) rt.addValue("roiw", rect.width) rt.addValue("roih", rect.height) rt.addValue("cellw", self.__ipw[index-1]) rt.addValue("cellh", self.__iph[index-1]) self.__impRes.killRoi() xCoord[:] = [] yCoord[:] = [] currentPixel[:] = [] points = [] points[:] = [] npointsmax = 0 #lab = self.__labels[index-1] nameroi = self.__dictCells[index][0] lab = self.__dictCells[index][1] self.__impMax.setSlice(index) ipmax = self.__impMax.getProcessor() for y in range(ipmax.getHeight()) : for x in range(ipmax.getWidth()) : if ipmax.getPixelValue(x,y) > 0 : #print str(index) #print lab #print nameroi #print str(x) #print str(y) #print str(self.__cellsrois[index-1][0].getLength()) #print str(self.__ipw[index-1]) #print str(self.__iph[index-1]) twpoints.append(str(index)+"\t"+lab+"\t"+nameroi+"\t"+str(x)+"\t"+str(y)+"\t"+str(self.__cellsrois[index-1][0].getLength())+"\t"+str(self.__ipw[index-1])+"\t"+str(self.__iph[index-1])) npointsmax+=1 rt.addValue("npoints", npointsmax) twlabels.append(str(index)+"\t"+lab+"\t"+nameroi+"\t"+str(npointsmax)) rt.show("RT-"+self.__name) rt.show("RT-"+self.__name) def __setDisplay(self, val=""): self.__display.text = str(val) def setLabel(self, text): self.__label.setText(text) def listmean(self, l) : return float(sum(l)/len(l)) def listmedian(self, l) : s=l[:] s.sort() w=len(l) return float(s[(w-1)/2]) if (w%2 == 1) else float((s[w/2]+s[(w/2)-1]))/2 def __help(self, event): IJ.log(""" -------------------------------------------------------------------------------------- New = Starts a new process with stacked cells Add = Adds un ROI as a new cell in the stack (poly segments line or a closed area ROI) Add Roi manager = adds all the ROIs contained in the roi manager End = Stops the stack process and generates images and results -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- Line width = width of the cells in pixels. Noise for peaks = value passed to detect peaks function Fluo threshold = value of the background in the fluo image. Used for acurated calculus of moments. Min length = filter for small short cells Max length = filter for long cells -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- DIA = Select the image and click to set the source image for cells ROI FLUO = Select the image and click to set the image containig the fluorescence signal (if Add Roi manager selected, this is not take in to account) -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- Skip failed ROIs = debug option Generate Mosaic = Generates a vertcal image with all the stacked cells Mean Projection = creates the projection of all cells by mean method Create maxFinder = uses the maxFinder function to generate peaks information Apply median = smooth the streched images by a 3x3 median filter Apply Fire LUT = shows all images with false colors (Fire LUT) Auto Align = Flip the cells to align the center of mass in the left part of the images Auto enlarge = Stretch the cell to fit the length of the longuest cell Generate measures = creates a text windows with measures parameters. """)
# Make the ROIs based on the mask IJ.setThreshold(imgMask, 1, 255, "Red") IJ.run(imgMask, "Analyze Particles...", "size=200 exclude add stack") roiManager.runCommand("Show None") maskStk = imgMask.getStack() im410Stk = img410.getStack() im470Stk = img470.getStack() areas = [] angles = [] xs = [] ys = [] # TODO: subtract median here? ra = roiManager.getRoisAsArray() for i in range(maskStk.getSize()): ip = im410Stk.getProcessor(i+1) ip.setRoi(ra[i]) istats = ip.getStatistics() dataTable.setValue('Intensity410_wholePharynx', i, istats.mean) ip = im470Stk.getProcessor(i+1) ip.setRoi(ra[i]) istats = ip.getStatistics() dataTable.setValue('Intensity470_wholePharynx', i, istats.mean) # TODO: Figure out units for Area dataTable.setValue('Area (Px)', i, istats.area) # we don't need to keep track of these in our `data` object, just need them to do the rotations
def segmentation(imp, spot_data, channel, diameter_init, ES_tolerance, ES_area_max, ES_ctrl_pts, ES_iteration, repeat_max): # Open files cal = imp.getCalibration() manager = RoiManager.getInstance() if manager is None: manager = RoiManager() # Prepare log files for output options = IS.MEDIAN | IS.AREA | IS.MIN_MAX | IS.CENTROID | IS.PERIMETER | IS.ELLIPSE | IS.SKEWNESS convergence = [] Sintensity = [] for spot in spot_data: repeat = 0 flag = False spotID = int(spot[0]) Xcenter = (float(spot[1]) / cal.pixelWidth) Ycenter = (float(spot[2]) / cal.pixelHeight) Quality = float(spot[3]) diameter_init = float(spot[4] / cal.pixelWidth) * 2.0 while True: manager = RoiManager.getInstance() if manager is None: manager = RoiManager() Xcurrent = int(Xcenter - diameter_init / 2.0) Ycurrent = int(Ycenter - diameter_init / 2.0) Dcurrent1 = int(diameter_init * (1.2 - repeat / 10.0)) Dcurrent2 = int(diameter_init * (0.8 + repeat / 10.0)) roi = OvalRoi(Xcurrent, Ycurrent, Dcurrent1, Dcurrent2) imp.setPosition(channel) imp.setRoi(roi) Esnake_options1 = "target_brightness=Bright control_points=" + \ str(ES_ctrl_pts) + " gaussian_blur=0 " Esnake_options2 = "energy_type=Contour alpha=2.0E-5 max_iterations=" + \ str(ES_iteration) + " immortal=false" IJ.run(imp, "E-Snake", Esnake_options1 + Esnake_options2) roi_snake = manager.getRoisAsArray() roi_ind = len(roi_snake) - 1 stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) perimeter = roi_snake[roi_ind].getLength() * cal.pixelWidth circularity = 4.0 * 3.1417 * (stats.area / (perimeter * perimeter)) if stats.area > 17.0 and stats.area < ES_area_max and stats.skewness < -0.01 and circularity > 0.01 and stats.minor > 2.0 and boundaries(Xcenter, Ycenter, stats.xCentroid / cal.pixelWidth, stats.yCentroid / cal.pixelHeight, ES_tolerance): Sintensity = stats.median convergence.append(True) break if stats.median > 6000 and stats.area > 17.0 and stats.area < ES_area_max: Sintensity = stats.median convergence.append(True) break elif repeat > repeat_max: manager.select(imp, roi_ind) manager.runCommand(imp, 'Delete') roi = OvalRoi(Xcenter + 1.0 - diameter_init / 2.0, Ycenter + 1.0 - diameter_init / 2.0, diameter_init, diameter_init) imp.setRoi(roi) manager.add(imp, roi, spotID) roi_snake.append(roi) stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) Sintensity = stats.median convergence.append(False) break else: IJ.log('Area=' + str(stats.area) + ' Skewness=' + str(stats.skewness) + ' circularity=' + str(circularity) + ' Minor=' + str(stats.minor)) manager.select(imp, roi_ind) manager.runCommand(imp, 'Delete') repeat += 1 # End Spot-segmentation # End all Spots-segmentation manager.runCommand(imp, 'Show All') imp.setPosition(channel) color = imp.createImagePlus() ip = imp.getProcessor().duplicate() color.setProcessor("segmentation" + str(channel), ip) color.show() IJ.selectWindow("segmentation" + str(channel)) manager.moveRoisToOverlay(color) spot_optimal = manager.getRoisAsArray() manager.reset() for i in xrange(0, len(spot_optimal)): spot = spot_optimal[i] spot.setStrokeWidth(2) if convergence[i]: spot.setStrokeColor(Color.GREEN) else: spot.setStrokeColor(Color.MAGENTA) imp.setRoi(spot) manager.add(imp, spot, i) manager.runCommand(imp, 'Show All') imp.setPosition(channel)
def batch_open_Rois(pathRoi, file_typeRoi=None, name_filterRoi=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the Rois. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Reject files that contain the given string (default: wild characters). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathRoi, File): pathRoi = pathRoi.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeRoi: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeRoi, (list, tuple)): for file_type_ in file_typeRoi: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeRoi, string): if string.endswith(file_typeRoi): return True else: return False return False # Accept all files if file_type is None. else: return True # We collect all files to open in a list. path_to_Roi = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathRoi) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathRoi): full_path = os.path.join(pathRoi, file_name) if os.path.isfile(full_path): if check_type(file_name): path_to_Roi.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathRoi): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): # Add the file to the list of Rois to open. path_to_Roi.append([ full_path, os.path.basename(os.path.splitext(full_path)[0]) ]) # Create the list that will be returned by this function. RoisX = [] RoisY = [] print('path', path_to_Roi) for roi_path in path_to_Roi: print('path', roi_path) # An object equals True and None equals False. rm = RoiManager.getInstance() if (rm == None): rm = RoiManager() Roi = IJ.open(roi_path) roi_points = rm.getRoisAsArray() table = ResultsTable() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints for i in range(len(xpoints)): table.incrementCounter() table.addValue("Index", i) table.addValue("X", xpoints[i]) table.addValue("Y", ypoints[i]) table.show("XY-Coordinates") return roi_points
reffn = odref.getFileName() if reffn is None: print "User canceled the dialog!" else: refdir = odref.getDirectory() refpath = os.path.join(refdir, reffn) refImp = IJ.openImage(refpath) width = refImp.width height = refImp.height roim = RoiManager() roim.runCommand("open", roipath) roiArray = roim.getRoisAsArray() nRoi = len(roiArray) roim.close() bwStack = ImageStack(width, height, nRoi) for i in xrange(1, nRoi+1): bwStack.setProcessor(FloatProcessor(width, height, zeros('f', width * height), None), i) for i in xrange(1, nRoi+1): roi = roiArray[i-1] fp = bwStack.getProcessor(i) fp.setValue(1.0) fp.fill(roi) roiImp = ImagePlus("roi", bwStack)
from operator import itemgetter, attrgetter from ij.gui import PolygonRoi, Roi true=1 false=0 IJ.run("Invert", "stack"); IJ.run("Fill Holes", "stack"); IJ.run("Create Selection"); rm = RoiManager() rm.runCommand("add") rm.runCommand("split") #number_selected=rm.getCount() IJ.run("Select None"); rm.runCommand("deselect") #rm.select(0) #print number_selected roi_array=rm.getRoisAsArray() max_roi=None max_points=-1 for roi in roi_array: polygon=roi.getPolygon() if polygon is not None: number_of_points = polygon.npoints if max_points < number_of_points: max_points=number_of_points max_roi=roi #print max_points #sorted_roi_array=sorted(roi_array, key=methodcaller('getLength'), reverse=True) #length_array=[] #index=0 #for roi in roi_array:
def process(subFolder, outputDirectory, filename): #IJ.close() imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif")) imp.show() # Get the pixel values from the xml file for file in os.listdir(inputDirectory + subFolder): if file.endswith('.xml'): xml = os.path.join(inputDirectory + subFolder, file) xml = "C:/Users/Harris/Desktop/test_xml_for_parsing_pixel.xml" element_tree = ET.parse(xml) root = element_tree.getroot() for dimensions in root.iter('DimensionDescription'): num_pixels = int(dimensions.attrib['NumberOfElements']) if dimensions.attrib['Unit'] == "m": length = float(dimensions.attrib['Length']) * 1000000 else: length = float(dimensions.attrib['Length']) pixel_length = length / num_pixels else: pixel_length = 0.8777017 IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=" + str(pixel_length) + " pixel_height=" + str(pixel_length) + " voxel_depth=25400.0508001") ic = ImageConverter(imp) ic.convertToGray8() #IJ.setThreshold(imp, 2, 255) #Automatically selects the area of the organoid based on automated thresholding and creates a mask to be applied on #all other images IJ.setAutoThreshold(imp, "Mean dark no-reset") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Analyze Particles...", "size=100000-Infinity add select") rm = RoiManager.getInstance() num_roi = rm.getCount() for i in num_roi: imp = getCurrentImage() rm.select(imp, i) IJ.setBackgroundColor(0, 0, 0) IJ.run(imp, "Clear Outside", "") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Dark") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Bright") # Save the mask and open it IJ.saveAs("tiff", inputDirectory + '/mask' + i) mask = IJ.openImage(inputDirectory + '/mask' + i + '.tif') if not displayImages: imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 bigAreas = [None] * 5 imp.close() # Loop to open all the channel images for chan in channels: v, x = chan images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", "_ch0" + str(x) + ".tif")) # Apply Mask on all the images and save them into an array apply_mask = ImageCalculator() images[x] = apply_mask.run("Multiply create 32 bit", mask, images[x]) ic = ImageConverter(images[x]) ic.convertToGray8() imp = images[x] # Calculate the intensities for each channel as well as the organoid area for roi in rm.getRoisAsArray(): imp.setRoi(roi) stats_i = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats_i.mean bigAreas[x] = stats_i.area rm.close() # Opens the ch00 image and sets default properties #Get the pixel values from the xml file for file in os.listdir(subFolder): if file.endswith('.xml'): xml = os.path.join(inputDirectory + subFolder, file) xml = "C:/Users/Harris/Desktop/test_xml_for_parsing_pixel.xml" element_tree = ET.parse(xml) root = element_tree.getroot() for dimensions in root.iter('DimensionDescription'): num_pixels = int(dimensions.attrib['NumberOfElements']) if dimensions.attrib['Unit'] == "m": length = float(dimensions.attrib['Length']) * 1000000 else: length = float(dimensions.attrib['Length']) pixel_length = length / num_pixels else: pixel_length = 0.8777017 imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) imp = apply_mask.run("Multiply create 32 bit", mask, imp) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=" + str(pixel_length) + "pixel_height=" + str(pixel_length) + "voxel_depth=25400.0508001") # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() IJ.run(imp, "Remove Outliers...", "radius=2" + " threshold=50" + " which=Dark") IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur)) IJ.setThreshold(imp, lowerBounds[0], 255) if displayImages: imp.show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if not displayImages: imp.changes = False imp.close() # 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, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) # imp = impM # imp.getProcessor().invert() pa.analyze(imp) areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [None] * 5 for chan in channels: v, x = chan # Opens each image and thresholds imp = images[x] IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, lowerBounds[x], 255) if displayImages: imp.show() WaitForUserDialog("Title", "Adjust Threshold for Marker " + v).show() IJ.run(imp, "Convert to Mask", "") # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray[x] = areaFractions roim.close() for chan in channels: v, x = chan imp = images[x] imp.deleteRoi() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.analyze(imp) blobs = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA) blobs.append(stats.area) blobsarea[x] = sum( blobs ) #take this out and use intial mask tissue area from the beginning blobsnuclei[x] = len(blobs) if not displayImages: imp.changes = False imp.close() roim.reset() roim.close() imp.close() # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} summary['Image'] = filename summary['Directory'] = subFolder # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'Image', 'size-average', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) summary["organoid-area"] = bigAreas[x] fieldnames.append("organoid-area") for chan in channels: v, x = chan summary[v + "-positive"] = 0 fieldnames.append(v + "-positive") summary[v + "-intensity"] = intensities[x] fieldnames.append(v + "-intensity") summary[v + "-blobsarea"] = blobsarea[x] fieldnames.append(v + "-blobsarea") summary[v + "-blobsnuclei"] = blobsnuclei[x] fieldnames.append(v + "-blobsnuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 for z, area in enumerate(areas): log.write(str(area)) log.write("\n") if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for chan in channels: v, x = chan if areaFractionsArray[x][z] > areaFractionThreshold[ 0]: # theres an error here im not sure why. i remember fixing it before summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[2][z] > areaFractionThreshold[2]: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold[2]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][z] > areaFractionThreshold[1]: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", '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) IJ.run(imp, "Close All", "")
IJ.log("-------start at "+now+" ------") #for cell in listfilescells : f1 = open(rootdir+now+"-R1-MT.txt", "w") tab="\t" f1.write("cell"+tab+"maxFrames"+tab+"maxcumul"+tab+"nrevs"+"\n") for cle in listcellname : rm.runCommand("reset") #cle = cell.rsplit("/", 1)[1][:-len(".cell")] #cles.append(cle) rm.runCommand("Open", dictRois[cle]) rm.runCommand("Show None") RawroisArray=rm.getRoisAsArray() if len(RawroisArray)< minLife : continue roisArray=[RawroisArray[i] for i in range(0,len(RawroisArray), subs)] IJ.showStatus(cle) IJ.showProgress(listcellname.index(cle), len(listcellname)) dxA=[] dyA=[] dxB=[] dyB=[] dA=[] dB=[] sensA = 1 sensB = -1 nrev = 0
reffn = odref.getFileName() if reffn is None: print "User canceled the dialog!" else: refdir = odref.getDirectory() refpath = os.path.join(refdir, reffn) refImp = IJ.openImage(refpath) width = refImp.width height = refImp.height roim = RoiManager() roim.runCommand("open", roipath) roiArray = roim.getRoisAsArray() nRoi = len(roiArray) roim.close() bwStack = ImageStack(width, height, nRoi) for i in xrange(1, nRoi + 1): bwStack.setProcessor( FloatProcessor(width, height, zeros('f', width * height), None), i) for i in xrange(1, nRoi + 1): roi = roiArray[i - 1] fp = bwStack.getProcessor(i) fp.setValue(1.0) fp.fill(roi) roiImp = ImagePlus("roi", bwStack)
from ij.plugin.frame import RoiManager from ij.plugin.filter import ParticleAnalyzer from ij import IJ # get active image imp=IJ.getImage() # set up first ROI manager table1 = ResultsTable() roim1=RoiManager() pa1 = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN|Measurements.ELLIPSE, table1, 0, 100, 0, 1) pa1.setRoiManager(roim1) pa1.analyze(imp) # set up second ROI manager table2 = ResultsTable() # Pass true to second ROI manager so it will not be seen roim2=RoiManager(True) pa2 = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA|Measurements.MEAN|Measurements.ELLIPSE, table2, 100, 500, 0, 1) pa2.setRoiManager(roim2) pa2.analyze(imp) print "rois from first manager:" for roi in roim1.getRoisAsArray(): print roi print print "rois from second manager:" for roi in roim2.getRoisAsArray(): print roi
def __calRois(self, imp, indice) : """ Returns the ROIs of a slice given (identified with its n°) in a stack """ ##imp=self.__dictImages[nameimages] # IL FAUT RÉCUPÉRER L'IMAGE DU STACK !!!!! #if self.__batch : imp.hide() #else : imp.show() #imp.hide() imp.show() if self.__batch : imp.hide() imp.setSlice(indice) imp.killRoi() ip = imp.getProcessor() bs=BackgroundSubtracter() #if str(self.__subback) == "0" or str(self.__subback) == "1" : self.__subback = bool(int(self.__subback)) #if self.__subback == True : IJ.run(imp, "Subtract Background...", "rolling="+str(self.__radius)+" light") if self.__subback == True : bs.rollingBallBackground(ip, self.__radius, False, True, False, True, False) if self.__runmacro : imp.show() imp.setSlice(indice) imp.updateAndDraw() IJ.runMacroFile(self.__macropath, imp.getTitle()) imp.updateAndDraw() #if str(self.__manthresh) == "0" or str(self.__manthresh) == "1" : self.__manthresh = bool(int(self.__manthresh)) #if self.__manthresh : IJ.setThreshold(imp, self.__minthr, self.__maxthr) if self.__manthresh : ip.setThreshold(self.__minthr, self.__maxthr, ImageProcessor.RED_LUT) else : self.__setThreshold(imp, indice) rt=ResultsTable() pa1=ParticleAnalyzer(ParticleAnalyzer.SHOW_MASKS+ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES , Measurements.AREA, rt, self.__minArea, self.__maxArea, self.__minCirc, self.__maxCirc) pa1.setHideOutputImage(True) pa1.analyze(imp) masks=pa1.getOutputImage() masks.getProcessor().erode() masks.getProcessor().dilate() masks.getProcessor().invertLut() masks.getProcessor().threshold(1) rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") #rm.hide() pa2=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET+ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES , Measurements.AREA, rt, self.__minArea, self.__maxArea, self.__minCirc, self.__maxCirc) pa2.analyze(masks) masks.close() temparray=rm.getRoisAsArray() for r in temparray : tempnameroi=r.getName() r.setPosition(indice) r.setName(str(indice)+"-"+tempnameroi) r.setStrokeWidth(1) if len(self.__params) > 0 : for k in self.__params: #if k[0]=="Area": self.__minArea, self.__maxArea = str(k[1]), str(k[2]) if k[0]=="Area": self.__minArea, self.__maxArea = k[1], k[2] for k in self.__params: #if k[0]=="Circ": self.__minCirc, self.__maxCirc = str(k[1]), str(k[2]) if (k[0]=="Circ") and k[3] : self.__minCirc, self.__maxCirc = k[1], k[2] else : self.__minCirc, self.__maxCirc = 0, 1 self.__rr.setRoisarray(temparray, imp) self.__rr.setRange(indice, self.__params) return self.__rr.includeRois else : return temparray
class CellsSelection(swing.JFrame): def __init__(self): swing.JFrame.__init__(self, title="Cells Selection") self.setFont(awt.Font("Courrier", 1, 10)) self.__dictBox = {} self.__dictFiles = {} self.oked = False self.__mem=[] self.setDefaultCloseOperation(swing.JFrame.DISPOSE_ON_CLOSE) def run(self, cells, path) : self.__cells=cells cells.sort() self.__cells.sort() self.__path=path if len(cells) <= 6 : cols=len(cells) rows=1 else : cols=6 rows=int(len(cells)/6)+1 #print "cols", cols, "rows", rows self.setFont(awt.Font("Courrier", 1, 10)) #self.size=(max(200*cols, 1100), max(70*rows, 300)) self.size=(max(150*cols, 800), max(50*rows, 250)) line = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) self.contentPane.layout = awt.BorderLayout() self.__display = swing.JTextField(preferredSize=(400, 30), horizontalAlignment=swing.SwingConstants.LEFT) self.__setDisplay() northpanel=swing.JPanel(awt.FlowLayout(awt.FlowLayout.LEFT)) northpanel.setBorder(line) #northpanel.add(self.__display, awt.BorderLayout.NORTH) northpanel.add(self.__display) selectall = swing.JButton("select ALL", size=(100, 70), actionPerformed=self.__selectall) #northpanel.add(selectall, awt.BorderLayout.WEST) northpanel.add(selectall) selectnone = swing.JButton("select NONE", size=(100, 70), actionPerformed=self.__selectnone) #northpanel.add(selectnone, awt.BorderLayout.EAST) northpanel.add(selectnone) mem = swing.JButton("Memorize", size=(100, 70), actionPerformed= self.__memorize) northpanel.add(mem) recall = swing.JButton("Recall", size=(100, 70), actionPerformed=self.__recall) northpanel.add(recall) southpanel=swing.JPanel(awt.FlowLayout(awt.FlowLayout.RIGHT)) southpanel.setBorder(line) self.__label=swing.JLabel("validate selection with ok") southpanel.add(self.__label) ok = swing.JButton("ok", size=(100, 70), actionPerformed=self.__ok) southpanel.add(ok) close = swing.JButton("close", size=(100, 70), actionPerformed=self.__close) southpanel.add(close) westpanel=swing.JPanel(awt.FlowLayout(awt.FlowLayout.CENTER), preferredSize=(150, 200)) westpanel.setBorder(line) show = swing.JButton("show overlay", size=(100, 70), actionPerformed=self.__show) westpanel.add(show) hide = swing.JButton("hide overlay", size=(100, 70), actionPerformed=self.__hide) westpanel.add(hide) allframes = swing.JButton("show all", size=(100, 70), actionPerformed=self.__showall) westpanel.add(allframes) oneframe = swing.JButton("show one frame", size=(100, 70), actionPerformed=self.__showone) westpanel.add(oneframe) reset = swing.JButton("reset", size=(100, 70), actionPerformed=self.__reset) westpanel.add(reset) title = BorderFactory.createTitledBorder("Edit Cells") title.setTitleJustification(TitledBorder.CENTER) eastpanel = swing.JPanel(awt.FlowLayout(awt.FlowLayout.CENTER), preferredSize=(130, 200)) eastpanel.setBorder(title) split = swing.JButton("split", size=(100, 70), actionPerformed=self.__split) eastpanel.add(split) grid = awt.GridLayout() grid.setRows(rows) checkpanel=swing.JPanel(grid) checkpanel.setFont(awt.Font("Courrier", 1, 10)) self.__boxes=[swing.JCheckBox(actionPerformed=self.__boxaction) for i in range(len(cells))] for b in self.__boxes : b.setFont(awt.Font("Courrier", 1, 10)) #self.__mem=[True for i in range(len(cells))] for i in range(len(self.__boxes)) : self.__dictBox[cells[i]]=(cells[i], self.__boxes[i]) for i in range(len(self.__boxes)) : self.__boxes[i].setText(str(cells[i])) self.__boxes[i].setSelected(True) checkpanel.add(self.__boxes[i]) for i in range(rows*cols-len(self.__boxes)) : checkpanel.add(awt.Label("")) self.contentPane.add(northpanel, awt.BorderLayout.NORTH) self.contentPane.add(checkpanel, awt.BorderLayout.CENTER) self.contentPane.add(westpanel, awt.BorderLayout.WEST) self.contentPane.add(eastpanel, awt.BorderLayout.EAST) self.contentPane.add(southpanel, awt.BorderLayout.SOUTH) self.contentPane.setFont(awt.Font("Courrier", 1, 10)) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() self.__rm.runCommand("reset") listfilescells=[] listfilescells.extend(glob.glob(path+"*.zip")) #includecells = [filename for filename in listfilescells if filename.rsplit("/",1)[1][0:-4] in cells] includecells = [filename for filename in listfilescells if os.path.splitext(os.path.split(filename)[1])[0] in cells] for cell in includecells : #c = cell.rsplit("/",1)[1][0:-4] c=os.path.splitext(os.path.split(cell)[1])[0] self.__dictFiles[c] = (c, cell) #for i in range(len(cells)) : # f=listfilescells[i].rsplit("/",1)[1][0:-4] # #print "f=", f # for c in cells : # #print "c=", c, "f=", f # if f==c : # self.__dictFiles[c] = (c, listfilescells[i]) # #print "CS dictFiles", c, listfilescells[i] def __selectall(self, event): for b in self.__boxes : b.setSelected(True) def __selectnone(self, event): for b in self.__boxes : b.setSelected(False) def __ok(self, event): self.oked = True #self.dispose() def __close(self, event): self.oked = True time.sleep(0.01) self.dispose() def __memorize(self, event): self.__mem[:]=[] for i in range(len(self.__boxes)) : if self.__boxes[i].isSelected() : #print i, "mem", self.__boxes[i].text self.__mem.append(True) else : self.__mem.append(False) def __recall(self, event): for i in range(len(self.__boxes)) : if self.__mem[i] : self.__boxes[i].setSelected(True) else : self.__boxes[i].setSelected(False) def __show(self, event): IJ.run("Show Overlay", "") def __hide(self, event): IJ.run("Hide Overlay", "") def __showall(self, event) : self.__rm.runCommand("Associate", "false") self.__rm.runCommand("Show All") def __showone(self, event) : self.__rm.runCommand("Associate", "true") self.__rm.runCommand("Show All") def __reset(self, event) : self.__rm.runCommand("reset") def __boxaction(self, event): self.__setDisplay(str(event.getSource().text)+" is "+str(event.getSource().isSelected())) if event.getSource().isSelected() : #print self.__dictFiles[event.getSource().text][1] #self.__rm.runCommand("reset") self.__rm.runCommand("Open", self.__dictFiles[event.getSource().text][1]) def __setDisplay(self, val=""): self.__display.text = str(val) def __split(self, event) : sel = self.getSelected() if len(sel) != 1 : IJ.showMessage("only one cell should be selected !") return else : cellname = sel[0] rois = self.__rm.getRoisAsArray() self.__rm.runCommand("reset") n = int(IJ.getNumber("slice to split ?", 1)) for i in range(n) : self.__rm.addRoi(rois[i]) #print self.__path+cellname+"-a.zip" self.__rm.runCommand("Save", self.__path+cellname+"-a.zip") self.__rm.runCommand("reset") for i in range(n, len(rois)) : self.__rm.addRoi(rois[i]) self.__rm.runCommand("Save", self.__path+cellname+"-b.zip") self.__rm.runCommand("reset") root = self.__path.rsplit(os.path.sep, 2)[0]+os.path.sep if not path.exists(root+"Cells"+os.path.sep) :os.makedirs(root+"Cells"+os.path.sep, mode=0777) fichiertemp = open(root+"Cells"+os.path.sep+cellname+"-a.cell","w") fichiertemp.write("NAMECELL="+cellname+"-a\n") fichiertemp.write("PATHCELL="+root+"Cells"+os.path.sep+cellname+"-a.cell\n") fichiertemp.write("PATHROIS="+root+"ROIs"+os.path.sep+cellname+"-a.zip\n") fichiertemp.write("NSLICES="+str(len(rois))+"\n") fichiertemp.write("SLICEINIT="+str(1)+"\n") fichiertemp.write("SLICEEND="+str(n)+"\n") r = random.randrange(5,205,1) g = random.randrange(10,210,1) b = random.randrange(30,230,1) fichiertemp.write("COLOR="+str(r)+";"+str(g)+";"+str(b)+"\n") fichiertemp.close() fichiertemp = open(root+"Cells"+os.path.sep+cellname+"-b.cell","w") fichiertemp.write("NAMECELL="+cellname+"-b\n") fichiertemp.write("PATHCELL="+root+"Cells"+os.path.sep+cellname+"-b.cell\n") fichiertemp.write("PATHROIS="+root+"ROIs"+os.path.sep+cellname+"-b.zip\n") fichiertemp.write("NSLICES="+str(len(rois))+"\n") fichiertemp.write("SLICEINIT="+str(n+1)+"\n") fichiertemp.write("SLICEEND="+str(len(rois))+"\n") r = random.randrange(5,205,1) g = random.randrange(10,210,1) b = random.randrange(30,230,1) fichiertemp.write("COLOR="+str(r)+";"+str(g)+";"+str(b)+"\n") fichiertemp.close() def getSelected(self) : #selected=[self.__cells[i] for i in range(len(self.__cells)) if self.__boxes[i].isSelected()] selected=[b.getText() for b in self.__boxes if b.isSelected()] return selected def setSelected(self, selected) : for b in self.__boxes : b.setSelected(False) #for s in selected : print str(s) for c in self.__cells : #print str(c) if c in selected : self.__dictBox[c][1].setSelected(True) def resetok(self): self.oked = False def setLabel(self, text): self.__label.setText(text)
def main(): # Get active dataset #img = IJ.getImage() display = displayservice.getActiveDisplay() active_dataset = imagedisplayservice.getActiveDataset(display) if not active_dataset: IJ.showMessage('No image opened.') return # Get image path fname = active_dataset.getSource() dir_path = os.path.dirname(fname) if not fname: IJ.showMessage('Source image needs to match a file on the system.') return # Open ROIs rois = RoiManager.getInstance() if not rois: roi_path = os.path.join(dir_path, "RoiSet.zip") if not os.path.isfile(roi_path): try: roi_path = glob.glob(os.path.join(dir_path, "*.roi"))[0] except: roi_path = None if not roi_path: IJ.showMessage('No ROIs. Please use Analyze > Tools > ROI Manager...') return rois = RoiManager(True) rois.reset() rois.runCommand("Open", roi_path) IJ.log('Image filename is %s' % fname) dt = get_dt(active_dataset) rois_array = rois.getRoisAsArray() for i, roi in enumerate(rois_array): crop_id = i + 1 IJ.log("Croping %i / %i" % (crop_id, len(rois_array))) # Get filename and basename of the current cropped image crop_basename = "crop%i_%s" % (crop_id, active_dataset.getName()) crop_basename = os.path.splitext(crop_basename)[0] + ".ome.tif" crop_fname = os.path.join(os.path.dirname(fname), crop_basename) # Get bounds and crop bounds = roi.getBounds() dataset = crop(ij, datasetservice, active_dataset, bounds.x, bounds.y, bounds.width, bounds.height, crop_basename) # Show cropped image ij.ui().show(dataset.getName(), dataset) # Save cropped image (ugly hack) IJ.log("Saving crop to %s" % crop_fname) imp = IJ.getImage() bfExporter = LociExporter() macroOpts = "save=[" + crop_fname + "]" bfExporter.setup(None, imp) Macro.setOptions(macroOpts) bfExporter.run(None) imp.close() IJ.log('Done')
def channel_segmentation(infile, diameter, tolerance, repeat_max, Zrepeat=10): # ROI optimization by Esnake optimisation default_options = "stack_order=XYCZT color_mode=Grayscale view=Hyperstack" IJ.run("Bio-Formats Importer", default_options + " open=[" + infile + "]") imp = IJ.getImage() cal = imp.getCalibration() channels = [i for i in xrange(1, imp.getNChannels() + 1)] log = filename(infile) log = re.sub('.ids', '.csv', log) XZdrift, YZdrift = retrieve_Zdrift(log) XZpt = [i * imp.getWidth() / Zrepeat for i in xrange(1, Zrepeat - 1)] YZpt = [i * imp.getHeight() / Zrepeat for i in xrange(1, Zrepeat - 1)] # Prepare head output file for ch in channels: csv_name = 'ch' + str(ch) + log with open(os.path.join(folder6, csv_name), 'wb') as outfile: SegLog = csv.writer(outfile, delimiter=',') SegLog.writerow(['spotID', 'Xpos', 'Ypos', 'Zpos', 'Quality', 'area', 'intensity', 'min', 'max', 'std']) # Retrieve seeds from SpotDetector options = IS.MEDIAN | IS.AREA | IS.MIN_MAX | IS.CENTROID spots = retrieve_seeds(log) for ch in channels: for spot in spots: repeat = 0 # Spots positions are given according to calibration, need to # convert it to pixel coordinates spotID = int(spot[0]) Xcenter = int(float(spot[2]) / cal.pixelWidth) Ycenter = int(float(spot[3]) / cal.pixelHeight) Zcenter = float(spot[4]) / cal.pixelDepth Quality = float(spot[5]) # find closest grid location in Zdrift matrix Xpt = min(range(len(XZpt)), key=lambda i: abs(XZpt[i] - Xcenter)) Ypt = min(range(len(YZpt)), key=lambda i: abs(YZpt[i] - Ycenter)) # Calculate Z position according to SpotZ, calibration and # channel-specific Zdrift # Zshift = median([float(XZdrift[Xpt][ch - 1]), float(YZdrift[Ypt][ch - 1])]) / cal.pixelDepth correctZ = int(Zcenter - Zshift) imp.setPosition(ch, correctZ, 1) imp.getProcessor().setMinAndMax(0, 3000) while True: manager = RoiManager.getInstance() if manager is None: manager = RoiManager() roi = OvalRoi(Xcenter - diameter * (1.0 + repeat / 10.0) / 2.0, Ycenter - diameter * ( 1.0 + repeat / 10.0) / 2.0, diameter * (1.0 + repeat / 10.0), diameter * (1.0 + repeat / 10.0)) imp.setRoi(roi) IJ.run(imp, "E-Snake", "target_brightness=Bright control_points=3 gaussian_blur=0 energy_type=Mixture alpha=2.0E-5 max_iterations=20 immortal=false") roi_snake = manager.getRoisAsArray()[0] imp.setRoi(roi_snake) stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) manager.reset() if stats.area > 20.0 and stats.area < 150.0 and boundaries(Xcenter, Ycenter, stats.xCentroid / cal.pixelWidth, stats.yCentroid / cal.pixelHeight, tolerance): Sarea = stats.area Sintensity = stats.median Smin = stats.min Smax = stats.max Sstd = stats.stdDev break elif repeat > repeat_max: roi = OvalRoi(Xcenter - diameter / 2.0, Ycenter - diameter / 2.0, diameter, diameter) imp.setRoi(roi) manager.add(imp, roi, i) stats = IS.getStatistics( imp.getProcessor(), options, imp.getCalibration()) Sarea = stats.area Sintensity = stats.median Smin = stats.min Smax = stats.max Sstd = stats.stdDev break else: repeat += 1 # Save results csv_name = 'ch' + str(ch) + log with open(os.path.join(folder6, csv_name), 'ab') as outfile: SegLog = csv.writer(outfile, delimiter=',') SegLog.writerow([spotID, Xcenter, Ycenter, correctZ, Quality, Sarea, Sintensity, Smin, Smax, Sstd]) # End spot optimization # End spots # End channels IJ.selectWindow(filename(infile)) IJ.run("Close")
def batch_open_images(pathRoi, pathMask, file_typeImage=None, name_filterImage=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the images. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Reject files that contain the given string (default: wild characters). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathMask, File): pathMask = pathMask.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathMask) path = os.path.expandvars(pathMask) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathMask): full_path = os.path.join(pathMask, file_name) if os.path.isfile(full_path): if check_type(file_name): if check_filter(file_name): path_to_Image.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathMask): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([ full_path, os.path.basename(os.path.splitext(full_path)[0]) ]) # Create the list that will be returned by this function. Masks = [] rois = [] ImageRois = [] for img_path, file_name in path_to_Image: # IJ.openImage() returns an ImagePlus object or None. if check_filter(file_name): continue else: MaskName = str(pathMask) + '/' + file_name + '.tif' Mask = IJ.openImage(MaskName) Mask.show() rm = RoiManager.getInstance() if (rm == None): rm = RoiManager() rm.runCommand("Delete") IJ.selectWindow(file_name + '.tif') IJ.run("Find Edges") IJ.setAutoThreshold(Mask, "Default dark") IJ.run("Threshold") IJ.setThreshold(0, 0) IJ.run("Convert to Mask") IJ.run("Invert") IJ.run("Create Selection") rm.runCommand("Add") # An object equals True and None equals False. rois = rm.getRoisAsArray() rm.runCommand("Save", str(pathRoi) + "/" + file_name + '.roi') Mask.changes = False Mask.close() ImageRois.append(rois) return ImageRois
def process(subDir, subsubDir, outputDirectory, filename): subFolder = subDir + "/" + subsubDir # Opens the d0 image and sets default properties imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() imp.updateAndDraw() dup = imp.duplicate() IJ.run( dup, "Convolve...", "text1=[-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 24 -1 -1\n-1 -1 -1 -1 -1\n-1 -1 -1 -1 -1\n] normalize" ) stats = dup.getStatistics(Measurements.MEAN | Measurements.MIN_MAX | Measurements.STD_DEV) dup.close() blurry = (stats.mean < 18 and stats.stdDev < 22) or stats.max < 250 IJ.setThreshold(imp, lowerBounds[0], 255) IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if displayImages: imp.show() WaitForUserDialog("Title", "Look at image").show() # 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, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) pa.analyze(imp) if not displayImages: imp.changes = False imp.close() areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the d0 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [] areaMeansArray = [] means = [] totalAreas = [] for chan in channels: v, x = chan # Opens each image and thresholds imp = IJ.openImage(inputDirectory + subFolder + '/' + filename.replace("d0.TIF", "d" + str(x) + ".TIF")) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() imp.updateAndDraw() stats = imp.getStatistics(Measurements.MEAN) means.append(stats.mean) areaMeans = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN) areaMeans.append(stats.mean) IJ.setThreshold(imp, lowerBounds[x], 255) IJ.run(imp, "Convert to Mask", "") if displayImages: imp.show() WaitForUserDialog("Title", "Look at image").show() stats = imp.getStatistics(Measurements.AREA_FRACTION) totalAreas.append(stats.areaFraction) # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray.append(areaFractions) areaMeansArray.append(sum(areaMeans) / len(areaMeans)) if not displayImages: imp.changes = False imp.close() roim.close() # Figures out what well the image is a part of ind = filename.index("p00_0_") row = filename[ind + 6:ind + 7] column = str(int(filename[ind + 7:ind + 9])) # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} # Finds the name of the well from the nameArray 2d array if row in nameArray: if column in nameArray[row]: summary['Name'] = nameArray[row][column] summary['Image'] = filename summary['Directory'] = subDir summary['SubDirectory'] = subsubDir summary['Row'] = row summary['Column'] = column # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 summary['image-quality'] = blurry # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'SubDirectory', 'Image', 'Row', 'Column', 'size-average', 'image-quality', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) for chan in channels: v, x = chan summary[v + "-positive"] = 0 summary[v + "-intensity"] = means[x] summary[v + "-area"] = totalAreas[x] summary[v + "-intensity-in-nuclei"] = areaMeansArray[x] summary[v + "-area-fraction-in-nuclei"] = sum( areaFractionsArray[x]) / len(areaFractionsArray[x]) fieldnames.append(v + "-positive") fieldnames.append(v + "-intensity") fieldnames.append(v + "-area") fieldnames.append(v + "-intensity-in-nuclei") fieldnames.append(v + "-area-fraction-in-nuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 if not (areas is None): for z, area in enumerate(areas): if not (area is None or summary is None): if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for y, chan in enumerate(channels): v, x = chan if areaFractionsArray[y][z] > areaFractionThreshold: summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold: if areaFractionsArray[2][z] > areaFractionThreshold: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold: if areaFractionsArray[3][z] > areaFractionThreshold: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold: if areaFractionsArray[3][z] > areaFractionThreshold: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][ z] > areaFractionThreshold: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", '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)
) writer.writeheader() writer.writerows(current) print("wrote results to {}".format(out_path)) # imp = IJ.openImage(th_files[0]) # imp.show() # get open image imp = IJ.getImage() image_name = imp.getShortTitle() # get roi manager roi_manager = RoiManager().getInstance() all_rois = roi_manager.getRoisAsArray() csv_name = make_path(out_dir, image_name, ".csv") roi_name = make_path(out_dir, image_name, "_rois.zip") old_name = make_path(target_dir, image_name, ".tif") new_name = make_path(out_dir, image_name, ".tif") current = [] for roi in all_rois: res = get_stats(2, roi, imp) current.append(res) # write csv write_csv(current, csv_name) # save all rois save_rois(roi_manager, roi_name)
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): # set calibration detectionParameters.setCalibration(inputImp); # calculate area of roi stats=inputImp.getStatistics() inputRoiArea=stats.area # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) #cropped=ops.image().crop(interval, None, inputDataset.getImgPlus() ) cropped=ops.image().crop(inputDataset.getImgPlus() , interval) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() # instantiate the duplicator and the substackmaker classes duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", ""); brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3") brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate=duplicator.run(croppedPlus) channels=ChannelSplitter().split(duplicate) redPlus=channels[0] red=ImgPlus(ImageJFunctions.wrapByte(redPlus)) # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() croppedPlus.changes=False croppedPlus.close() # get the A channel APlus=substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') #APlus.show() APlus.getProcessor().resetMinAndMax() #APlus.updateAndDraw() AThresholded=threshold(APlus, -10, 50) # get the B channel BPlus=substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') #BPlus.show() BPlus.getProcessor().resetMinAndMax() #BPlus.updateAndDraw() BThresholded=threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator(); redMask = ic.run("AND create", AThresholded, BThresholded); IJ.run(redMask, "Divide...", "value=255"); labPlus.close() fast=True # threshold the spots from the red channel if (fast==False): thresholdedred=SpotDetectionGray(red, data, display, ops, "triangle") impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") else: impthresholdedred=SpotDetection2(redPlus) # threshold the spots from the brightness channel if (fast==False): thresholded=SpotDetectionGray(brightness, data, display, ops, "triangle") impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") else: impthresholded=SpotDetection2(brightnessPlus) # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); roim=RoiManager(True) # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.porphyrinRedPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.porphyrinRedPercentage): return False else: return True roiClone=inputRoi.clone() roiClone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, roiClone) impthresholded.show() countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \ detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity) uvPoreList=[] for roi in roim.getRoisAsArray(): uvPoreList.append(roi.clone()) #allList=uvPoreList+closedPoresList+openPoresList # count particles that are porphyrins (red) porphyrinList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, isRed) # count particles that are visible on uv but not porphyrins sebumList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, notRed) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in uvPoreList] # draw the ROIs on to the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3"); inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList] [CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList] inputImp.updateAndDraw() # calculate stats for the UV visible particles detectionParameters.setCalibration(APlus) statsDictUV=CountParticles.calculateParticleStatsUV(APlus, BPlus, redMask, roim.getRoisAsArray()) totalUVPoreArea=0 for area in statsDictUV['Areas']: totalUVPoreArea=totalUVPoreArea+area averageUVPoreArea=totalUVPoreArea/len(statsDictUV['Areas']) poreDiameter=0 for diameter in statsDictUV['Diameters']: poreDiameter=poreDiameter+diameter poreDiameter=poreDiameter/len(statsDictUV['Diameters']) redTotal=0 for red in statsDictUV['redPercentage']: redTotal=redTotal+red redAverage=redTotal/len(statsDictUV['redPercentage']) statslist=[len(porphyrinList), 100*redAverage]; statsheader=[Messages.Porphyrins, Messages.PercentageRedPixels] print("Roi Area: "+str(inputRoiArea)) print("Total Pore Area: "+str(totalUVPoreArea)) print("Average Pore Area: "+str(averageUVPoreArea)) print str(len(uvPoreList))+" "+str(len(porphyrinList))+" "+str(len(sebumList))+" "+str(100*totalUVPoreArea/inputRoiArea)+" "+str(100*redAverage) print "cp min circularity"+str(detectionParameters.closedPoresMinCircularity)+":"+str(detectionParameters.closedPoresMinSize) # close the thresholded image impthresholded.changes=False impthresholded.close() return uvPoreList, statslist, statsheader
def batch_open_images(pathImage, pathRoi, pathMask, file_typeImage=None, name_filterImage=None, recursive=False): '''Open all files in the given folder. :param path: The path from were to open the images. String and java.io.File are allowed. :param file_type: Only accept files with the given extension (default: None). :param name_filter: Reject files that contain the given string (default: wild characters). :param recursive: Process directories recursively (default: False). ''' # Converting a File object to a string. if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True def dog_detection(overlay,img, imp, cal): # Create a variable of the correct type (UnsignedByteType) for the value-extended view zero = img.randomAccess().get().createVariable() # Run the difference of Gaussian cell = 8.0 # microns in diameter min_peak = 2.0 # min intensity for a peak to be considered dog = DogDetection(Views.extendValue(img, zero), img, [cal.pixelWidth, cal.pixelHeight,cal.pixelDepth], cell / 2, cell, DogDetection.ExtremaType.MINIMA, min_peak, False, DoubleType()) peaks = dog.getPeaks() roi = OvalRoi(0, 0, cell/cal.pixelWidth, cell/cal.pixelHeight) print ('Number of cells = ', len(peaks)) p = zeros(img.numDimensions(), 'i') boundRect = imp.getRoi() for peak in peaks: # Read peak coordinates into an array of integers XYZ location of spots peak.localize(p) print(p) if(boundRect is not None and boundRect.contains(p[0], p[1])): oval = OvalRoi(p[0], p[1],cell/cal.pixelWidth, cell/cal.pixelHeight) oval.setColor(Color.RED) overlay.add(oval) def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). if not recursive: for file_name in os.listdir(pathImage): full_path = os.path.join(pathImage, file_name) if os.path.isfile(full_path): if check_type(file_name): if check_filter(file_name): path_to_Image.append(full_path) # For a recursive search os.walk() is used. else: # os.walk() is iterable. # Each iteration of the for loop processes a different directory. # the first return value represents the current directory. # The second return value is a list of included directories. # The third return value is a list of included files. for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([full_path, os.path.basename(os.path.splitext(full_path)[0])]) # Create the list that will be returned by this function. Images = [] Rois = [] for img_path, file_name in path_to_Image: # IJ.openImage() returns an ImagePlus object or None. imp = IJ.openImage(img_path) imp.show() print(img_path) if check_filter(file_name): continue; else: print(file_name , pathRoi) RoiName = str(pathRoi) + '/'+ file_name + '_rois' + '.zip' if os.path.exists(RoiName): Roi = IJ.open(RoiName) imp = IJ.getImage() cal= imp.getCalibration()# in microns img = IJF.wrap(imp) print('Image Dimensions', img.dimensions, 'Calibration', cal) print(Roi) # An object equals True and None equals False. rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() try: rm.runCommand('Delete') except: pass rm.runCommand("Open", RoiName) rois = rm.getRoisAsArray() overlay = Overlay() for (i in range(0,len(rois))): overlay.add(rois[i])
def load_rois(roifile): rm = RoiManager(False) rm.reset() rm.runCommand("Open", roifile) rois = rm.getRoisAsArray() return rois
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): title = inputImp.getTitle() title=title.replace('UV', 'SD') print title #trueColorImp= WindowManager.getImage(title) #print type( trueColorImp) # calculate are of roi stats=inputImp.getStatistics() inputRoiArea=stats.area print inputRoi # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 print x1 print y1 print x2 print y2 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) #duplicate.show() # convert duplicate of roi to HSB and get brightness IJ.run(duplicate, "HSB Stack", ""); brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3") brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus)) brightnessPlus.setTitle("Brightness") #brightnessPlus.show() # make another duplicate, split channels and get red duplicate=duplicator.run(croppedPlus) channels=ChannelSplitter().split(duplicate) redPlus=channels[0] red=ImgPlus(ImageJFunctions.wrapByte(redPlus)) redPlus.show() # convert to lab IJ.run(croppedPlus, "Color Transformer", "colour=Lab") IJ.selectWindow('Lab') labPlus=IJ.getImage() # get the A channel APlus=substackMaker.makeSubstack(labPlus, "2-2") APlus.setTitle('A') APlus.show() APlus.getProcessor().resetMinAndMax() APlus.updateAndDraw() AThresholded=threshold(APlus, -10, 50) # get the B channel BPlus=substackMaker.makeSubstack(labPlus, "3-3") BPlus.setTitle('B') BPlus.show() BPlus.getProcessor().resetMinAndMax() BPlus.updateAndDraw() BThresholded=threshold(BPlus, -10, 50) # AND the Athreshold and Bthreshold to get a map of the red pixels ic = ImageCalculator(); redMask = ic.run("AND create", AThresholded, BThresholded); IJ.run(redMask, "Divide...", "value=255"); #redMask.show() labPlus.close() # threshold the spots from the red channel thresholdedred=SpotDetectionGray(red, data, display, ops, False) display.createDisplay("thresholdedred", data.create(thresholdedred)) impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped") # threshold the spots from the brightness channel thresholded=SpotDetectionGray(brightness, data, display, ops, False) display.createDisplay("thresholded", data.create(thresholded)) impthresholded=ImageJFunctions.wrap(thresholded, "wrapped") # or the thresholding results from red and brightness channel impthresholded = ic.run("OR create", impthresholded, impthresholdedred); # convert to mask Prefs.blackBackground = True IJ.run(impthresholded, "Convert to Mask", "") # clear the region outside the roi clone=inputRoi.clone() clone.setLocation(0,0) Utility.clearOutsideRoi(impthresholded, clone) # create a hidden roi manager roim = RoiManager(True) # count the particlesimp.getProcessor().setColor(Color.green) countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity) # define a function to determine the percentage of pixels that are foreground in a binary image # inputs: # imp: binary image, 0=background, 1=foreground # roi: an roi def isRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return True else: return False def notRed(imp, roi): stats = imp.getStatistics() if (stats.mean>detectionParameters.redPercentage): return False else: return True allList=[] for roi in roim.getRoisAsArray(): allList.append(roi.clone()) # count particles that are red redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed) # count particles that are red blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed) print "Total particles: "+str(len(allList)) print "Filtered particles: "+str(len(redList)) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList] # create an overlay and add the rois overlay1=Overlay() inputRoi.setStrokeColor(Color.green) overlay1.add(inputRoi) [CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList] [CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList] def drawAllRoisOnImage(imp, mainRoi, redList, blueList): imp.getProcessor().setColor(Color.green) IJ.run(imp, "Line Width...", "line=3"); imp.getProcessor().draw(inputRoi) imp.updateAndDraw() IJ.run(imp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList] [CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList] imp.updateAndDraw() drawAllRoisOnImage(inputImp, inputRoi, redList, blueList) #drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList) # draw overlay #inputImp.setOverlay(overlay1) #inputImp.updateAndDraw() statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray()) print inputRoiArea areas=statsdict['Areas'] poreArea=0 for area in areas: poreArea=poreArea+area ATotal=0 ALevels=statsdict['ALevel'] for A in ALevels: ATotal=ATotal+A AAverage=ATotal/len(ALevels) BTotal=0 BLevels=statsdict['BLevel'] for B in BLevels: BTotal=BTotal+B BAverage=BTotal/len(BLevels) redTotal=0 redPercentages=statsdict['redPercentage'] for red in redPercentages: redTotal=redTotal+red redAverage=redTotal/len(redPercentages) pixwidth=inputImp.getCalibration().pixelWidth inputRoiArea=inputRoiArea/(pixwidth*pixwidth) print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
# 4. The script will pop up a file browser. Specify the output file for the ROIs. Press "Open". The coordinates of all # ROI polygons will be save to a text file in JSON format. # # Frank Vernaillen # VIB - Vlaams Instituut voor Biotechnologie # October 2018 from ij import IJ from ij.plugin.frame import RoiManager import sys rm = RoiManager.getInstance() if rm == None: rm = RoiManager() rois = rm.getRoisAsArray() if rois == None or len(rois) == 0: sys.exit('The ROI manager has no ROIs') filename = IJ.getFilePath( 'Specify the output file for the ROIs in JSON format (e.g. myrois.json)') if filename == None: sys.exit('ROI saving canceled by the user.') # Save the ROIs as JSON arrays IJ.log("Saving {} ROIs to {}".format(len(rois), filename)) with open(filename, 'w') as f: f.write('[\n') for i, roi in enumerate(rois): polygon = roi.getPolygon() f.write('[\n')
def analyze_homogeneity(image_title): IJ.selectWindow(image_title) raw_imp = IJ.getImage() IJ.run(raw_imp, "Duplicate...", "title=Homogeneity duplicate") IJ.selectWindow('Homogeneity') hg_imp = IJ.getImage() # Get a 2D image if hg_imp.getNSlices() > 1: IJ.run(hg_imp, "Z Project...", "projection=[Average Intensity]") hg_imp.close() IJ.selectWindow('MAX_Homogeneity') hg_imp = IJ.getImage() hg_imp.setTitle('Homogeneity') # Blur and BG correct the image IJ.run(hg_imp, 'Gaussian Blur...', 'sigma=' + str(HOMOGENEITY_RADIUS) + ' stack') # Detect the spots IJ.setAutoThreshold(hg_imp, HOMOGENEITY_THRESHOLD + " dark") rm = RoiManager(True) table = ResultsTable() pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, # measurements table, # Output table 0, # MinSize 500, # MaxSize 0.0, # minCirc 1.0) # maxCirc pa.setHideOutputImage(True) pa.analyze(hg_imp) areas = table.getColumn(table.getHeadings().index('Area')) median_areas = compute_median(areas) st_dev_areas = compute_std_dev(areas, median_areas) thresholds_areas = (median_areas - (2 * st_dev_areas), median_areas + (2 * st_dev_areas)) roi_measurements = {'integrated_density': [], 'max': [], 'area': []} IJ.setForegroundColor(0, 0, 0) for roi in rm.getRoisAsArray(): hg_imp.setRoi(roi) if REMOVE_CROSS and hg_imp.getStatistics().AREA > thresholds_areas[1]: rm.runCommand('Fill') else: roi_measurements['integrated_density'].append(hg_imp.getStatistics().INTEGRATED_DENSITY) roi_measurements['max'].append(hg_imp.getStatistics().MIN_MAX) roi_measurements['integrated_densities'].append(hg_imp.getStatistics().AREA) rm.runCommand('Delete') measuremnts = {'mean_integrated_density': compute_mean(roi_measurements['integrated_density']), 'median_integrated_density': compute_median(roi_measurements['integrated_density']), 'std_dev_integrated_density': compute_std_dev(roi_measurements['integrated_density']), 'mean_max': compute_mean(roi_measurements['max']), 'median_max': compute_median(roi_measurements['max']), 'std_dev_max': compute_std_dev(roi_measurements['max']), 'mean_area': compute_mean(roi_measurements['max']), 'median_area': compute_median(roi_measurements['max']), 'std_dev_area': compute_std_dev(roi_measurements['max']), } # generate homogeinity image # calculate interpoint distance in pixels nr_point_columns = int(sqrt(len(measuremnts['mean_max']))) # TODO: This is a rough estimation that does not take into account margins or rectangular FOVs inter_point_dist = hg_imp.getWidth() / nr_point_columns IJ.run(hg_imp, "Maximum...", "radius="+(inter_point_dist*1.22)) # Normalize to 100 IJ.run(hg_imp, "Divide...", "value=" + max(roi_measurements['max'] / 100)) IJ.run(hg_imp, "Gaussian Blur...", "sigma=" + (inter_point_dist/2)) hg_imp.getProcessor.setMinAndMax(0, 255) # Create a LUT based on a predefined threshold red = zeros(256, 'b') green = zeros(256, 'b') blue = zeros(256, 'b') acceptance_threshold = HOMOGENEITY_ACCEPTANCE_THRESHOLD * 256 / 100 for i in range(256): red[i] = (i - acceptance_threshold) green[i] = (i) homogeneity_LUT = LUT(red, green, blue) hg_imp.setLut(homogeneity_LUT) return hg_imp, measuremnts
def process(subFolder, outputDirectory, filename): imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif")) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, 2, 255) IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Dark") IJ.run(imp, "Remove Outliers...", "radius=5" + " threshold=50" + " which=Bright") imp.getProcessor().invert() rm = RoiManager(True) imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE) boundroi = ThresholdToSelection.run(imp) rm.addRoi(boundroi) if not displayImages: imp.changes = False imp.close() images = [None] * 5 intensities = [None] * 5 blobsarea = [None] * 5 blobsnuclei = [None] * 5 bigAreas = [None] * 5 for chan in channels: v, x = chan images[x] = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", "_ch0" + str(x) + ".tif")) imp = images[x] for roi in rm.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA) intensities[x] = stats.mean bigAreas[x] = stats.area rm.close() # Opens the ch00 image and sets default properties imp = IJ.openImage(inputDirectory + subFolder + '/' + filename) IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html ic = ImageConverter(imp) ic.convertToGray8() IJ.run(imp, "Remove Outliers...", "radius=2" + " threshold=50" + " which=Dark") IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur)) IJ.setThreshold(imp, lowerBounds[0], 255) if displayImages: imp.show() IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Watershed", "") if not displayImages: imp.changes = False imp.close() # 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, 15, 9999999999999999, 0.2, 1.0) pa.setHideOutputImage(True) #imp = impM # imp.getProcessor().invert() pa.analyze(imp) areas = table.getColumn(0) # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel # It will save all the area fractions into a 2d array called areaFractionsArray areaFractionsArray = [None] * 5 for chan in channels: v, x = chan # Opens each image and thresholds imp = images[x] IJ.run( imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001" ) ic = ImageConverter(imp) ic.convertToGray8() IJ.setThreshold(imp, lowerBounds[x], 255) if displayImages: imp.show() WaitForUserDialog("Title", "Adjust Threshold for Marker " + v).show() IJ.run(imp, "Convert to Mask", "") # Measures the area fraction of the new image for each ROI from the ROI manager. areaFractions = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA_FRACTION) areaFractions.append(stats.areaFraction) # Saves the results in areaFractionArray areaFractionsArray[x] = areaFractions roim.close() for chan in channels: v, x = chan imp = images[x] imp.deleteRoi() roim = RoiManager(True) ParticleAnalyzer.setRoiManager(roim) pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA, table, 15, 9999999999999999, 0.2, 1.0) pa.analyze(imp) blobs = [] for roi in roim.getRoisAsArray(): imp.setRoi(roi) stats = imp.getStatistics(Measurements.AREA) blobs.append(stats.area) blobsarea[x] = sum(blobs) blobsnuclei[x] = len(blobs) if not displayImages: imp.changes = False imp.close() roim.reset() roim.close() # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column summary = {} summary['Image'] = filename summary['Directory'] = subFolder # Adds usual columns summary['size-average'] = 0 summary['#nuclei'] = 0 summary['all-negative'] = 0 summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0 summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0 # Creates the fieldnames variable needed to create the csv file at the end. fieldnames = [ 'Name', 'Directory', 'Image', 'size-average', 'too-big-(>' + str(tooBigThreshold) + ')', 'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei', 'all-negative' ] # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei) summary["organoid-area"] = bigAreas[x] fieldnames.append("organoid-area") for chan in channels: v, x = chan summary[v + "-positive"] = 0 fieldnames.append(v + "-positive") summary[v + "-intensity"] = intensities[x] fieldnames.append(v + "-intensity") summary[v + "-blobsarea"] = blobsarea[x] fieldnames.append(v + "-blobsarea") summary[v + "-blobsnuclei"] = blobsnuclei[x] fieldnames.append(v + "-blobsnuclei") # Adds the column for colocalization between first and second marker if len(channels) > 2: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive') # Adds the columns for colocalization between all three markers if len(channels) > 3: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] = 0 fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive') fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive') # Loops through each particle and adds it to each field that it is True for. areaCounter = 0 for z, area in enumerate(areas): log.write(str(area)) log.write("\n") if area > tooBigThreshold: summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1 elif area < tooSmallThreshold: summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1 else: summary['#nuclei'] += 1 areaCounter += area temp = 0 for chan in channels: v, x = chan if areaFractionsArray[x][z] > areaFractionThreshold[ 0]: #theres an error here im not sure why. i remember fixing it before summary[chan[0] + '-positive'] += 1 if x != 0: temp += 1 if temp == 0: summary['all-negative'] += 1 if len(channels) > 2: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[2][z] > areaFractionThreshold[2]: summary[channels[1][0] + '-' + channels[2][0] + '-positive'] += 1 if len(channels) > 3: if areaFractionsArray[1][z] > areaFractionThreshold[1]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[1][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[2][z] > areaFractionThreshold[2]: if areaFractionsArray[3][z] > areaFractionThreshold[3]: summary[channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 if areaFractionsArray[1][z] > areaFractionThreshold[1]: summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] + '-positive'] += 1 # Calculate the average of the particles sizes if float(summary['#nuclei']) > 0: summary['size-average'] = round(areaCounter / summary['#nuclei'], 2) # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image) with open(outputDirectory + "/" + outputName + ".csv", '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 poreDetectionTrueColor(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): detectionParameters.setCalibration(inputImp) # calculate area of roi stats = inputImp.getStatistics() inputRoiArea = stats.area # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1 = long(inputRec.getX()) y1 = long(inputRec.getY()) x2 = x1 + long(inputRec.getWidth()) - 1 y2 = y1 + long(inputRec.getHeight()) - 1 # crop the roi interval = FinalInterval(array([x1, y1, 0], 'l'), array([x2, y2, 2], 'l')) cropped = ops.crop(interval, None, inputDataset.getImgPlus()) datacropped = data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus = IJ.getImage() duplicator = Duplicator() substackMaker = SubstackMaker() # duplicate the roi duplicate = duplicator.run(croppedPlus) # separate into RGB and get the blue channel IJ.run(duplicate, "RGB Stack", "") bluePlus = substackMaker.makeSubstack(duplicate, "3-3") blue = ImgPlus(ImageJFunctions.wrapByte(bluePlus)) bluePlus.setTitle("Blue") # duplicate and look for bright spots thresholdedLight = SpotDetection2(bluePlus) # duplicate and look for dark spots thresholdedDark = SpotDetection3(bluePlus, True) # convert to mask Prefs.blackBackground = True #IJ.run(thresholdedDark, "Convert to Mask", "") # clear the region outside the roi clone = inputRoi.clone() clone.setLocation(0, 0) Utility.clearOutsideRoi(thresholdedLight, clone) Utility.clearOutsideRoi(thresholdedDark, clone) roimClosedPores = RoiManager(True) detectionParameters.setCalibration(thresholdedDark) countParticles(thresholdedDark, roimClosedPores, detectionParameters.closedPoresMinSize, detectionParameters.closedPoresMaxSize, \ detectionParameters.closedPoresMinCircularity, detectionParameters.closedPoresMaxCircularity) # count number of open pores roimOpenPores = RoiManager(True) detectionParameters.setCalibration(thresholdedDark) countParticles(thresholdedDark, roimOpenPores, detectionParameters.openPoresMinSize, detectionParameters.openPoresMaxSize, \ detectionParameters.openPoresMinCircularity, detectionParameters.openPoresMaxCircularity) # count number of sebum roimSebum = RoiManager(True) detectionParameters.setCalibration(thresholdedLight) countParticles(thresholdedLight, roimSebum, detectionParameters.sebumMinSize, detectionParameters.sebumMaxSize, \ detectionParameters.sebumMinCircularity, detectionParameters.sebumMaxCircularity) # create lists for open and closed pores closedPoresList = [] for roi in roimClosedPores.getRoisAsArray(): closedPoresList.append(roi.clone()) openPoresList = [] for roi in roimOpenPores.getRoisAsArray(): openPoresList.append(roi.clone()) # create lists for sebum sebumsList = [] for roi in roimSebum.getRoisAsArray(): sebumsList.append(roi.clone()) # a list of all pores allList = closedPoresList + openPoresList + sebumsList # calculate the stats for all pores detectionParameters.setCalibration(bluePlus) statsDict = CountParticles.calculateParticleStats(bluePlus, allList) poresTotalArea = 0 for area in statsDict['Areas']: poresTotalArea = poresTotalArea + area print area poresAverageArea = poresTotalArea / len(statsDict['Areas']) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [ roi.setLocation(roi.getXBase() + x1, roi.getYBase() + y1) for roi in allList ] # draw the rois on the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3") inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1") [ CountParticles.drawParticleOnImage(inputImp, roi, Color.red) for roi in closedPoresList ] [ CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in openPoresList ] [ CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumsList ] inputImp.updateAndDraw() # close images that represent intermediate steps croppedPlus.changes = False croppedPlus.close() bluePlus.changes = False bluePlus.close() print "Total ROI Area: " + str(inputRoiArea) print "Num closed pores: " + str(len(closedPoresList)) print "Num open pores: " + str(len(openPoresList)) print "Num sebums: " + str(len(sebumsList)) print "Total particles: " + str( len(allList)) + " total area: " + str(poresTotalArea) statslist = [ inputRoiArea, len(allList), len(closedPoresList), len(openPoresList), len(sebumsList), poresAverageArea, 100 * poresTotalArea / inputRoiArea ] header = [ Messages.TotalAreaMask, Messages.TotalDetectedPores, Messages.ClosedPores, Messages.OpenPores, Messages.Sebum, Messages.PoresAverageArea, Messages.PoresFractionalArea ] return header, statslist
otsu=ops.run("threshold", ops.create( dimensions2D, BitType()), imgBgs, Otsu()) display.createDisplay("thresholded", data.create(ImgPlus(otsu))) ''' #Utility.clearOutsideRoi(imp, clone) IJ.run(imp, "Auto Local Threshold", "method=MidGrey radius=15 parameter_1=0 parameter_2=0 white") IJ.run(imp, "Fill Holes", "") IJ.run(imp, "Close-", "") IJ.run(imp, "Watershed", "") iplus.updateAndDraw() # create a hidden roi manager roim = RoiManager(True) # count the particles countParticles(iplus, roim, 10, 200, 0.5, 1.0) [truecolor1.getProcessor().draw(roi) for roi in roim.getRoisAsArray()] truecolor1.updateAndDraw() #Prefs.blackBackground = False; #IJ.run("Make Binary", ""); #IJ.run("LoG 3D"); #IJ.run("Duplicate...", "title="+"test") #IJ.run("RGB Stack"); #IJ.run("Convert Stack to Images");
if pa.analyze(blueImp): print "All ok" else: print "There was a problem in analyzing", blueImp #Export roi center and radius to TSV default_name = imp.getShortTitle() + "_cells" sd = SaveDialog('Save ellypses to file', default_name, '.tsv') dirToSave = sd.getDirectory() fileh = open(dirToSave + sd.getFileName(), "w") #fileh.write("name\tx1\tx2\ty1\ty2\n") roim = RoiManager.getInstance() if roim is None: sys.exit(1) rois = roim.getRoisAsArray() print rois for roi in rois: bounds = roi.getBounds() x1 = (float(bounds.x) + float(bounds.x + bounds.width)) / 2. y1 = (float(bounds.y) + float(bounds.y + bounds.height)) / 2. fileh.write("\t".join([ roi.getName(), str(x1), str(y1), str(bounds.width), str(bounds.height) ]) + "\n") fileh.close()
# Binarize imp = IJ.getImage() imp1 = imp.duplicate() IJ.run(imp1, "Subtract Background...", "rolling=15 stack") IJ.run(imp1, "Median...", "radius=2 stack") IJ.run(imp1, "Gaussian Blur...", "sigma=2 stack") Prefs.blackBackground = True; IJ.run(imp1, "Convert to Mask", "method=MaxEntropy background=Dark calculate black") IJ.run(imp1, "Analyze Particles...", "size=400-Infinity pixel exclude add stack") imp1.show() # Analyze by using ROI manger rm = RoiManager() rm = RoiManager.getInstance() roi_array = rm.getRoisAsArray() # xyで構成される入れ子構造を組みかえる def xypoint_flatten(roi_array = RoiManager.getInstance().getRoisAsArray()): if roi_array is not None: xpoint = [[] for _ in range(len(roi_array))] ypoint = [[] for _ in range(len(roi_array))] for i, roi in enumerate(roi_array): xy_coord = list(roi.getContainedPoints()) for j, coord in enumerate(xy_coord): xpoint[i].append(coord.x) ypoint[i].append(coord.y) return xpoint, ypoint xpoint,ypoint = xypoint_flatten()
def batch_open_images(pathImage, file_typeImage, name_filterImage=None): if isinstance(pathImage, File): pathImage = pathImage.getAbsolutePath() def check_filter(string): '''This function is used to check for a given filter. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the filtering on. ''' if name_filterImage: # The first branch is used if name_filter is a list or a tuple. if isinstance(name_filterImage, (list, tuple)): for name_filter_ in name_filterImage: if name_filter_ in string: # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if name_filter is a string. elif isinstance(name_filterImage, string): if name_filterImage in string: return True else: return False return False else: # Accept all files if name_filter is None. return True def check_type(string): '''This function is used to check the file type. It is possible to use a single string or a list/tuple of strings as filter. This function can access the variables of the surrounding function. :param string: The filename to perform the check on. ''' if file_typeImage: # The first branch is used if file_type is a list or a tuple. if isinstance(file_typeImage, (list, tuple)): for file_type_ in file_typeImage: if string.endswith(file_type_): # Exit the function with True. return True else: # Next iteration of the for loop. continue # The second branch is used if file_type is a string. elif isinstance(file_typeImage, string): if string.endswith(file_typeImage): return True else: return False return False # Accept all files if file_type is None. else: return True # We collect all files to open in a list. path_to_Image = [] # Replacing some abbreviations (e.g. $HOME on Linux). path = os.path.expanduser(pathImage) path = os.path.expandvars(pathImage) # If we don't want a recursive search, we can use os.listdir(). for directory, dir_names, file_names in os.walk(pathImage): # We are only interested in files. for file_name in file_names: # The list contains only the file names. # The full path needs to be reconstructed. full_path = os.path.join(directory, file_name) # Both checks are performed to filter the files. if check_type(file_name): if check_filter(file_name) is False: # Add the file to the list of images to open. path_to_Image.append([ full_path, os.path.basename(os.path.splitext(full_path)[0]) ]) Images = [] for img_path, file_name in path_to_Image: imp = IJ.openImage(img_path) maskimage = ops.run("create.img", imp) cursor = maskimage.localizingCursor() imp.show() IJ.run("Select None") overlay = imp.getOverlay() if overlay == None: overlay = Overlay() imp.setOverlay(overlay) else: overlay.clear() imp.updateAndDraw() impY = imp.getHeight() impX = imp.getWidth() print(impY, impX) rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.runCommand("reset") WaitForUserDialog("Select the landmark and the second point").show() rm.runCommand("Add") roi_points = rm.getRoisAsArray() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints print(xpoints, ypoints) print('Start Landmark', xpoints[0], ypoints[0]) fixedpointX = xpoints[0] fixedpointY = ypoints[0] print('End Landmark', xpoints[1], ypoints[1]) IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1]) gui = GenericDialog("Rotation Angle") gui.addNumericField("Choose Angle", 15, 0) gui.showDialog() if gui.wasOKed(): rotateangle = gui.getNextNumber() IJ.run("Rotate...", "angle=" + str(int(float(rotateangle)))) rm.runCommand("reset") overlay = imp.getOverlay() rm.runCommand("Add") roi_points = rm.getRoisAsArray() for Roi in roi_points: xpoints = Roi.getPolygon().xpoints ypoints = Roi.getPolygon().ypoints print(xpoints, ypoints) print('Rotated Start Landmark', xpoints[0], ypoints[0]) print('Rotated End Landmark', xpoints[1], ypoints[1]) slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20) intercept = fixedpointY - slope * fixedpointX print(fixedpointX, fixedpointY) print('Slope', slope, 'Intercept', intercept) XwY0 = -intercept / slope YxwY0 = slope * XwY0 + intercept XwYmax = (impY - intercept) / slope YxwYmax = slope * XwYmax + intercept YwX0 = intercept XywX0 = (YwX0 - intercept) / slope YwXmax = impX * slope + intercept XxwXmax = (YwXmax - intercept) / slope rm.runCommand("reset") if XwY0 > 0: lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0) lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax) overlay.add(lineROIA) overlay.add(lineROIB) if XwY0 < 0: lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0) lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax) overlay.add(lineROIA) overlay.add(lineROIB) while cursor.hasNext(): cursor.fwd() X = cursor.getDoublePosition(0) Y = cursor.getDoublePosition(1) if abs(Y - slope * X - intercept) <= 4: cursor.get().set(0) else: cursor.get().set(1) labeling = ops.labeling().cca(maskimage, StructuringElement.EIGHT_CONNECTED) # get the index image (each object will have a unique gray level) labelingIndex = labeling.getIndexImg() dataImg = ds.create(labelingIndex) location = ls.resolve( str(savedir) + '/' + file_name + '.' + file_type_image) dio.save(dataImg, location) imp.close()
def poreDetectionTrueColor(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters): detectionParameters.setCalibration(inputImp); # calculate area of roi stats=inputImp.getStatistics() inputRoiArea=stats.area # get the bounding box of the active roi inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) cropped=ops.image().crop(inputDataset.getImgPlus(), interval ) datacropped=data.create(cropped) display.createDisplay("cropped", datacropped) croppedPlus=IJ.getImage() # instantiate the duplicator and the substackmaker classes duplicator=Duplicator() substackMaker=SubstackMaker() # duplicate the roi duplicate=duplicator.run(croppedPlus) # separate into RGB and get the blue channel IJ.run(duplicate, "RGB Stack", "") bluePlus=substackMaker.makeSubstack(duplicate, "3-3") blue=ImgPlus(ImageJFunctions.wrapByte(bluePlus)) bluePlus.setTitle("Blue") # duplicate and look for bright spots thresholdedLight=SpotDetection2(bluePlus) # duplicate and look for dark spots thresholdedDark=SpotDetection3(bluePlus, True) # convert to mask Prefs.blackBackground = True #IJ.run(thresholdedDark, "Convert to Mask", "")substackMaker # clear the region outside the roi clone=inputRoi.clone() clone.setLocation(0,0) Utility.clearOutsideRoi(thresholdedLight, clone) Utility.clearOutsideRoi(thresholdedDark, clone) roimClosedPores = RoiManager(True) detectionParameters.setCalibration(thresholdedDark) countParticles(thresholdedDark, roimClosedPores, detectionParameters.closedPoresMinSize, detectionParameters.closedPoresMaxSize, \ detectionParameters.closedPoresMinCircularity, detectionParameters.closedPoresMaxCircularity) # count number of open pores roimOpenPores = RoiManager(True) detectionParameters.setCalibration(thresholdedDark) countParticles(thresholdedDark, roimOpenPores, detectionParameters.openPoresMinSize, detectionParameters.openPoresMaxSize, \ detectionParameters.openPoresMinCircularity, detectionParameters.openPoresMaxCircularity) # count number of sebum roimSebum = RoiManager(True) detectionParameters.setCalibration(thresholdedLight) countParticles(thresholdedLight, roimSebum, detectionParameters.sebumMinSize, detectionParameters.sebumMaxSize, \ detectionParameters.sebumMinCircularity, detectionParameters.sebumMaxCircularity) # create lists for open and closed pores closedPoresList=[] for roi in roimClosedPores.getRoisAsArray(): closedPoresList.append(roi.clone()) openPoresList=[] for roi in roimOpenPores.getRoisAsArray(): openPoresList.append(roi.clone()) # create lists for sebum sebumsList=[] for roi in roimSebum.getRoisAsArray(): sebumsList.append(roi.clone()) # a list of all pores allList=closedPoresList+openPoresList+sebumsList # calculate the stats for all pores detectionParameters.setCalibration(bluePlus) statsDict=CountParticles.calculateParticleStats(bluePlus, allList) poresTotalArea=0 for area in statsDict['Areas']: poresTotalArea=poresTotalArea+area print area poresAverageArea=poresTotalArea/len(statsDict['Areas']) # for each roi add the offset such that the roi is positioned in the correct location for the # original image [roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList] # draw the rois on the image inputImp.getProcessor().setColor(Color.green) IJ.run(inputImp, "Line Width...", "line=3"); inputImp.getProcessor().draw(inputRoi) IJ.run(inputImp, "Line Width...", "line=1"); [CountParticles.drawParticleOnImage(inputImp, roi, Color.red) for roi in closedPoresList] [CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in openPoresList] [CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumsList] inputImp.updateAndDraw() # close images that represent intermediate steps croppedPlus.changes=False croppedPlus.close() bluePlus.changes=False bluePlus.close() print "Total ROI Area: "+str(inputRoiArea) print "Num closed pores: "+str(len(closedPoresList)) print "Num open pores: "+str(len(openPoresList)) print "Num sebums: "+str(len(sebumsList)) print "Total particles: "+str(len(allList))+ " total area: "+str(poresTotalArea) statslist=[inputRoiArea, len(allList), len(closedPoresList), len(openPoresList), len(sebumsList), poresAverageArea, 100*poresTotalArea/inputRoiArea] header=[Messages.TotalAreaMask, Messages.TotalDetectedPores, Messages.ClosedPores, Messages.OpenPores, Messages.Sebum, Messages.PoresAverageArea, Messages.PoresFractionalArea] return header,statslist
# set up first ROI manager table1 = ResultsTable() roim1 = RoiManager() pa1 = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA | Measurements.MEAN | Measurements.ELLIPSE, table1, 0, 100, 0, 1) pa1.setRoiManager(roim1) pa1.analyze(imp) # set up second ROI manager table2 = ResultsTable() # Pass true to second ROI manager so it will not be seen roim2 = RoiManager(True) pa2 = ParticleAnalyzer( ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA | Measurements.MEAN | Measurements.ELLIPSE, table2, 100, 500, 0, 1) pa2.setRoiManager(roim2) pa2.analyze(imp) print "rois from first manager:" for roi in roim1.getRoisAsArray(): print roi print print "rois from second manager:" for roi in roim2.getRoisAsArray(): print roi