def run():
    roidir = '/Volumes/TRANSCEND/LauraLeopold/Rois/'
    maskdir = '/Volumes/TRANSCEND/LauraLeopold/Mask/'
    originaldir = '/Volumes/TRANSCEND/LauraLeopold/Original/'
    Raw_path = os.path.join(originaldir, '*tif')
    X = glob.glob(Raw_path)
    axes = 'YX'
    for fname in X:
        print(fname)
        IJ.open(fname)
        imp = IJ.getImage()
        Name = os.path.basename(os.path.splitext(fname)[0])
        RoiName = roidir + Name + '.roi'
        Roi = IJ.open(RoiName)
        rm = RoiManager.getInstance()
        if (rm == None):
            rm = RoiManager()
        rm.addRoi(Roi)
        print(fname, RoiName)
        if not rm:
            print "Please first add some ROIs to the ROI Manager"
            return
        impMask = IJ.createImage("Mask", "8-bit grayscale-mode",
                                 imp.getWidth(), imp.getHeight(),
                                 imp.getNChannels(), imp.getNSlices(),
                                 imp.getNFrames())
        IJ.setForegroundColor(255, 255, 255)
        rm.runCommand(impMask, "Deselect")
        rm.runCommand(impMask, "Fill")
        rm.runCommand('Delete')
        IJ.saveAs(impMask, '.tif', maskdir + Name)
        imp.close()
Exemplo n.º 2
0
    def saveCroppedROIs(self, event):
        """ Duplicates cropped ROIs and saves """
        # Create export dir, if not already present
        current_export_dir = self.createExportDir("Cropped_ROI")

        for Image in self.Images.values():  # for all Image instances
            # save image
            cropped_copy = Image.imp.crop()  # returns cropped image as an imp
            img_filename = os.path.join(current_export_dir, Image.title)
            if os.path.splitext(img_filename)[1] != ".tif":
                os.path.join(img_filename, ".tif")
            FileSaver(cropped_copy).saveAsTiff(img_filename)

            # save roi
            roi_filename = os.path.splitext(img_filename)[0] + "_roi.roi"
            roi = Image.imp.getRoi()
            if roi != None:
                rm = RM.getInstance()
                if rm == None:
                    rm = RM()
                rm.addRoi(roi)
                rm.runCommand("Save", roi_filename)  # which one does it save
                rm.runCommand("Delete")
            IJ.log("Cropped ROI saved: " +
                   os.path.join(current_export_dir, Image.title))
Exemplo n.º 3
0
	def showimage(self):
		roim = RoiManager.getInstance()
		if roim is None:
			roim = RoiManager()
		IJ.run("Close All")
		IJ.run("Clear Results")
		try:
			roim.reset()
		except AttributeError:
			roim.runCommand("reset")
		obj = self.fcsimages[self.idximg][0]
		imgName = self.fcsimages[self.idximg][1]

		img =  BF.openImagePlus(imgName)[0]
		img.setZ(obj[1][2]+1)
		img.setC(3)
		IJ.run(img, "Grays", "");
		img.setC(1)
		img.show()

		#draw rois
		for i in range(1, len(obj)+1):
			PR = PointRoi(obj[i][0],obj[i][1])
			try:
				PR.setSize(3)
				PR.setPointType(0)
				roim.addRoi(PR)
			except:
				roim.addRoi(PR)
		roim.runCommand('Show All with Labels')
Exemplo n.º 4
0
def save_qcd_edges2(edges, output_folder, filename="user_defined_edges.zip"):
    """save edges as rois to a *.zip file"""
    roim = RoiManager(False)
    for edge in edges:
        if edge is not None:
            roim.addRoi(edge)
    roim.runCommand("Save", os.path.join(output_folder, filename))
    roim.close()
Exemplo n.º 5
0
def save_cell_rois(rois, output_folder, filename):
    """save cell rois to a *.zip file"""
    roim = RoiManager(False)
    for roi in rois:
        if roi is not None:
            roim.addRoi(roi)
    roim.runCommand(
        "Save", os.path.join(output_folder,
                             "{} cell rois.zip".format(filename)))
    roim.close()
Exemplo n.º 6
0
def save_roi(directory, name, roi):
    """Saves ROI object in specific directory"""
    if roi is not None:
        rm = RoiManager(False)
        print roi.getName()
        roifile = path.join(directory, name+".zip")
        rm.addRoi(roi)
        rm.runCommand("Save", roifile)
    else:
        print "skipping saving ROI"
Exemplo n.º 7
0
def save_qc_image(imp, rois, output_path):
    """save rois overlaid on imp to output_path"""
    imp.killRoi()
    roim = RoiManager(False)
    for roi in rois:
        roim.addRoi(roi)
    roim.runCommand("Show All with labels")
    RGBStackConverter.convertToRGB(imp)
    roim.moveRoisToOverlay(imp)
    FileSaver(imp).saveAsTiff(output_path)
    roim.runCommand("Show None")
    roim.close()
Exemplo n.º 8
0
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
Exemplo n.º 9
0
def createROI(xy_coord, diameter):
    imp = WindowManager.getCurrentImage()
    pixelWidth = imp.getCalibration().pixelWidth
    pixelHeight = imp.getCalibration().pixelHeight
    x_diameter = diameter / pixelWidth
    y_diameter = diameter / pixelHeight
    x_coord = xy_coord[0] / pixelWidth - (0.5 * x_diameter)
    y_coord = xy_coord[1] / pixelHeight - (0.5 * y_diameter)

    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()

    roi = OvalRoi(x_coord, y_coord, x_diameter, y_diameter)
    rm.addRoi(roi)
Exemplo n.º 10
0
def generate_limit_labels(imp, limits, cb_fraction, params):
    """generate text ROIs in correct positions to label colorbar"""
    rois = []
    w = imp.getWidth()
    h = imp.getHeight()
    txt_h_px = float(h) / 15
    txt_sz_pt = int(round((18.0 / 24.0) * txt_h_px))
    for limit in limits:
        roi = TextRoi(1, 1, str(round(limit, 3)),
                      Font("SansSerif", Font.ITALIC, txt_sz_pt))
        roi.setJustification(TextRoi.RIGHT)
        roi.setFillColor(Color.BLACK)
        roi.setStrokeColor(Color.WHITE)
        rois.append(roi)
    roim = RoiManager(False)
    roim.reset()
    imp.show()
    mbui.autoset_zoom(imp)
    for fridx in range(1, imp.getNSlices() + 1):
        imp.setPosition(fridx)
        roi_uu = rois[1].clone()
        xpos = w - cb_fraction * w - float(w) / 100 - rois[1].getFloatWidth()
        roi_uu.setLocation(xpos, 1)
        imp.setRoi(roi_uu)
        roim.addRoi(roi_uu)
        roi_ll = rois[0].clone()
        roi_ll.setLocation(xpos, h - rois[0].getFloatHeight())
        imp.setRoi(roi_ll)
        roim.addRoi(roi_ll)
    roim.runCommand("Show All")
    FileSaver(imp).saveAsTiff(
        os.path.join(params.output_path,
                     "overlaid curvature nudged labels.tif"))
    # nudge positions
    roim.reset()
    imp.killRoi()
    for fridx in range(1, imp.getNSlices() + 1):
        imp.setPosition(fridx)
        roi_uu = rois[1].clone()
        xpos = w - cb_fraction * w - float(w) / 100
        roi_uu.setLocation(xpos, 1)
        imp.setRoi(roi_uu)
        roim.addRoi(roi_uu)
        roi_ll = rois[0].clone()
        roi_ll.setLocation(xpos, h - rois[0].getFloatHeight())
        imp.setRoi(roi_ll)
        roim.addRoi(roi_ll)
    roim.runCommand("Show All")
    FileSaver(imp).saveAsTiff(
        os.path.join(params.output_path, "overlaid curvature.tif"))
    return imp
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
def process(subFolder, outputDirectory, filename):
    #IJ.close()
    imp = IJ.openImage(inputDirectory + subFolder + '/' + rreplace(filename, "_ch00.tif", ".tif"))
    imp.show()


    # Finds the pixel length in microns from the xml metadata file
    file_list = [file for file in os.listdir(inputDirectory + subFolder) if file.endswith('.xml')]
    if len(file_list) > 0:
        xml = os.path.join(inputDirectory + subFolder, file_list[0])
        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.877017

    log.write("Pixel Length:" + str(pixel_length) + "\n")

    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)


    # If wand tool is enabled, then this will prompt that to be used
    if enableWand:
        # Call threshold function to adjust threshold and select Organoid ROI
        IJ.run("Threshold...")
        WaitForUserDialog("Adjust Threshold to create mask").show()
        IJ.setTool("Wand")
        WaitForUserDialog("Click on Organoid Area for it to be selected. Best selection will be at the edge of the organoid to get entire organoid shape.").show()
        IJ.run("Clear Outside")

    if not enableWand:
        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()
        imp = getCurrentImage()
        rm.select(imp, 0)
        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')
    mask = IJ.openImage(inputDirectory + '/mask.tif')

    if enableWand:
        #Select ROI again to add it to the the ROI manager so that intensities and area is saved
        #IJ.run("Threshold...")
        IJ.setTool("Wand")
        WaitForUserDialog("Select Organoid area again for it to register within the ROI manager").show()
        rm = RoiManager()
        boundroi = ThresholdToSelection.run(mask)
        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

    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 = imp.getStatistics(Measurements.MEAN | Measurements.AREA)
            intensities[x] = stats.mean
            bigAreas[x] = stats.area

    rm.close()

    # Opens the ch00 image and sets default properties
    apply_mask = ImageCalculator()
    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=" + str(pixel_length) + " pixel_height=" + str(pixel_length) + " 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", "")
Exemplo n.º 13
0
	def __settings(self, imgName) :
		"""
		Lets the user to choose different measures to make, and displays it following the choice of the user.
		
		"""

		try : dico=self.__dictCells[imgName]
		except KeyError : 
			try : dico=self.__dictCells[imgName[:-4]]
			except KeyError : return False
			else : imgName=imgName[:-4]
		
		dico=self.__dictCells[imgName]
		for cellname in dico.keys() :
			self.__dictMeasures[dico[cellname]]={}
			
		# Represents the datas on a diagram
		def diagrambuttonPressed(event) :
			IJ.showMessage("Push 'Auto' button each time you want to see the diagram")
			x1=10
			y1=20
			x2=100
			y2=50
			x3=60
			y3=30
			xr=10
			yr=20
			wr=20
			hr=20

			
			rect=Rectangle(xr,yr,wr,hr)
			
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife
			IJ.run("Hyperstack...", "title=Diagram type=32-bit display=Color width="+str(x2+(nbslices+1)*x3)+" height="+str(y2+y3*len(dico))+" channels=1 slices="+str(len(self.__measures))+" frames=1")
			im=IJ.getImage()
			ip=im.getProcessor()
			for i in range(len(self.__measures)) :
				indiceligne=0
				maxvalue=0
				minvalue=1000000
				im.setPosition(1,i+1,1)
				for cellname in self.__listcellname :
					indiceligne+=1
					for indicecolonne in range(1,nbslices+1):
						rect.setLocation(x2+indicecolonne*x3+int(x3/6),(y1+indiceligne*y3-int(y3/2)))
						# we create at the first iteration a dictionary with the rectangles (for a future use)
						if i==0 :
							self.__gridrectangle[(indiceligne,indicecolonne)]=Rectangle(rect)
						im.setRoi(rect)
						ipr=im.getProcessor()
						# we find the min and max values of the datas for a measure given.
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]>maxvalue :
							maxvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]<minvalue :
							minvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						# we fill the rectangle with the value of the measure
						ipr.setValue(self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1])
						ipr.fill()
				# we write the names and the n of slices on the image with the maxvalue.
				ip.setValue(maxvalue)
				ip.moveTo(x1,y1)
				ip.drawString(self.__measures[i])
				for j in range(1,nbslices+1) :
					ip.moveTo(x2+j*x3,y1)
					ip.drawString("Slice "+str(j))
				j=0
				for cellname in self.__listcellname :
					ip.moveTo(x1,y2+j*y3)
					ip.drawString(cellname)
					j+=1
			im.killRoi()
			im=IJ.run(im,"Fire","")
			IJ.run("Brightness/Contrast...", "")
			#im.setMinAndMax(minvalue,maxvalue)
			#im.updateImage()
			
			#we add a mouse listener in order to be able to show the roi corresponding to a rectangle when the user clicks on it.
			listener = ML()
			listener.name=imgName
			for imp in map(WindowManager.getImage, WindowManager.getIDList()):
				if imp.getTitle().startswith("Diagram") : 
					win = imp.getWindow()
 					if win is None:
						continue
					win.getCanvas().addMouseListener(listener)
		
		# Represents the datas on a series of graphs.
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")

		#def histbuttonPressed(event) :
		#	
		#	pass

		# Represents the values in a tab.
		def tabbuttonPressed(event) :
		
			tab="\t"
			headings=[]
			measures=[]
			#img=IJ.getImage()
			#for i in range(self.__img.getImageStackSize()+1) :
			for i in range(self.__maxLife+1) :
				headings.append("Slice "+str(i))
			
			headings[0]=WindowManager.getUniqueName(self.__img.getShortTitle())
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				
				headstring=""
				for head in headings: 
					headstring+=head+tab
				tw=TextWindow(self.__listfiles[0]+"-"+m,headstring,"",800,600)
				tp=tw.getTextPanel()
				#for cellname in dico.keys() :
				for cellname in self.__listcellname :
					line=[]
					line=[str(meas)+tab for meas in self.__dictMeasures[dico[cellname]][m]]
					line.insert(0, cellname+tab)
					linestr=""
					for s in line: linestr+=s
					tp.appendLine(linestr)
				tp.updateDisplay()

			if self.__measuresparambool_global[0] :
				tw=TextWindow("Latency","cell\tLatency", "",800,600)
				tp=tw.getTextPanel()
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					tp.appendLine(line)
				tp.updateDisplay() 
				
		def helpbuttonPressed(event) :

			IJ.showMessage("TO DO")

		def newsetPressed(event) :
			gd0.dispose()
			self.__settings()

		def alignbuttonPressed(event) :
			IJ.showMessage("TO DO")


		def mergebuttonPressed(event) :
			IJ.showMessage("TO DO")

		def saveResults() :
			
			#if len(self.__listcellname) == 0 :
			
			nbslices=self.__maxLife
			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time_sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
							
			if not path.exists(self.__rootpath+"Results"+os.path.sep) : os.makedirs(self.__rootpath+os.path.sep+"Results"+os.path.sep, mode=0777)
			tab="\t"
			nl="\n"
			measures=[]
			headstring=""
			#if self.__savemode : mode = "a"
			#else : mode ="w"
			mode = "a"
			
			#for i in range(1, self.__maxLife+1) :headstring += "Slice_"+str(i)+tab
			for i in range(self.__maxLife) :headstring += str(x[i])+tab
			
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				#f.write(m+nl)
				f.write(imgName+"-"+self.__time+"-"+m+"-"+namex+tab+headstring+nl)
				if len(self.__listcellname) == 0 : f.write("no cells")
				else : 
					for cellname in self.__listcellname :
						linestr=cellname+tab
						for measure in self.__dictMeasures[dico[cellname]][m] :
							#print m, cellname, measure 
							linestr += str(measure)+tab
						linestr+=nl
						f.write(linestr)
				f.close()

			if self.__measuresparambool_global[0] :
				m = "Latency"
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				f.write(imgName+"-"+self.__time+"-"+m+nl)
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					line+=nl
					f.write(line)
				f.close()
				
			

			

		#
		# ----------- main measures dialog -------------------------
		#
     		# Allows the user to choose the measures to make, etc..
		
		measureslabels_indep=["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"]
		measureslabels_dep=["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"]
		measureslabels_global=["Latency", "velocity", "cumulatedDist"]
		measureslabels_dep_tabonly=set(["MidAxis","FerCoord","FerAxis","Fprofil","MidProfil","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"])
		ens_measures_global=set(measureslabels_global)
		ens_measures_indep=set(measureslabels_indep)
		ens_measures_dep=set(measureslabels_dep)
		measureslabels=[]
		
		for label in measureslabels_indep :
			measureslabels.append(label)

		for label in measureslabels_dep :
			measureslabels.append(label)

		#self.__defaultmeasures=[False for i in range(len(measureslabels))]
		#self.__defaultmeasures_global=[False for i in range(len(measureslabels_global))]

		gdmeasures=NonBlockingGenericDialog("MeasuresChoice")
		gdmeasures.setFont(Font("Courrier", 1, 10))
		gdmeasures.addMessage("*******     TIME SETTINGS     *******")
		gdmeasures.addCheckbox("Only starting at begining  :", self.__onlystart)				# 1 only start
		gdmeasures.addNumericField("Minimal Lifetime  : ",self.__minLife,0)
		gdmeasures.addNumericField("Maximal Lifetime  : ",self.__maxLife,0)
		#gdmeasures.addNumericField("Maximal Lifetime  : ",self.__img.getImageStackSize(),0)
		gdmeasures.addCheckbox("x axis in seconds", self.__useTime)				# 2 use time
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		gdmeasures.addMessage("Choose the measures to make on the cells : ")			
		gdmeasures.addMessage("*******     TIME MEASURES     *******")
		gdmeasures.addCheckboxGroup(4,8,measureslabels,self.__defaultmeasures)
		gdmeasures.addMessage("")
		gdmeasures.addMessage("*******     GLOBAL MEASURES     *******")
		gdmeasures.addMessage("PLEASE : If you have selected movement parameters you MUST to select XC and YC !")
		gdmeasures.addCheckboxGroup(3,1,measureslabels_global,self.__defaultmeasures_global)
		gdmeasures.addNumericField("Noise value for maxima finder: ",self.__noise,0)
		gdmeasures.addMessage("")	
		gdmeasures.addMessage("*******     OPTIONS     *******")
		gdmeasures.addCheckbox("Select the cells in next dialog ?", self.__onlyselect)			# 3 only select
		gdmeasures.addCheckbox("Save results to text files ?", self.__savetables)			# 4 save files
		#gdmeasures.addCheckbox("Append mode ?", self.__savemode)					# 5 append mode
		gdmeasures.addCheckbox("Analyse in batch mode ?", self.__batchanalyse)				# 6 analysis batch mode
		gdmeasures.addCheckbox("Update overlay ?", self.__updateoverlay)				# 7 update overlay
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		help_panel=Panel()
		helpbutton=Button("HELP")
		helpbutton.actionPerformed = helpbuttonPressed
		help_panel.add(helpbutton)	
		gdmeasures.addPanel(help_panel)	
		gdmeasures.hideCancelButton()

		if not self.__batchanalyse :
			gdmeasures.showDialog()
			self.__onlystart=gdmeasures.getNextBoolean() 						# 1 only start
			self.__minLife=gdmeasures.getNextNumber()
			self.__maxLife=gdmeasures.getNextNumber()
			self.__useTime=gdmeasures.getNextBoolean()						# 2 use time

			self.__measuresparambool=[]
			self.__measuresparambool_global=[]
			for i in range(len(measureslabels)) : 
				self.__measuresparambool.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures[i]=self.__measuresparambool[-1]
			for i in range(len(measureslabels_global)) : 
				self.__measuresparambool_global.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures_global[i] = self.__measuresparambool_global[i]
 
			self.__noise=gdmeasures.getNextNumber()
			self.__onlyselect=gdmeasures.getNextBoolean()						# 3 only select
			self.__savetables = gdmeasures.getNextBoolean()						# 4 save files
			#self.__savemode = gdmeasures.getNextBoolean()						# 5 append mode
			self.__batchanalyse = gdmeasures.getNextBoolean()					# 6 analyse mode
			self.__updateoverlay = gdmeasures.getNextBoolean()					# 7 update overlay

		# we update a list of all cells that have a lifetime corresponding to what the user chose.
		if len (self.__allcells) == 0 :
			for cellname in dico.keys() :
				if dico[cellname].getLifeTime()>=self.__minLife : #and dico[cellname].getLifeTime()<=self.__maxLife :
					if self.__onlystart :
						if dico[cellname].getSlideInit()<2 : self.__allcells.append(cellname)
						else : self.__allcells.append(cellname)

		
		if self.__noise == 0 : self.__noise = None
		if self.__batchanalyse : self.__onlyselect = False
		
		if self.__onlyselect : 
			
			try : 
				self.__gw
			except AttributeError :
				if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
				self.__gw = CellsSelection()
				self.__gw.setTitle(imgName)
				self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
				self.__gw.show()
				self.__gw.setSelected(self.__allcells)
				while not self.__gw.oked and self.__gw.isShowing() : 
					self.__gw.setLabel("Validate selection with OK !!")
					self.__listcellname = list(self.__gw.getSelected())
				self.__gw.resetok()
				self.__gw.setLabel("...")
				self.__gw.hide()
			else : 
				if self.__gw.getTitle() == imgName :
					self.__gw.show()
					self.__gw.setSelected(self.__listcellname)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

				else : 
					self.__gw.dispose()
					if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
					self.__gw = CellsSelection()
					self.__gw.setTitle(imgName)
					self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
					self.__gw.show()
					self.__gw.setSelected(self.__allcells)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

			filestodelet=glob.glob(self.__pathdir+"Selected-Cells"+os.path.sep+"*.cell")
			for f in filestodelet : os.remove(f)
			for cell in self.__listcellname :
				sourcestr = self.__pathdir+"Cells"+os.path.sep+cell+".cell"
				deststr =  self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell"
				#os.system("copy "+sourcestr+", "+deststr) 
				#shutil.copy(self.__pathdir+"Cells"+os.path.sep+cell+".cell",self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell")
				shutil.copy(sourcestr,deststr)

			self.__dictNcells[imgName] = len(self.__listcellname)
		
		else : 
			self.__listcellname = list(self.__allcells)
			self.__dictNcells[imgName] = len(self.__listcellname)

		if len(self.__listcellname) == 0 : 
			self.__dictNcells[imgName] = 0
			return False
		
		self.__img.hide()
		
		# we make the measures.
		for i in range(len(measureslabels)) :
			IJ.showProgress(i, len(measureslabels))
			if  self.__measuresparambool[i]==True :
				
				self.__measurescompl.append(measureslabels[i])
				
				if (measureslabels[i] in measureslabels_dep_tabonly)==False :
					self.__measures.append(measureslabels[i])
				
				if (i<18) and (measureslabels[i] in ens_measures_indep) :
					self.__measureAll(self.__img,measureslabels[i],False, imgName, self.__noise)
					ens_measures_indep.discard(measureslabels[i])
					
				if i>=18 :
					self.__measureAll(self.__img,measureslabels[i],True, imgName, self.__noise)
					
		if self.__measuresparambool_global[0] : # calculate latency
			latencies=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				latencies.append(self.latencie(self.__listcellname[i], self.__img, imgName, self.__useTime))

		if self.__measuresparambool_global[1] : # calculate velocity
			self.__measures.append("velocity")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measureVelocity(self.__img,imgName)

		if self.__measuresparambool_global[2] : # calculate cumulatedDistance
			self.__measures.append("cumulatedDist")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measurecumulDist(self.__img,imgName)	
				
		
		self.__img.show()

		self.__img.getProcessor().resetThreshold()		

		
		if self.__updateoverlay :
			if self.__img.getOverlay() is not None : self.__img.getOverlay().clear()
		
			outputrois=[]
			cellnames=[]
			self.__img.hide()
			for cellname in self.__listcellname :
				
				for r in dico[cellname].getListRoi():
					if isinstance(r,Roi) : 
						pos=r.getPosition()
						#print "MC overlay", cellname, r.getName(), pos
						#r.setPosition(0)
						#overlay.add(r)
						outputrois.append(r)
						if "cell" in r.getName() : cellnames.append(r.getName())
						else : cellnames.append(str(pos)+"-"+cellname)
						#print cellnames[-1]

			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.show()
			self.__img.show()
			IJ.selectWindow(self.__img.getTitle())
			rm.runCommand("reset")
			for i in range(len(outputrois)) :
				outputrois[i].setName(cellnames[i])
				rm.addRoi(outputrois[i])
				rm.select(rm.getCount()-1)
				rm.runCommand("Rename", cellnames[i])
			
			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(self.__img, "Labels...", "color=red font=12 show use")
			IJ.run(self.__img, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")


		# ----------- batch analyse ------------------------
		if self.__batchanalyse :
			if self.__savetables :  saveResults()
			self.__dictMeasures.clear()
     			self.__allcells[:]=[]
     			self.__measurescompl[:]=[]
     			self.__measures[:]=[] 
			return False
			
		# ---------- display methodes dialog ----------------
		# Allows the user to choose how to see the results of the measures.		
		
		gd0=NonBlockingGenericDialog("Display")

		gd0.addMessage("How do you want to see the results ?")
		
		panel0=Panel()
		
		diagrambutton=Button("Diagram")
		diagrambutton.actionPerformed = diagrambuttonPressed
		panel0.add(diagrambutton)

		graphbutton=Button("Graph")
		graphbutton.actionPerformed = graphbuttonPressed
		panel0.add(graphbutton)

		tabbutton=Button("Tab")
		tabbutton.actionPerformed = tabbuttonPressed
		panel0.add(tabbutton)
		gd0.addPanel(panel0)
		gd0.addCheckbox("Analyse next stack ?", self.__nextstack)
		gd0.hideCancelButton()	
		gd0.showDialog()

		self.__nextstack = gd0.getNextBoolean()

		# ---------- save tables ---------------------------
		if self.__savetables :  saveResults()
		
		# --------- re-start analysis -------------------
		
     		self.__dictMeasures.clear()
     		#self.__listcellname[:]=[]
     		self.__allcells[:]=[]
     		self.__measurescompl[:]=[]
     		self.__measures[:]=[]

     		if self.__nextstack : return False
     		else : return True
Exemplo n.º 14
0
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: Only accept files that contain the given string (default: None).
    :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 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)
        print(img_path)
        if check_filter(file_name):
         continue;
        else: 
         print(file_name  ,  pathRoi)
         RoiName = str(pathRoi) + '/'+ file_name + '.roi'
         Roi = IJ.open(RoiName)
         # An object equals True and None equals False.
         rm = RoiManager.getInstance()
         if (rm==None):
            rm = RoiManager()
         rm.addRoi(Roi)
         
         impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames())
         IJ.setForegroundColor(255, 255, 255)
         rm.runCommand(impMask,"Deselect")
         rm.runCommand(impMask,"Fill")
         rm.runCommand('Delete')
         IJ.saveAs(impMask, '.tif', str(pathMask) + "/"  +  file_name);
         imp.close();
        
         #print(img_path, RoiName)
         Images.append(imp)
         Rois.append(Roi)    
    return Images, Rois
Exemplo n.º 15
0
from ij import IJ
from ij import ImagePlus
from ij.gui import Roi, PointRoi, PolygonRoi
from ij.plugin.frame import RoiManager

ROI_PIXEL_INPUT_FILE_PATH = "/media/raid/michael/CellVision/segmenter/CellVisionSegmenter/imagej_files/reg001_X05_Y02_Z05-coords.txt"

imp = IJ.getImage()
rm = RoiManager.getInstance()
if not rm:
    rm = RoiManager()

roi_raw_vals = []
with open(ROI_PIXEL_INPUT_FILE_PATH, "r") as f:
    input_content = f.read()
    roi_raw_vals = input_content.splitlines()

for roi_raw_val in roi_raw_vals:
    raw_roi = roi_raw_val.split(',')
    roi_x = [float(x) for x in raw_roi[0].split()]
    roi_y = [float(x) for x in raw_roi[1].split()]
    roi = PolygonRoi(roi_x, roi_y, Roi.FREEROI)
    rm.addRoi(roi)
Exemplo n.º 16
0
from ij.plugin.frame import RoiManager
from ij.gui import WaitForUserDialog, Toolbar

#remove all the previous ROIS
imp = IJ.getImage()
rm = RoiManager.getInstance()
if not rm:
    rm = RoiManager()
rm.runCommand("reset")

#ask the user to define a selection and get the bounds of the selection
IJ.setTool(Toolbar.RECTANGLE)
WaitForUserDialog("Select the area,then click OK.").show()
boundRect = imp.getRoi()
imp.setRoi(boundRect)
rm.addRoi(boundRect)

imp = IJ.getImage()
cal = imp.getCalibration()  # in microns

img = IJF.wrap(imp)

print(img.dimensions)
# Create a variable of the correct type (UnsignedByteType) for the value-extended view
zero = img.randomAccess().get().createVariable()

# Run the difference of Gaussian
cell = 30.0  # microns in diameter
min_peak = 10.0  # min intensity for a peak to be considered
dog = DogDetection(
    Views.extendValue(img, zero),
Exemplo n.º 17
0
                                   roi1.getAngle() + 90))
end_lower_point = (calculate_point(point2[0], point2[1], roi_width,
                                   roi1.getAngle() - 90))

x_coordinates = [
    starting_upper_point[0], starting_lower_point[0], end_lower_point[0],
    end_upper_point[0]
]
y_coordinates = [
    starting_upper_point[1], starting_lower_point[1], end_lower_point[1],
    end_upper_point[1]
]

roi2 = PolygonRoi(x_coordinates, y_coordinates, Roi.POLYGON)
imp1.setRoi(roi2)
rm.addRoi(roi2)

# Generate boxes along line profile and add them to the ROI manager

for i in range(1, (number_of_rois - 1)):
    point1 = (coordinates.xpoints[i], coordinates.ypoints[i])
    point2 = (coordinates.xpoints[i + 1], coordinates.ypoints[i + 1])
    if i + 2 == number_of_rois:
        point3 = (coordinates.xpoints[i + 1], coordinates.ypoints[i + 1]
                  )  # for graceful interpolation of angles
    else:
        point3 = (coordinates.xpoints[i + 2], coordinates.ypoints[i + 2]
                  )  # for graceful interpolation of angles
    roi4 = Line(point1[0], point1[1], point3[0], point3[1])
    roi1 = Line(point1[0], point1[1], point2[0], point2[1])
    starting_upper_point = end_upper_point
Exemplo n.º 18
0
	def __displayCells(self, nameimage, methodeleon=False):
		"""
		Displays all the ROIs of the cells with different colors
		
		"""
		# we define a list of colors that will be used.

		colors = []
		ncells= len(self.__dict[nameimage])
		if ncells > 0 :
			step=200/ncells
			if step<1 : step=1
			for i in range(ncells) : 
				r = random.randrange(5,205,step)
				g = random.randrange(10,210,step)
				b = random.randrange(30,230,step)
				#r = int(0+i*step)
				#g = random.randrange(10, 190, 30)
				#b = int(250-i*step)
				
				colors.append(Color(r, g, b))

		else : 	colors=[Color.blue, Color.green, Color.magenta, Color.orange, Color.yellow]
		tempcolors=list(colors)
		# we try to have random and different colors for each cell.
		for cellname in self.__dict[nameimage].keys() :
			if len(tempcolors)>0 : 
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
			else :
				tempcolors=list(colors)
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
		

		self.__SaveCells(nameimage)
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		# if the user wants to save files, .zip for the ROIs are saved.
		#if self.__optionSave == True : 
		#os.mkdir(self.__pathdir+"ROIs/", mode=0777)
		os.makedirs(self.__pathdir+"ROIs/", mode=0777)
		tempimp = IJ.createImage("tempimp", "8-bit Black", self.__dictImages[nameimage].getWidth(), self.__dictImages[nameimage].getHeight(), 1)
		tempimp.show()
		for cellname in self.__dict[nameimage].keys() :
			for numslice in range(self.__dictImages[nameimage].getImageStackSize()) :
				r = self.__dict[nameimage][cellname].getRoi(numslice)
				try : 
					name=r.getName()
				
				except AttributeError : continue

				else :
					s = "%04i" % (numslice+1)
					#name=s+"-"+name.split("-", 1)[1]
					name=s+"-cell"+name.split("cell")[1]
					r.setName(name)
					try :
						rm.addRoi(r)
						rname=rm.getName(rm.getCount()-1)
						#rm.select(self.__dictImages[nameimage], rm.getCount()-1)
						rm.select(tempimp, rm.getCount()-1)
						rm.runCommand("Rename", name)
					except TypeError : continue
					
					
				#if isinstance(self.__dict[nameimage][cellname].getRoi(numslice),Roi) == True :
				#	s = "%04i" % (numslice)
				#	#rm.add(self.__dictImages[nameimage], self.__dict[nameimage][cellname].getRoi(numslice)  ,  numslice)
				#	name=self.__dict[nameimage][cellname].getRoi(numslice).getName()
				#	name=s+name
				#	self.__dict[nameimage][cellname].getRoi(numslice).setName(name)
				#	rm.addRoi(self.__dict[nameimage][cellname].getRoi(numslice))
			rm.runCommand("Save", self.__pathdir+"ROIs/"+cellname+".zip")
			rm.runCommand("reset")
		
		tempimp.close()
Exemplo n.º 19
0
def run():

	IJ.run("Close All", "")
	IJ.log("\\Clear")

	IJ.log("Find_close_peaks")

	imp = IJ.run("Bio-Formats Importer")
	imp = IJ.getImage()


	Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist = getOptions()

	IJ.log("option used:" \
    		+ "\n" + "channel 1:" + str(Channel_1) \
    		+ "\n" + "channel 2:"+ str(Channel_2) \
    		+ "\n" + "Radius Background:"+ str(radius_background) \
    		+ "\n" + "Smaller Sigma:"+ str(sigmaSmaller) \
    		+ "\n" + "Larger Sigma:"+str(sigmaLarger) \
    		+ "\n" + "Min Peak Value:"+str(minPeakValue) \
    		+ "\n" + "Min dist between peaks:"+str(min_dist))

	IJ.log("Computing Max Intensity Projection")

	if imp.getDimensions()[3] > 1:
		imp_max = ZProjector.run(imp,"max")
		#imp_max = IJ.run("Z Project...", "projection=[Max Intensity]")
		#imp_max = IJ.getImage()
	else:
		imp_max = imp

	ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2)
	imp1, imp2 = back_substraction(ip1, ip2, radius_background)
	imp1.show()
	imp2.show()

	IJ.log("Finding Peaks")

	ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue)

	# Create a PointRoi from the DoG peaks, for visualization
	roi_1 = PointRoi(0, 0)
	roi_2 = PointRoi(0, 0)
	roi_3 = PointRoi(0, 0)
	roi_4 = PointRoi(0, 0)

	# A temporary array of integers, one per dimension the image has
	p_1 = zeros(ip1_1.numDimensions(), 'i')
	p_2 = zeros(ip2_1.numDimensions(), 'i')

	# Load every peak as a point in the PointRoi
	for peak in peaks_1:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_1)
	  roi_1.addPoint(imp1, p_1[0], p_1[1])

	for peak in peaks_2:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_2)
	  roi_2.addPoint(imp2, p_2[0], p_2[1])

	# Chose minimum distance in pixel
	#min_dist = 20

	for peak_1 in peaks_1:
		peak_1.localize(p_1)
		for peak_2 in peaks_2:
			peak_2.localize(p_2)
			d1 = distance(p_1, p_2)
			if  d1 < min_dist:
				roi_3.addPoint(imp1, p_2[0], p_2[1])
				break

	for peak_2 in peaks_2:
		peak_2.localize(p_2)
		for peak_1 in peaks_1:
			peak_1.localize(p_1)
			d2 = distance(p_2, p_1)
			if  d2 < min_dist:
				roi_4.addPoint(imp1, p_2[0], p_2[1])
				break

	rm = RoiManager.getInstance()
	if not rm:
	  rm = RoiManager()
	rm.reset()

	rm.addRoi(roi_1)
	rm.addRoi(roi_2)
	rm.addRoi(roi_3)
	rm.addRoi(roi_4)

	rm.select(0)
	rm.rename(0, "ROI neuron")
	rm.runCommand("Set Color", "yellow")

	rm.select(1)
	rm.rename(1, "ROI glioma")
	rm.runCommand("Set Color", "blue")

	rm.select(2)
	rm.rename(2, "ROI glioma touching neurons")
	rm.runCommand("Set Color", "red")

	rm.select(3)
	rm.rename(3, "ROI neurons touching glioma")
	rm.runCommand("Set Color", "green")

	rm.runCommand(imp1, "Show All")

	#Change distance to be in um
	cal = imp.getCalibration()
	min_distance = str(round((cal.pixelWidth * min_dist),1))

	table = ResultsTable()
	table.incrementCounter()
	table.addValue("Numbers of Neuron Markers", roi_1.getCount(0))
	table.addValue("Numbers of Glioma Markers", roi_2.getCount(0))
	table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0))
	table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0))

	table.show("Results Analysis")
Exemplo n.º 20
0
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)
Exemplo n.º 21
0
	xmlfile = arg[0]
	ch = 1

#open xml file and parse it
tree = ET.parse(xmlfile)
root = tree.getroot()
obj, imgName = getPosition(root)
print imgName

#open image
img =  BF.openImagePlus(imgName)[0] 
img.setZ(obj[1][2]+1)
img.setC(int(ch))
img.show()


#draw rois
for i in range(1, len(obj)+1):
	PR = PointRoi(obj[i][0],obj[i][1])
	try:
		PR.setSize(3)
		PR.setPointType(0)
		roim.addRoi(PR)
	except:
		roim.addRoi(PR)

roim.runCommand('Show All with Labels')



Exemplo n.º 22
0
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager
from ij.plugin.filter import Analyzer
from ij.measure import Measurements, ResultsTable

imp = IJ.getImage()  
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists 
 
bright_roi = OvalRoi(118,94,12,12); # define and add ROI
imp.setRoi(bright_roi)  # make active on image
rm.addRoi(bright_roi)  # add
#rm.select(0) # select the ROI

dark_roi = OvalRoi(138,144,12,12)
imp.setRoi(dark_roi)  # make active on image
rm.addRoi(dark_roi)  # add

rm.runCommand(imp,"Measure")		# this will create a new results table
rm.runCommand(imp,"Show All")		# show all ROI
rt = Analyzer.getResultsTable()		

bright_mean = rt.getValueAsDouble(rt.getColumnIndex("Max"),0)
dark_mean = rt.getValueAsDouble(rt.getColumnIndex("Mean"),1)
print "Bright :" + str(bright_mean) + " Dark: " + str(dark_mean) +  "the contrast value is :" + str(bright_mean/dark_mean) #access table by col and row
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
#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)


#imp = IJ.getImage()
#roi = imp.getRoi()
#p = roi.getPolygon()
#peterimeter = roi.getLength()
#p.npoints

#rm.sort()
#rm.split();
#print rm 
#for i in range(1,p.npoints):
#	print "(" + str(p.xpoints[i]) + "," + str(p.ypoints[i]) + ")"

#IJ.run("Create Selection");
Exemplo n.º 25
0
if WhiteBackground:
    Type = DogDetection.ExtremaType.MAXIMA
else:
    Type = DogDetection.ExtremaType.MINIMA
dog = DogDetection(Views.extendValue(img, zero), img,
                   [cal.pixelWidth, cal.pixelHeight], cell / 2, cell, Type,
                   min_peak, False, DoubleType())

peaks = dog.getPeaks()

roi = OvalRoi(0, 0, cell / cal.pixelWidth, cell / cal.pixelHeight)

p = zeros(img.numDimensions(), 'i')
overlay = Overlay()
imp.setOverlay(overlay)
regionpeak = 0
for peak in peaks:

    # Read peak coordinates into an array of integers
    peak.localize(p)
    if (boundRect.contains(p[0], p[1])):
        oval = OvalRoi(p[0] - 0.5 * cell / cal.pixelWidth,
                       p[1] - 0.5 * cell / cal.pixelHeight,
                       cell / cal.pixelWidth, cell / cal.pixelHeight)
        oval.setColor(Color.RED)
        overlay.add(oval)
        regionpeak = regionpeak + 1
        rm.addRoi(oval)
print('Number of hairs in region = ', regionpeak,
      'Total hairs in the image = ', len(peaks))
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager

imp = IJ.getImage()
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists

roi = OvalRoi(75, 75, 50, 50)
# define and add ROI
imp.setRoi(roi)  # make active on image
rm.addRoi(roi)  # add
rm.select(0)  # select the zeroth ROI and rename it
rm.runCommand("Rename", "roi")
Exemplo n.º 27
0
for i in range(len(x)):
	x[i] = float(x[i]) * dimensions
y = coordinates[2];
for i in range(len(y)):
	y[i] = float(y[i]) * dimensions
m = coordinates[3];
for i in range(len(m)):
	m[i] = float(m[i])

#3. 
rm = RoiManager.getInstance()
#prompt Set Measurements GUI
IJ.run("Set Measurements...")
if (rm==None):
	rm = RoiManager()

for i in range(len(t)):
	if x[i] != 0:
		#imp.setPosition switches to GFP channel and sets frame for each ROI
		imp.setPosition(2, 1, int(t[i])+1)
		#adds an oval ROI centered around coordinates
		rm.addRoi(ij.gui.OvalRoi(x[i]-5, y[i]-5, 10, 10))
		
#measures requested data on all ROIs
rm.runCommand(imp,"Measure")

#4. Saving measured data to desktop
IJ.selectWindow("Results")
IJ.saveAs("Text", filename+"_results")
IJ.run("Close")
Exemplo n.º 28
0
def process(subFolder, outputDirectory, filename):

    imp = IJ.openImage(inputDirectory + subFolder + '/' + filename)
    imp.show()
    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)
    dup = imp.duplicate()
    dup_title = dup.getTitle()
    ic.convertToGray8()
    imp.updateAndDraw()
    IJ.run("Threshold...")

    IJ.setThreshold(218, 245)

    IJ.run(imp, "Convert to Mask", "")

    rm = RoiManager()
    imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE)
    boundroi = ThresholdToSelection.run(imp)
    rm.addRoi(boundroi)

    imp.changes = False
    imp.close()

    images = [None] * 5
    intensities = [None] * 5
    blobsarea = [None] * 5
    blobsnuclei = [None] * 5
    cells = [None] * 5
    bigareas = [None] * 5

    IJ.run(dup, "Colour Deconvolution", "vectors=[H DAB]")

    images[0] = getImage(dup_title + "-(Colour_1)")
    images[1] = getImage(dup_title + "-(Colour_2)")
    images[2] = getImage(dup_title + "-(Colour_3)")

    images[2].close()

    for chan in channels:
        v, x = chan
        imp = images[x]
        imp.show()
        for roi in rm.getRoiManager().getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA)
            intensities[x] = stats.mean
            bigareas[x] = stats.area

        rm.runCommand(imp, "Show None")

    rm.close()
    # Opens the ch00 image and sets default properties

    imp = images[0].duplicate()
    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

    imp.show()
    setTempCurrentImage(imp)
    ic = ImageConverter(imp)
    imp.updateAndDraw()
    IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur))
    imp.updateAndDraw()

    imp.show()
    IJ.run("Threshold...")
    IJ.setThreshold(30, lowerBounds[0])
    if displayImages:
        imp.show()
        WaitForUserDialog(
            "Title", "Adjust threshold for nuclei. Current region is: " +
            region).show()
    IJ.run(imp, "Convert to Mask", "")

    # 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()
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA,
                          table, 5, 9999999999999999, 0.05, 1.0)

    pa.setHideOutputImage(True)
    imp = IJ.getImage()
    # imp.getProcessor().invert()
    pa.analyze(imp)

    imp.changes = False
    imp.close()

    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
    maxThresholds = []
    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"
        )

        imp.show()

        setTempCurrentImage(imp)

        ic = ImageConverter(imp)
        ic.convertToGray8()
        imp.updateAndDraw()

        rm.runCommand(imp, "Show None")
        rm.runCommand(imp, "Show All")
        rm.runCommand(imp, "Show None")

        imp.show()
        IJ.selectWindow(imp.getTitle())

        IJ.run("Threshold...")
        IJ.setThreshold(20, lowerBounds[x])

        if displayImages:

            WaitForUserDialog(
                "Title", "Adjust threshold for " + v +
                ". Current region is: " + region).show()
            ip = imp.getProcessor()
            maxThresholds.append(ip.getMaxThreshold())

        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.getRoiManager().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()
        imp.updateAndDraw()
        setTempCurrentImage(imp)
        roim = RoiManager()
        pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                              Measurements.AREA, table, 15, 9999999999999999,
                              0.2, 1.0)
        pa.analyze(imp)

        blobs = []
        cell = []
        for roi in roim.getRoiManager().getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.AREA)
            blobs.append(stats.area)
            if stats.area > tooSmallThresholdDAB and stats.area < tooBigThresholdDAB:
                cell.append(stats.area)

        blobsarea[x] = sum(blobs)
        blobsnuclei[x] = len(blobs)

        cells[x] = len(cell)
        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 = [
        'Directory', 'Image', 'size-average',
        'too-big-(>' + str(tooBigThreshold) + ')',
        'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei',
        'all-negative'
    ]

    for row in info:
        if row['Animal ID'] == filename.replace('s', '-').replace(
                'p', '-').split('-')[0]:
            for key, value in row.items():
                fieldnames.insert(0, key)
                summary[key] = value

    # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei)

    summary["tissue-area"] = bigareas[0]
    fieldnames.append("tissue-area")

    for chan in channels:
        v, x = chan
        summary[v + "-HEMO-cells"] = 0
        fieldnames.append(v + "-HEMO-cells")

        summary[v + "-intensity"] = intensities[x]
        fieldnames.append(v + "-intensity")

        summary[v + "-area"] = blobsarea[x]
        fieldnames.append(v + "-area")

        summary[v + "-area/tissue-area"] = blobsarea[x] / bigareas[0]
        fieldnames.append(v + "-area/tissue-area")

        summary[v + "-particles"] = blobsnuclei[x]
        fieldnames.append(v + "-particles")

        summary[v + "-cells"] = cells[x]
        fieldnames.append(v + "-cells")

        summary[v + "-particles/tissue-area"] = blobsnuclei[x] / bigareas[0]
        fieldnames.append(v + "-particles/tissue-area")

        fieldnames.append(v + "-HEMO-Cells/tissue-area")

    # 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):

        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]:
                    summary[chan[0] + '-HEMO-cells'] += 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

    for chan in channels:
        v, x = chan
        summary[v + "-cells/tissue-area"] = summary[v + "-cells"] / bigareas[0]

    if float(summary['#nuclei']) > 0:
        summary['size-average'] = round(areaCounter / summary['#nuclei'], 2)

    if displayImages:

        fieldnames = ["Directory", "Image"]

        for chan in channels:
            v, x = chan
            summary[v + "-threshold"] = maxThresholds[x]
            fieldnames.append(v + "-threshold")
            allMaxThresholds[v + "-" + region].append(maxThresholds[x])

    # 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(outputName, 'a') as csvfile:

        writer = csv.DictWriter(csvfile,
                                fieldnames=fieldnames,
                                extrasaction='ignore',
                                lineterminator='\n')
        if os.path.getsize(outputName) < 1:
            writer.writeheader()
        writer.writerow(summary)
  features = sift.run() # instances of mpicbg.imagefeatures.Feature
  return features

features1 = extractFeatures(imp1.getProcessor(), p)
features2 = extractFeatures(imp2.getProcessor(), p)

# Feature locations as points in an ROI
# Store feature locations in the Roi manager for visualization later
roi_manager = RoiManager()

roi1 = PointRoi()
roi1.setName("features for cut1")
for f in features1:
  roi1.addPoint(f.location[0], f.location[1])

roi_manager.addRoi(roi1)

roi2 = PointRoi()
roi2.setName("features for cut2")
for f in features2:
  roi2.addPoint(f.location[0], f.location[1])

roi_manager.addRoi(roi2)

# Find matches between the two sets of features
# (only by whether the properties of the features themselves match,
#  not by their spatial location.)
rod = 0.9 # ratio of distances in feature similarity space (closest/next closest match)
pointmatches = FloatArray2DSIFT.createMatches(features1, features2, rod)

# Some matches are spatially incoherent: filter matches with RANSAC
Exemplo n.º 30
0
def process(subFolder, outputDirectory, filename):

    roim = RoiManager()
    roim.close()

    imp = IJ.openImage(inputDirectory + subFolder + '/' +
                       filename.replace("_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()
    imp.updateAndDraw()
    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()

    imp.changes = False
    imp.close()

    x_amount = 10
    y_amount = 10

    l = 0
    j = 0
    while l < x_amount:
        k = 0
        while k < y_amount:
            copy = IJ.openImage(inputDirectory + subFolder + '/' +
                                filename.replace("_ch00.tif", ".tif"))
            Xposition = (int)(round((imp.width / x_amount) * l))
            Yposition = (int)(round((imp.width / y_amount) * k))
            Width = (int)(round(imp.width / x_amount))
            Height = (int)(round(imp.height / y_amount))
            roi = Roi(Xposition, Yposition, Width, Height)
            copy.setRoi(roi)
            IJ.run(copy, "Crop", "")
            FileSaver(copy).saveAsTiff(outputDirectory + '/' + filename +
                                       "_crop_" + str(j) + ".tif")
            copy.changes = False
            copy.close()

            for chan in channels:
                v, x = chan
                image = IJ.openImage(inputDirectory + subFolder + '/' +
                                     filename.replace("ch00.tif", "ch0" +
                                                      str(x) + ".tif"))
                roi = Roi(Xposition, Yposition, Width, Height)
                image.setRoi(roi)
                IJ.run(image, "Crop", "")
                FileSaver(image).saveAsTiff(outputDirectory + '/' + filename +
                                            "_crop_" + str(j) + "_ch0" +
                                            str(x) + ".tif")
                image.changes = False
                image.close()

            roim.close()

            k = k + 1
            j = j + 1

        l = l + 1

    imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE)
    boundroi = ThresholdToSelection.run(imp)

    rm = RoiManager()
    rm.addRoi(boundroi)

    images = [None] * 5
    intensities = [None] * 5
    blobsarea = [None] * 5
    blobsnuclei = [None] * 5
    areas = [None] * 5

    for chan in channels:
        v, x = chan
        images[x] = IJ.openImage(inputDirectory + subFolder + '/' +
                                 filename.replace("ch00.tif", "ch0" + str(x) +
                                                  ".tif"))
        imp = images[x]
        for roi in rm.getRoiManager().getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA)
            intensities[x] = stats.mean
            areas[x] = stats.area

    rm.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

    # Creates the fieldnames variable needed to create the csv file at the end.

    fieldnames = ['Name', 'Directory', 'Image']

    # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei)

    summary["organoid-area"] = areas[x]
    fieldnames.append("organoid-area")

    for chan in channels:
        v, x = chan

        summary[v + "-intensity"] = intensities[x]
        fieldnames.append(v + "-intensity")

    # 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 main():
    #print (sys.version_info) # debug
    #print(sys.path) # debug
    data_root = r'C:\Users\dougk\Desktop\test'
    # debug
    output_root = r'C:\Users\dougk\Desktop\test'
    #debug
    #default_directory = r'C:\\Users\\Doug\\Desktop\\test';
    #data_root, output_root = file_location_chooser(default_directory);
    if (data_root is None) or (output_root is None):
        raise IOError("File location dialogs cancelled!")
    timestamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H.%M.%S")
    output_path = os.path.join(output_root, (timestamp + " output"))
    for file_path in filterByFileType(os.listdir(data_root), '.tif'):
        subfolder_name = os.path.splitext(file_path)[0]
        output_subfolder = os.path.join(output_path, subfolder_name)
        print(output_subfolder)
        os.makedirs(output_subfolder)
        imps = bf.openImagePlus(os.path.join(data_root, file_path))
        imp = imps[0]
        imp.show()
        h = imp.height
        w = imp.width
        slices = imp.getNSlices()
        channels = imp.getNChannels()
        frames = imp.getNFrames()

        # rotation step - since using multiples of 90, TransformJ.Turn is more efficient
        IJ.run("Enhance Contrast", "saturated=0.35")
        angleZ = 1
        while ((angleZ % 90) > 0):
            gd = GenericDialog("Rotate?")
            gd.addMessage(
                "Define rotation angle - increments of 90. Apical at top")
            gd.addNumericField("Rotation angle", 0, 0)
            gd.showDialog()
            angleZ = int(gd.getNextNumber())

        if (angleZ > 1):
            IJ.run("TransformJ Turn",
                   "z-angle=" + str(angleZ) + " y-angle=0 x-angle=0")
            imp.close()
            imp = WindowManager.getCurrentImage()
            imp.setTitle(file_path)

        # trim time series
        IJ.run("Enhance Contrast", "saturated=0.35")
        imp.setDisplayMode(IJ.COLOR)
        WaitForUserDialog(
            "Scroll to the first frame of the period of interest and click OK"
        ).show()
        start_frame = imp.getT()
        WaitForUserDialog(
            "Scroll to the last frame of the period of interest and click OK"
        ).show()
        end_frame = imp.getT()
        trim_imp = Duplicator().run(imp, 1, channels, 1, slices, start_frame,
                                    end_frame)
        imp.close()
        trim_imp.show()
        dup_imp = Duplicator().run(trim_imp)

        # create images to process and find bounds for
        dup_imps = ChannelSplitter().split(dup_imp)
        myo_imp = dup_imps[1]
        mem_imp = dup_imps[0]
        FileSaver(myo_imp).saveAsTiffStack(
            os.path.join(output_subfolder, "myosin_channel.tif"))
        FileSaver(mem_imp).saveAsTiffStack(
            os.path.join(output_subfolder, "membrane_channel.tif"))

        # set basal bounds
        myo_imp.show()
        ImageConverter(myo_imp).convertToGray8()
        frames = myo_imp.getNFrames()
        gb = GaussianBlur()
        for fridx in range(0, frames):
            myo_imp.setSliceWithoutUpdate(fridx + 1)
            ip = myo_imp.getProcessor()
            gb.blurGaussian(ip, 5.0, 1.0, 0.02)
            # assymmetrical Gaussian
        IJ.run(myo_imp, "Convert to Mask",
               "method=Otsu background=Dark calculate")
        IJ.run("Despeckle", "stack")
        title = myo_imp.getTitle()

        # assume that first frame is good quality image...
        basal_edges = find_basal_edges(myo_imp)
        #myo_imp.hide()
        mem_imp.hide()

        # draw some edges for checking
        roim = RoiManager()
        xs = [x for x in range(1,
                               trim_imp.getWidth() + 1)]
        trim_imp.show()
        for fridx in range(0, myo_imp.getNFrames()):
            trim_imp.setPosition(2, 1, fridx + 1)
            IJ.run("Enhance Contrast", "saturated=0.35")

            roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE)
            trim_imp.setRoi(roi)
            roim.addRoi(roi)
Exemplo n.º 32
0
def adjustRoiAndMeasure(imp, frameNumber, dstDir):

    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()

    nROIs = rm.getCount()
    indexlist = range(nROIs)

    if nROIs > 2:
        for roi in indexlist:

            indexlist_copy = list(indexlist)
            del indexlist_copy[roi]
            rm.setSelectedIndexes(indexlist_copy)
            rm.runCommand(imp, "Combine")
            IJ.run(imp, "Make Inverse", "")
            rm.addRoi(imp.getRoi())
            new_nROI = rm.getCount()
            rm.setSelectedIndexes([roi, new_nROI - 1])
            rm.runCommand(imp, "AND")
            if imp.getRoi():
                rm.addRoi(imp.getRoi())
                rm.setSelectedIndexes([new_nROI])
                rm.runCommand("Rename", "Cell" + str(roi))
            else:
                rm.setSelectedIndexes([roi])
                rm.addRoi(imp.getRoi())
            rm.setSelectedIndexes([new_nROI - 1])
            rm.runCommand(imp, "Delete")
    elif nROIs == 2:
        for roi in indexlist:
            indexlist_copy = list(indexlist)
            del indexlist_copy[roi]

            rm.setSelectedIndexes(indexlist_copy)
            IJ.run(imp, "Make Inverse", "")
            rm.addRoi(imp.getRoi())
            new_nROI = rm.getCount()
            rm.setSelectedIndexes([roi, new_nROI - 1])
            rm.runCommand(imp, "AND")
            rm.addRoi(imp.getRoi())
            rm.setSelectedIndexes([new_nROI])
            rm.runCommand("Rename", "Cell" + str(roi))
            rm.setSelectedIndexes([new_nROI - 1])
            rm.runCommand(imp, "Delete")

    elif nROIs == 1:
        nROIs = 0
        new_nROI = 1
        rm.setSelectedIndexes([new_nROI])
        rm.runCommand("Rename", "Cell0")

    else:
        return

    adjustedROIs = range(nROIs, new_nROI, 1)
    rm.setSelectedIndexes(adjustedROIs)
    measureChannels(adjustedROIs, imp, frameNumber)
    rm.setSelectedIndexes(adjustedROIs)
    rm.runCommand("Save selected",
                  dstDir + "\\Frame " + str(frameNumber + 1) + " roi set.zip")
    rm.runCommand(imp, "Deselect")
    rm.runCommand(imp, "Delete")
Exemplo n.º 33
0
#imp.show()

roi_manager = RoiManager()

for gene in gene_list:
    roi_manager.reset()
    with open(csv_path) as csvfile:
        reader = csv.DictReader(csvfile)
        for n, row in enumerate(reader):
            #		print(row['cell_n'])
            poly_name = row['gene_name']
            #			poly_name = ast.literal_eval(poly_name)
            if gene == poly_name:
                print(gene, poly_name)
                rr = row['row_pixels']
                cc = row['col_pixels']
                rs = ast.literal_eval(rr)
                cs = ast.literal_eval(cc)
                proi = PolygonRoi(cs, rs, len(rs), Roi.POLYGON)
                roi_manager.addRoi(proi)
        roi_manager.runCommand("Deselect")
        roi_save_path = os.path.join(dir.getDirectory(), gene + "_RoiSet.zip")
        print(roi_save_path)

        if not os.path.exists(roi_save_path):
            with zipfile.ZipFile(roi_save_path, "w") as file:
                pass
            file.close()

        roi_manager.runCommand("Save", roi_save_path)
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager

imp = IJ.getImage()  
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists 
 
roi = OvalRoi(75, 75, 50, 50); # define and add ROI
imp.setRoi(roi)  # make active on image
rm.addRoi(roi)  # add
rm.select(0) # select the zeroth ROI and rename it
rm.runCommand("Rename", "roi");
for i in range(len(x)):
    x[i] = float(x[i]) * dimensions
y = coordinates[2]
for i in range(len(y)):
    y[i] = float(y[i]) * dimensions
m = coordinates[3]
for i in range(len(m)):
    m[i] = float(m[i])

#3.
rm = RoiManager.getInstance()
if (rm == None):
    rm = RoiManager()

#Goes through all spots
for i in range(len(t)):
    #Ignores lines of zeros between tracks
    if x[i] != 0:
        #Goes through all spots again
        for j in range(len(t)):
            #Ignores lines of zeros between tracks
            if x[j] != 0:
                #Asks if there is another spot with the same time that isn't identical and hasn't been recorded yet
                if (t[i] == t[j] and i < j):
                    #Sets position of .tif
                    imp.setPosition(2, 1, int(t[i]) + 1)
                    #Adds line ROI between the two spots
                    rm.addRoi(ij.gui.Line(x[i], y[i], x[j], y[j]))

rm.runCommand(imp, "Multi Plot")
imp.close()
Exemplo n.º 36
0
def procOneImage(pathpre, wnumber, endings):
  """ Analyzes a single image set (Dapi, VSVG, PM images)
  pathpre: fullpath prefix, down till "endings". 
  endings: a dictionary with signiture for three different channels. 
  wnumber: a number in string, indicating the spot ID.
  Returns three results tables. 
  """
  imp = IJ.openImage(pathpre + endings['dapi'] + '.tif')
  impVSVG = IJ.openImage(pathpre + endings['vsvg'] + '.tif')
  impPM = IJ.openImage(pathpre + endings['pm'] + '.tif')
  imp2 = imp.duplicate()

  rtallcellPM = ResultsTable()
  rtjnucVSVG = ResultsTable()
  rtallcellVSVG = ResultsTable()

  backVSVG = backgroundSubtraction(impVSVG)
  backPM = backgroundSubtraction(impPM)
  impfilteredNuc = nucleusSegmentation(imp2)

  intmax = impfilteredNuc.getProcessor().getMax()
  if intmax == 0:
    return rtallcellPM, rtjnucVSVG, rtallcellVSVG

  impfilteredNuc.getProcessor().setThreshold(1, intmax, ImageProcessor.NO_LUT_UPDATE)
  nucroi = ThresholdToSelection().convert(impfilteredNuc.getProcessor())
  nucroiA = ShapeRoi(nucroi).getRois()
#print nucroiA
  allcellA = [roiEnlarger(r) for r in nucroiA]
  jnucroiA = [roiRingGenerator(r) for r in nucroiA]
#print allcellA
  print 'Detected Cells: ', len(jnucroiA)  
  if len(jnucroiA) <2:
      print "measurement omitted, as there is only on nucleus detected"
      return  rtallcellPM, rtjnucVSVG, rtallcellVSVG
  if (GUIMODE):
    rm = RoiManager()
    for r in jnucroiA:
      rm.addRoi(r)
    rm.show()
    impfilteredNuc.show()
  

  measOpt = PA.AREA + PA.MEAN + PA.CENTROID + PA.STD_DEV + PA.SHAPE_DESCRIPTORS + PA.INTEGRATED_DENSITY + PA.MIN_MAX +\
    PA.SKEWNESS + PA.KURTOSIS + PA.MEDIAN + PA.MODE

## All Cell Plasma Membrane intensity
  measureROIs(impPM, measOpt, rtallcellPM, allcellA, backPM, True)
  meanInt_Cell = rtallcellPM.getColumn(rtallcellPM.getColumnIndex('Mean'))
  print "Results Table rownumber:", len(meanInt_Cell)
# JuxtaNuclear VSVG intensity 
  measureROIs(impVSVG, measOpt, rtjnucVSVG, jnucroiA, backVSVG, False)    
  meanInt_jnuc = rtjnucVSVG.getColumn(rtjnucVSVG.getColumnIndex('Mean'))

# AllCell VSVG intensity 
  measureROIs(impVSVG, measOpt, rtallcellVSVG, allcellA, backVSVG, True)    
  meanInt_vsvgall = rtallcellVSVG.getColumn(rtallcellVSVG.getColumnIndex('Mean'))
  
#Calculation of Transport Ratio JuxtaNuclear VSVG intensity / All Cell Plasma Membrane intensity results will be appended to PM results table.
  for i in range(len(meanInt_Cell)):
    if meanInt_Cell[i] != 0.0:
      transportR = meanInt_jnuc[i] / meanInt_Cell[i]
      transportRall = meanInt_vsvgall[i] / meanInt_Cell[i]
    else:
      transportR = float('inf')
      transportRall = float('inf')
    rtjnucVSVG.setValue('TransportRatio', i, transportR)
    rtallcellVSVG.setValue('TransportRatio', i, transportRall)
    rtjnucVSVG.setValue('WellNumber', i, int(wnumber)) 
    rtallcellVSVG.setValue('WellNumber', i, int(wnumber))
    rtallcellPM.setValue('WellNumber', i, int(wnumber)) 
  return rtallcellPM, rtjnucVSVG, rtallcellVSVG