def ER_points(all_x, all_y, overlay, ER_measurements):
    imp = IJ.getImage()
    overlay = Overlay()
    overlay = imp.getOverlay()
    ## gets points added to overlay, and extracts a list of x & y values. list length must be three ###
    try:
        roi_points = overlay.toArray()
    except AttributeError as error:
        nbgd = NonBlockingGenericDialog("Select three Roi's")
        nbgd.hideCancelButton()
        nbgd.showDialog()
        overlay = imp.getOverlay()
        roi_points = overlay.toArray()
        pass

    for i in range(overlay.size()):
        roi = overlay.get(i)
        p = roi_points[i].getPolygon()
        all_x.append(p.xpoints[0])
        all_y.append(p.ypoints[0])
    while len(all_x) != 3:
        if len(all_x) < 3:
            nbgd = NonBlockingGenericDialog("Must Select three Roi's")
            nbgd.setCancelLabel("Roi Reset")
            nbgd.showDialog()
            if nbgd.wasCanceled():
                IJ.run("Remove Overlay", "")
            ER_points(all_x, all_y, overlay, ER_measurements)
        if len(all_x) > 3:
            all_x.pop(0)
            all_y.pop(0)
    overlay.clear()
Пример #2
0
def createLabelColorBar():

    imp7 = ImagePlus("labelColorBar", ShortProcessor(180, 20))
    ip7 = imp7.getProcessor()
    pix = ip7.getPixels()
    n_pixels = len(pix)
    # catch width
    w = imp7.getWidth()
    # create a ramp gradient from left to right
    for i in range(len(pix)):
        pix[i] = int((i % w) / 18) + 1

    # adjust min and max
    ip7.setMinAndMax(0, 255)
    font = Font("SansSerif", Font.PLAIN, 12)
    overlay = Overlay()
    for i in range(len(pix)):

        roi = TextRoi(i * 18 + 2, 2, str(i + 1), font)
        roi.setStrokeColor(Color.black)
        overlay.add(roi)
        imp7.setOverlay(overlay)

    imp7.show()
    IJ.run("glasbey_on_dark")
    imp7 = imp7.flatten()

    return imp7
Пример #3
0
def overlay_corners(corners, L):
    ov = Overlay()
    for [x, y] in corners:
        rect = Roi(x, y, L, L)
        rect.setStrokeColor(Color.RED)
        rect.setLineWidth(40)
        ov.add(rect)
    return ov
Пример #4
0
 def restoreRoi(self):
     overlay = Overlay()
     rois = [
         r for ind, r in enumerate(self.newRois)
         if ind != self.outlineRoiInd
     ]
     for roi in rois:
         overlay.add(roi)
     self.impCrop.setOverlay(overlay)
Пример #5
0
 def drawMinima(self):
     IJ.run("Remove Overlay", "")
     self.calculateSubtreeMinima()
     overlay = Overlay()
     for child in self.children:
         for spot in child.minima:
             roi = OvalRoi(spot.x - spot.radius, spot.y - spot.radius,
                           2 * spot.radius, 2 * spot.radius)
             overlay.add(roi)
     IJ.getImage().setOverlay(overlay)
Пример #6
0
def getOverlay(imp):
    """ Returns an image overlay cleansed of spot ROIs from previous runs """
    overlay = imp.getOverlay()
    if overlay is None:
        return Overlay()
    for i in range(0, overlay.size() - 1):
        roi_name = overlay.get(i).getName()
        if roi_name is not None and "Spots" in roi_name:
            overlay.remove(i)
    return overlay
Пример #7
0
    def roiprocess_ov(imp, filename):
        """
        !!! This is for testing purposes only. It is currently not used !!!
        """
        ov = Overlay()
        rt = ov.measure(imp)
        # log.info('Size ResultTable: ' + str(rt.size()))
        # print('Size ResultTable: ', rt.size())

        return None
def analyse():
	rt = ResultsTable()
	ol = Overlay()

	masks = [getMask(imp, c) for c in range(1, C+1)]
	DAPImask = masks[0]
	IJ.run(DAPImask, "Create Selection", "")
	DAPIRoi = DAPImask.getRoi()
	rois = ShapeRoi(DAPIRoi).getRois()
	for c,mask in enumerate(masks):
		if c==0:
def drawMinima(minima):
	rt = ResultsTable.getResultsTable()
	X = rt.getColumn(ResultsTable.X_CENTROID)
	Y = rt.getColumn(ResultsTable.Y_CENTROID)
	D = rt.getColumn(ResultsTable.FERET)	
	overlay = Overlay()
	for minimum in minima:
		index = minima[minimum]
	 	r = float(D[index]) / 2
		roi = OvalRoi(float(X[index])-r, float(Y[index])-r, float(D[index]), float(D[index]))	
		overlay.add(roi)
	IJ.getImage().setOverlay(overlay)
Пример #10
0
def convert_SNTpaths_to_roi(SNTpaths):
	'''
	Converts a list of SNT_paths to an Array of imageJ1 rois.
	'''
	roi_list = []
	for SNTpath in SNTpaths:
		as_tree = Tree()
		as_tree.add(SNTpath)
		converter = RoiConverter(as_tree)
		overlay = Overlay()
		converter.convertPaths(overlay)
		roi = overlay.toArray()[0]
		roi_list.append(roi)
	return roi_list
Пример #11
0
def create_mask_selection(movie,
                          sigma=0,
                          thresh_method='Huang',
                          threshold=None):
    ''' 
    If threshold is *None* use selected AutoThreshold, otherwise
    use fixed *threshold* '''

    C = movie.getC()
    S = movie.getSlice()
    NFrames = movie.getNFrames()

    maxThresh = 2**movie.getBitDepth()

    tts = ThresholdToSelection()

    ov = Overlay()  # to save the rois
    for frame in range(1, NFrames + 1):

        movie.setPosition(C, S, frame)
        ip = movie.getProcessor().duplicate()
        # imp = ImagePlus('Blurred', ip)
        if sigma != 0:
            ip.blurGaussian(sigma)

        # manual thresholding
        if threshold:
            ip.setThreshold(threshold, maxThresh, 0)  # no LUT update

        # automatic thresholding
        else:
            ip.setAutoThreshold(thresh_method, True, False)

        tts.setup("", movie)
        shape_roi = tts.convert(ip)

        # only one connected roi present
        if type(shape_roi) == ij.gui.PolygonRoi:
            mask_roi = shape_roi

        else:
            # for disconnected regions.. take the shape_roi as is
            # rois = shape_roi.getRois() # splits into sub rois
            # mask_roi = get_largest_roi(rois) # sort out smaller Rois
            mask_roi = shape_roi

        mask_roi.setPosition(frame)
        ov.add(mask_roi)

    return ov
Пример #12
0
def drawLines(imp, points=None):
    if points and (len(points) % 2 == 0):
        # points is numeric list of even length
        pRoi = PointRoi(points[0::2], points[1::2], len(points) / 2)
        pRoi.setShowLabels(True)
        pRoi.setSize(3)
        imp.setRoi(pRoi)
    roi = imp.getRoi()
    pp = roi.getFloatPolygon()
    # print "Added", pp.npoints
    if pp.npoints <= 1:
        # don't draw if only one point
        return
    xys = []
    for i in xrange(pp.npoints):
        xys.append([pp.xpoints[i], pp.ypoints[i]])
    ol = Overlay()
    x0 = xys[0][0]
    y0 = xys[0][1]
    cal = imp.getCalibration()
    for i in xrange(1, pp.npoints):
        xi = xys[i][0]
        yi = xys[i][1]
        # prepare text label
        d = math.sqrt((xi - x0)**2 + (yi - y0)**2) * cal.pixelWidth
        dText = String.format("%.2f ", d) + cal.getUnits()
        textOffset = 30
        xt = xi
        yt = yi
        #        if xi > x0:
        #            xt += textOffset
        if xi < x0:
            xt -= textOffset


#        if yi > y0:
#            yt += textOffset
        if yi < y0:
            yt -= textOffset
        dTextRoi = TextRoi(xt, yt, dText)
        ol.add(dTextRoi)

        lineRoi = Line(x0, y0, xi, yi)
        lineRoi.setStrokeWidth(1)
        lineRoi.setStrokeColor(Color(255, 255, 0))
        ol.add(lineRoi)
    imp.setOverlay(ol)
    imp.updateAndDraw()
Пример #13
0
def save_roi_set(imp=IJ.getImage()):

    img_dir, name = get_file_info()
    roi_dir = make_roi_dir(img_dir, name)
    roi_path = make_roi_path(roi_dir, name)

    Roi.setColor(Color.blue)
    rm = RoiManager().getInstance()
    rm.deselect()
    rm.runCommand("Save", roi_path)

    ol = imp.getOverlay()
    if ol is None:
        ol = Overlay()
    for roi in rm.getRoisAsArray():
        ol.add(roi)
        imp.setOverlay(ol)

    rm.runCommand("delete")
    ol.setStrokeColor(Color.blue)
    Roi.setColor(Color.yellow)
Пример #14
0
    def createMIP(self):
        print "starting createMIP"
        for a in self.itemSelected:
            ImStack = None
            for filename in self.dict1.get(a):
                self.savfileName = a
                if not filename.endswith(self.fileExt):
                    continue
                path = self.sourceDir + filename
                # Upon finding the first image, initialize the VirtualStack
                if ImStack is None:
                    imp = IJ.openImage(path)
                    ImStack = VirtualStack(imp.width, imp.height, None,
                                           self.sourceDir)
                # Add a slice, relative to the sourceDIr
                ImStack.addSlice(filename)
            #adding text overlay to output images so we can differentiate them. Overlay is non destructive - does not affect pixel values of image, and can be selected and deleted
            prefix_overlay = Overlay()
            font = Font("SansSerif", Font.PLAIN, 10)
            roi = TextRoi(0, 0, a)
            roi.setStrokeColor(Color(1.00, 1.00, 1.00))
            prefix_overlay.add(roi)
            #
            OnscreenImage = ImagePlus(self.sourceDir, ImStack)
            OnscreenImage.setOverlay(prefix_overlay)
            OnscreenImage.show()

            print "Generating MIP, waiting..."
            self.outimp = self.maxZprojection(
                OnscreenImage)  #generate max projection
            self.outimp.setOverlay(prefix_overlay)
            self.outimp.show()
            print "Max projection generated"
            if self.saveState == "Y":
                self.saveMIP()
            print "Finished!"
Пример #15
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: Reject files that contain the given string (default: wild characters).
    :param recursive: Process directories recursively (default: False).
    '''
    # Converting a File object to a string.
    if isinstance(pathImage, File):
        pathImage = pathImage.getAbsolutePath()

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_typeImage:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_typeImage, (list, tuple)):
                for file_type_ in file_typeImage:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_typeImage, string):
                if string.endswith(file_typeImage):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    def dog_detection(overlay,img, imp, cal):

                 # Create a variable of the correct type (UnsignedByteType) for the value-extended view
				 zero = img.randomAccess().get().createVariable()
				
				 # Run the difference of Gaussian
				 cell = 8.0 # microns in diameter
				 min_peak = 2.0 # min intensity for a peak to be considered
				 dog = DogDetection(Views.extendValue(img, zero), img,
				                   [cal.pixelWidth, cal.pixelHeight,cal.pixelDepth],
				                   cell / 2, cell,
				                   DogDetection.ExtremaType.MINIMA, 
				                   min_peak, False,
				                   DoubleType())
				
				 peaks = dog.getPeaks()
				 roi = OvalRoi(0, 0, cell/cal.pixelWidth, cell/cal.pixelHeight)  
				 print ('Number of cells = ', len(peaks))
			 	 p = zeros(img.numDimensions(), 'i')  
			 	
				 boundRect = imp.getRoi()
				 for peak in peaks:  
				    # Read peak coordinates into an array of integers  XYZ location of spots
				    peak.localize(p)  
				    print(p)
				    if(boundRect is not None and boundRect.contains(p[0], p[1])):
						    oval = OvalRoi(p[0], p[1],cell/cal.pixelWidth,  cell/cal.pixelHeight)
						    oval.setColor(Color.RED)
						    overlay.add(oval) 

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filterImage:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filterImage, (list, tuple)):
                for name_filter_ in name_filterImage:
                    if name_filter_ in string:
                        # Exit the function with True.
                        
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filterImage, string):
                if name_filterImage in string:
                    return True
                else:
                    return False
            return False
        else:
        # Accept all files if name_filter is None.
            return True

   

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathImage)
    path = os.path.expandvars(pathImage)
    # If we don't want a recursive search, we can use os.listdir().
    if not recursive:
        for file_name in os.listdir(pathImage):
            full_path = os.path.join(pathImage, file_name)
            if os.path.isfile(full_path):
                if check_type(file_name):
                    if check_filter(file_name):
                        path_to_Image.append(full_path)
    # For a recursive search os.walk() is used.
    else:
        # os.walk() is iterable.
        # Each iteration of the for loop processes a different directory.
        # the first return value represents the current directory.
        # The second return value is a list of included directories.
        # The third return value is a list of included files.
        for directory, dir_names, file_names in os.walk(pathImage):
            # We are only interested in files.
            for file_name in file_names:
                # The list contains only the file names.
                # The full path needs to be reconstructed.
                full_path = os.path.join(directory, file_name)
                # Both checks are performed to filter the files.
                if check_type(file_name):
                    if check_filter(file_name) is False:
                        # Add the file to the list of images to open.
                        path_to_Image.append([full_path, os.path.basename(os.path.splitext(full_path)[0])])
    # Create the list that will be returned by this function.
    Images = []
    Rois = []
    for img_path, file_name in path_to_Image:
        # IJ.openImage() returns an ImagePlus object or None.
        imp = IJ.openImage(img_path)
        imp.show()
        print(img_path)
        if check_filter(file_name):
         continue;
        else: 
         print(file_name  ,  pathRoi)
        RoiName = str(pathRoi) + '/'+ file_name + '_rois' + '.zip'
        
        if os.path.exists(RoiName):
		         Roi = IJ.open(RoiName)
		         imp = IJ.getImage()
		         cal= imp.getCalibration()# in microns
		         img = IJF.wrap(imp)
		         print('Image Dimensions', img.dimensions, 'Calibration', cal)
		         print(Roi)
		         # An object equals True and None equals False.
		         rm = RoiManager.getInstance()
		         if (rm==None):
		            rm = RoiManager()
		         try:   
		           rm.runCommand('Delete')   
		         except:
		           pass  
		         rm.runCommand("Open", RoiName)
		         rois = rm.getRoisAsArray()
		         overlay = Overlay()
				 for (i in range(0,len(rois))):
					overlay.add(rois[i])
def main(imp,options):
	from ij.plugin import ChannelSplitter
	from ij.gui import Roi,PointRoi, PolygonRoi, Overlay, Line
	from java.awt import Color
	from ij import WindowManager
	from ij.measure import ResultsTable
	from ij.text import TextWindow
	active_z=imp.getZ()
	imps = ChannelSplitter.split(imp)
	imp.setZ(active_z)
	roi_int = imp.getRoi()


	comp_imp=Zproj(imps[options["comp_ch"]],
		"SUM",
		active_z,
		options["z_range"])
	comp_imp=mode_subtract(comp_imp,roi_int)

	loci_imp=Zproj(imps[options["loci_ch"]],
		"SUM",
		imp.getZ(),
		options["z_range"])
	loci_imp=mode_subtract(loci_imp,roi_int)

	#Finding the boundaries of compartment and loci
	comp_roi=thresh(sum_prj=comp_imp,thresh=options["comp_T"],roi=roi_int,method="boundary")
	print "ok"
	if (options["loci_method"]== "locus center"):
		loci_roi=thresh(sum_prj=loci_imp,
			thresh=options["loci_T"],
			roi=roi_int,
			method="point")
	elif options["loci_method"]== "locus boundary":
		loci_roi=thresh(sum_prj=loci_imp,
			thresh=options["loci_T"],
			roi=roi_int,
			method="boundary")
		
	
	if options["loci_method"]== "locus center":
		dist,xc,yc,xl,yl=get_center_edge_dist(imp,comp_roi, loci_roi)
	elif options["loci_method"]== "locus boundary":
		dist,xc,yc,xl,yl=get_closest_points(imp,comp_roi,loci_roi)


	rt_exist = WindowManager.getWindow("Loci distance to compartment")
	
	if rt_exist==None or not isinstance(rt_exist, TextWindow):
		table= ResultsTable()
	else:
		table = rt_exist.getTextPanel().getOrCreateResultsTable()
	table.incrementCounter()
	table.addValue("Label", imp.title)
	table.addValue("Distance(micron)", dist)
	
	if options['measure_feret']:
		feret_roi,loci_feret,loci_area= feret(sum_prj=loci_imp,thresh=options["loci_T"],
		roi=roi_int,pixel_size=imp.getCalibration().pixelWidth)
		table.addValue("Loci feret", loci_feret)
		table.addValue("Loci area", loci_area)
		
		
	table.show("Loci distance to compartment")

	## Adding loci overlay
	ov=imp.getOverlay()
	if ov==None:
		ov=Overlay()
	line = Line(xc,yc, xl,yl)
	line.setStrokeWidth(0.2)
	line.setStrokeColor(Color.PINK)
	ov.add(line)

	
	if options["loci_method"]== "locus center":
		ov.add(PointRoi(loci_roi["x"],loci_roi["y"]))
	elif options["loci_method"]== "locus boundary":
		ov.add(loci_roi)
	if options['measure_feret']:
		ov.add(feret_roi)
	ov.add(comp_roi)
	imp.setOverlay(ov)	
    results.addValue("stdev", stdev.getRealDouble())
    results.addValue("sum", sum.getRealDouble())
    results.addValue("comment", comment)

# Display the table
results.show("Results")

# Outline and highlight the regions
outline = ops.run("morphology.outline", binary, False)
image_imp = ImageJFunctions.wrap(image, "Overlay Render")
binary_imp = ImageJFunctions.wrap(binary, "Binary")
outline_imp = ImageJFunctions.wrap(outline, "Outline")

IJ.run(binary_imp, "Green", "")
binary_ROI = ImageRoi(0, 0, binary_imp.getProcessor())
binary_ROI.setZeroTransparent(True)
binary_ROI.setOpacity(0.25)

IJ.run(outline_imp, "Green", "")
outline_ROI = ImageRoi(0, 0, outline_imp.getProcessor())
outline_ROI.setZeroTransparent(True)
outline_ROI.setOpacity(1.00)

overlay = Overlay()
overlay.add(binary_ROI)
overlay.add(outline_ROI)

image_imp.setOverlay(overlay)
image_imp.updateAndDraw()
image_imp.show()
Пример #18
0
def run(imp, preprocessor_path, postprocessor_path, threshold_method,
        user_comment):

    output_parameters = {
        "image title": "",
        "preprocessor path": float,
        "post processor path": float,
        "thresholding op": float,
        "use ridge detection": bool,
        "high contrast": int,
        "low contrast": int,
        "line width": int,
        "minimum line length": int,
        "mitochondrial footprint": float,
        "branch length mean": float,
        "branch length median": float,
        "branch length stdevp": float,
        "summed branch lengths mean": float,
        "summed branch lengths median": float,
        "summed branch lengths stdevp": float,
        "network branches mean": float,
        "network branches median": float,
        "network branches stdevp": float
    }

    output_order = [
        "image title", "preprocessor path", "post processor path",
        "thresholding op", "use ridge detection", "high contrast",
        "low contrast", "line width", "minimum line length",
        "mitochondrial footprint", "branch length mean",
        "branch length median", "branch length stdevp",
        "summed branch lengths mean", "summed branch lengths median",
        "summed branch lengths stdevp", "network branches mean",
        "network branches median", "network branches stdevp"
    ]

    # Perform any preprocessing steps...
    status.showStatus("Preprocessing image...")
    if preprocessor_path != None:
        if preprocessor_path.exists():
            preprocessor_thread = scripts.run(preprocessor_path, True)
            preprocessor_thread.get()
            imp = WindowManager.getCurrentImage()
    else:
        pass

    # Store all of the analysis parameters in the table
    if preprocessor_path == None:
        preprocessor_str = ""
    else:
        preprocessor_str = preprocessor_path.getCanonicalPath()
    if postprocessor_path == None:
        postprocessor_str = ""
    else:
        postprocessor_str = preprocessor_path.getCanonicalPath()

    output_parameters["preprocessor path"] = preprocessor_str
    output_parameters["post processor path"] = postprocessor_str
    output_parameters["thresholding op"] = threshold_method
    output_parameters["use ridge detection"] = str(use_ridge_detection)
    output_parameters["high contrast"] = rd_max
    output_parameters["low contrast"] = rd_min
    output_parameters["line width"] = rd_width
    output_parameters["minimum line length"] = rd_length

    # Create and ImgPlus copy of the ImagePlus for thresholding with ops...
    status.showStatus("Determining threshold level...")
    imp_title = imp.getTitle()
    slices = imp.getNSlices()
    frames = imp.getNFrames()
    output_parameters["image title"] = imp_title
    imp_calibration = imp.getCalibration()
    imp_channel = Duplicator().run(imp, imp.getChannel(), imp.getChannel(), 1,
                                   slices, 1, frames)
    img = ImageJFunctions.wrap(imp_channel)

    # Determine the threshold value if not manual...
    binary_img = ops.run("threshold.%s" % threshold_method, img)
    binary = ImageJFunctions.wrap(binary_img, 'binary')
    binary.setCalibration(imp_calibration)
    binary.setDimensions(1, slices, 1)

    # Get the total_area
    if binary.getNSlices() == 1:
        area = binary.getStatistics(Measurements.AREA).area
        area_fraction = binary.getStatistics(
            Measurements.AREA_FRACTION).areaFraction
        output_parameters[
            "mitochondrial footprint"] = area * area_fraction / 100.0
    else:
        mito_footprint = 0.0
        for slice in range(binary.getNSlices()):
            binary.setSliceWithoutUpdate(slice)
            area = binary.getStatistics(Measurements.AREA).area
            area_fraction = binary.getStatistics(
                Measurements.AREA_FRACTION).areaFraction
            mito_footprint += area * area_fraction / 100.0
        output_parameters[
            "mitochondrial footprint"] = mito_footprint * imp_calibration.pixelDepth

    # Generate skeleton from masked binary ...
    # Generate ridges first if using Ridge Detection
    if use_ridge_detection and (imp.getNSlices() == 1):
        skeleton = ridge_detect(imp, rd_max, rd_min, rd_width, rd_length)
    else:
        skeleton = Duplicator().run(binary)
        IJ.run(skeleton, "Skeletonize (2D/3D)", "")

    # Analyze the skeleton...
    status.showStatus("Setting up skeleton analysis...")
    skel = AnalyzeSkeleton_()
    skel.setup("", skeleton)
    status.showStatus("Analyzing skeleton...")
    skel_result = skel.run()

    status.showStatus("Computing graph based parameters...")
    branch_lengths = []
    summed_lengths = []
    graphs = skel_result.getGraph()

    for graph in graphs:
        summed_length = 0.0
        edges = graph.getEdges()
        for edge in edges:
            length = edge.getLength()
            branch_lengths.append(length)
            summed_length += length
        summed_lengths.append(summed_length)

    output_parameters["branch length mean"] = eztables.statistical.average(
        branch_lengths)
    output_parameters["branch length median"] = eztables.statistical.median(
        branch_lengths)
    output_parameters["branch length stdevp"] = eztables.statistical.stdevp(
        branch_lengths)

    output_parameters[
        "summed branch lengths mean"] = eztables.statistical.average(
            summed_lengths)
    output_parameters[
        "summed branch lengths median"] = eztables.statistical.median(
            summed_lengths)
    output_parameters[
        "summed branch lengths stdevp"] = eztables.statistical.stdevp(
            summed_lengths)

    branches = list(skel_result.getBranches())
    output_parameters["network branches mean"] = eztables.statistical.average(
        branches)
    output_parameters["network branches median"] = eztables.statistical.median(
        branches)
    output_parameters["network branches stdevp"] = eztables.statistical.stdevp(
        branches)

    # Create/append results to a ResultsTable...
    status.showStatus("Display results...")
    if "Mito Morphology" in list(WindowManager.getNonImageTitles()):
        rt = WindowManager.getWindow(
            "Mito Morphology").getTextPanel().getOrCreateResultsTable()
    else:
        rt = ResultsTable()

    rt.incrementCounter()
    for key in output_order:
        rt.addValue(key, str(output_parameters[key]))

    # Add user comments intelligently
    if user_comment != None and user_comment != "":
        if "=" in user_comment:
            comments = user_comment.split(",")
            for comment in comments:
                rt.addValue(comment.split("=")[0], comment.split("=")[1])
        else:
            rt.addValue("Comment", user_comment)

    rt.show("Mito Morphology")

    # Create overlays on the original ImagePlus and display them if 2D...
    if imp.getNSlices() == 1:
        status.showStatus("Generate overlays...")
        IJ.run(skeleton, "Green", "")
        IJ.run(binary, "Magenta", "")

        skeleton_ROI = ImageRoi(0, 0, skeleton.getProcessor())
        skeleton_ROI.setZeroTransparent(True)
        skeleton_ROI.setOpacity(1.0)
        binary_ROI = ImageRoi(0, 0, binary.getProcessor())
        binary_ROI.setZeroTransparent(True)
        binary_ROI.setOpacity(0.25)

        overlay = Overlay()
        overlay.add(binary_ROI)
        overlay.add(skeleton_ROI)

        imp.setOverlay(overlay)
        imp.updateAndDraw()

    # Generate a 3D model if a stack
    if imp.getNSlices() > 1:

        univ = Image3DUniverse()
        univ.show()

        pixelWidth = imp_calibration.pixelWidth
        pixelHeight = imp_calibration.pixelHeight
        pixelDepth = imp_calibration.pixelDepth

        # Add end points in yellow
        end_points = skel_result.getListOfEndPoints()
        end_point_list = []
        for p in end_points:
            end_point_list.append(
                Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth))
        univ.addIcospheres(end_point_list, Color3f(255.0, 255.0, 0.0), 2,
                           1 * pixelDepth, "endpoints")

        # Add junctions in magenta
        junctions = skel_result.getListOfJunctionVoxels()
        junction_list = []
        for p in junctions:
            junction_list.append(
                Point3f(p.x * pixelWidth, p.y * pixelHeight, p.z * pixelDepth))
        univ.addIcospheres(junction_list, Color3f(255.0, 0.0, 255.0), 2,
                           1 * pixelDepth, "junctions")

        # Add the lines in green
        graphs = skel_result.getGraph()
        for graph in range(len(graphs)):
            edges = graphs[graph].getEdges()
            for edge in range(len(edges)):
                branch_points = []
                for p in edges[edge].getSlabs():
                    branch_points.append(
                        Point3f(p.x * pixelWidth, p.y * pixelHeight,
                                p.z * pixelDepth))
                univ.addLineMesh(branch_points, Color3f(0.0, 255.0, 0.0),
                                 "branch-%s-%s" % (graph, edge), True)

        # Add the surface
        univ.addMesh(binary)
        univ.getContent("binary").setTransparency(0.5)

    # Perform any postprocessing steps...
    status.showStatus("Running postprocessing...")
    if postprocessor_path != None:
        if postprocessor_path.exists():
            postprocessor_thread = scripts.run(postprocessor_path, True)
            postprocessor_thread.get()

    else:
        pass

    status.showStatus("Done analysis!")
def NND(imp, mapC, compareC):
    cal = imp.getCalibration()
    title = imp.getTitle()
    impZ = imp.getNSlices()
    dup = Duplicator()
    compare = dup.run(imp, compareC, compareC, 1, impZ, 1, 1)
    compare = reslice(compare, cal.pixelWidth)
    IJ.run(compare, "Gaussian Blur 3D...", "x=3 y=3 z=3")
    Z = compare.getNSlices()
    IJ.setAutoThreshold(compare, THRESHOLD + " dark stack")
    Prefs.blackBackground = True
    IJ.run(compare, "Convert to Mask",
           "method=" + THRESHOLD + " background=Dark black")
    IJ.run(compare, "Exact Signed Euclidean Distance Transform (3D)", "")
    edtcompare = WindowManager.getImage("EDT")
    edtcompare.getWindow().setVisible(False)

    mapp = dup.run(imp, mapC, mapC, 1, impZ, 1, 1)
    mapp = reslice(mapp, cal.pixelWidth)
    IJ.run(mapp, "Gaussian Blur 3D...", "x=3 y=3 z=3")
    IJ.setAutoThreshold(mapp, THRESHOLD + " dark stack")
    Prefs.blackBackground = True
    IJ.run(mapp, "Convert to Mask",
           "method=" + THRESHOLD + " background=Dark black")

    dists = []
    rt = ResultsTable()
    ol = Overlay()
    row = 0
    for z in range(Z):
        mapp.setPosition(z + 1)
        IJ.run(mapp, "Create Selection", "")
        if mapp.getStatistics().mean == 0:
            IJ.run(mapp, "Make Inverse", "")
        roi = mapp.getRoi()
        if roi is None:
            continue

        edtcompare.setPosition(z + 1)
        edtcompare.setRoi(roi)
        IJ.setBackgroundColor(0, 0, 0)
        IJ.run(edtcompare, "Clear Outside", "slice")

        ip = edtcompare.getProcessor()
        roiList = ShapeRoi(roi).getRois()  #split roi to limit bounds
        for sr in roiList:
            bounds = sr.getBounds()
            for y in range(0, bounds.height):
                for x in range(0, bounds.width):
                    if sr.contains(bounds.x + x, bounds.y + y):
                        d = ip.getf(bounds.x + x,
                                    bounds.y + y) * cal.pixelWidth * 1000
                        rt.setValue("C" + str(mapC) + " X", row,
                                    (bounds.x + x) * cal.pixelWidth)
                        rt.setValue("C" + str(mapC) + " Y", row,
                                    (bounds.y + y) * cal.pixelHeight)
                        rt.setValue("C" + str(mapC) + " Z", row,
                                    z * cal.pixelDepth)
                        rt.setValue("Distance to C" + str(compareC) + " (nm)",
                                    row, d)
                        row += 1
                        histD = d
                        if histD >= 0:  #set all overlapping voxel distances to 0
                            histD = 0
                        dists.append(
                            -histD)  #invert to positive for outside distance
        posZ = int(((z + 1) / float(Z)) * impZ) + 1
        roi.setPosition(0, posZ, 1)
        roi.setStrokeColor(Colour.MAGENTA)
        ol.add(roi)

        compare.setPosition(z + 1)
        IJ.run(compare, "Create Selection", "")
        if compare.getStatistics().mean == 0:
            IJ.run(compare, "Make Inverse", "")
        compareRoi = compare.getRoi()
        if compareRoi is not None:
            compareRoi.setPosition(0, posZ, 1)
            compareRoi.setStrokeColor(Colour.CYAN)
            ol.add(compareRoi)

    edtcompare.killRoi()
    histogram(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance",
              dists)
    rt.show(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance")
    imp.setOverlay(ol)
    compare.close()
    edtcompare.changes = False
    edtcompare.close()
    mapp.close()
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	title =  inputImp.getTitle()
	title=title.replace('UV', 'SD')
	
	print title
	
	#trueColorImp= WindowManager.getImage(title)
	#print type( trueColorImp)
	
	# calculate are of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	print inputRoi
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1

	print x1
	print y1
	print x2
	print y2
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	#duplicate.show()
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	redPlus.show()
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	APlus.show()
	APlus.getProcessor().resetMinAndMax()
	APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	#redMask.show()
	
	labPlus.close()
	
	# threshold the spots from the red channel
	thresholdedred=SpotDetectionGray(red, data, display, ops, False)
	display.createDisplay("thresholdedred", data.create(thresholdedred))
	impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	
	# threshold the spots from the brightness channel
	thresholded=SpotDetectionGray(brightness, data, display, ops, False)
	display.createDisplay("thresholded", data.create(thresholded))
	impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, clone)
	
	# create a hidden roi manager
	roim = RoiManager(True)
	
	# count the particlesimp.getProcessor().setColor(Color.green)
	countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity)
	
	# define a function to determine the percentage of pixels that are foreground in a binary image
	# inputs:
	#    imp: binary image, 0=background, 1=foreground
	#    roi: an roi
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return False
		else: return True

	allList=[]

	for roi in roim.getRoisAsArray():
		allList.append(roi.clone())
	
	# count particles that are red
	redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed)
	# count particles that are red
	blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed)

	print "Total particles: "+str(len(allList))
	print "Filtered particles: "+str(len(redList))

	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList]
	
	# create an overlay and add the rois
	overlay1=Overlay()
		
	inputRoi.setStrokeColor(Color.green)
	overlay1.add(inputRoi)
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList]
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList]
	
	def drawAllRoisOnImage(imp, mainRoi, redList, blueList):
		imp.getProcessor().setColor(Color.green)
		IJ.run(imp, "Line Width...", "line=3");
		imp.getProcessor().draw(inputRoi)
		imp.updateAndDraw()
		IJ.run(imp, "Line Width...", "line=1");
		[CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList]
		[CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList]
		imp.updateAndDraw()
	
	drawAllRoisOnImage(inputImp, inputRoi, redList, blueList)
	#drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList)
	
	# draw overlay
	#inputImp.setOverlay(overlay1)
	#inputImp.updateAndDraw()
	
	statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	print inputRoiArea

	areas=statsdict['Areas']
	poreArea=0
	for area in areas:
		poreArea=poreArea+area

	ATotal=0
	ALevels=statsdict['ALevel']
	for A in ALevels:
		ATotal=ATotal+A

	AAverage=ATotal/len(ALevels)

	BTotal=0
	BLevels=statsdict['BLevel']
	for B in BLevels:
		BTotal=BTotal+B

	BAverage=BTotal/len(BLevels)

	redTotal=0
	redPercentages=statsdict['redPercentage']
	for red in redPercentages:
		redTotal=redTotal+red

	redAverage=redTotal/len(redPercentages)
	pixwidth=inputImp.getCalibration().pixelWidth

	inputRoiArea=inputRoiArea/(pixwidth*pixwidth)
	
	print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
Пример #21
0
impProc.flipVertical()
impProc = impProc.rotateRight()
impProc.smooth()
impProc.setInterpolationMethod(ImageProcessor.NONE)
impProc = impProc.resize(canvasWidth,canvasHeight)
imp.setProcessor(impProc)
imp.show()

IJ.run(imp, "Rainbow RGB", "");
IJ.run(imp, "Canvas Size...", "width=800 height=1024 position=Top-Center zero");

testROI = Roi(0,canvasHeight,canvasWidth,6)
testROI.setFillColor(Color.WHITE)
imp.setRoi(testROI,True)

overlay = Overlay(testROI)
font = Font("SansSerif",Font.PLAIN,fontSize)

# Write the EmissionWavelengths according
# to the metadata read earlier.
for i in xrange(1,len(pixelInt2[0]),tickInterval):
    pixelSize = (canvasWidth/(len(pixelInt2[0])*1.0))
    calc      = (pixelSize)*(i)
    roi       = TextRoi(calc+(pixelSize*0.2),canvasHeight+10,str(emissionWL[i]),font)
    roi.setStrokeColor(Color(1.00, 1.00, 1.00));
    overlay.add(roi)

imp.setOverlay(overlay)
imp.show()
IJ.run(imp, "Calibration Bar...", "location=[Upper Right] fill=None label=White number=3 decimal=1 font=9 zoom=2 bold overlay");
def getRois(mask):
    mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE)
    composite = ThresholdToSelection().convert(mask)
    rois = ShapeRoi(composite).getRois()
    return rois


def getRoi(mask):
    mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE)
    roi = ThresholdToSelection().convert(mask)
    return roi


imp = IJ.getImage()
cal = imp.getCalibration()
ol = Overlay()

proj_sca1 = maxProject(imp, channel_sca1)
proj_hoescht = maxProject(imp, channel_hoescht)
proj_opn = maxProject(imp, channel_opn)
proj_gfp = maxProject(imp, channel_gfp)

mask_sca1 = mask2D(proj_sca1, 1.0 / cal.pixelWidth, 6,
                   AutoThresholder.Method.Otsu, min_sca1, False,
                   False)  #surrounding lumen
mask_hoescht = mask2D(proj_hoescht, 1.5 / cal.pixelWidth, 5,
                      AutoThresholder.Method.Otsu, min_hoescht, True,
                      True)  #Hoescht
mask_opn = mask2D(proj_opn, 1.0 / cal.pixelWidth, 0,
                  AutoThresholder.Method.MaxEntropy, min_opn, False,
                  False)  #surrounding lumen fragments
Пример #23
0
def batch_open_images(pathImage, file_typeImage, name_filterImage=None):

    if isinstance(pathImage, File):
        pathImage = pathImage.getAbsolutePath()

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filterImage:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filterImage, (list, tuple)):
                for name_filter_ in name_filterImage:
                    if name_filter_ in string:
                        # Exit the function with True.

                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filterImage, string):
                if name_filterImage in string:
                    return True
                else:
                    return False
            return False
        else:
            # Accept all files if name_filter is None.
            return True

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_typeImage:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_typeImage, (list, tuple)):
                for file_type_ in file_typeImage:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_typeImage, string):
                if string.endswith(file_typeImage):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathImage)
    path = os.path.expandvars(pathImage)
    # If we don't want a recursive search, we can use os.listdir().

    for directory, dir_names, file_names in os.walk(pathImage):
        # We are only interested in files.
        for file_name in file_names:
            # The list contains only the file names.
            # The full path needs to be reconstructed.
            full_path = os.path.join(directory, file_name)
            # Both checks are performed to filter the files.
            if check_type(file_name):
                if check_filter(file_name) is False:
                    # Add the file to the list of images to open.
                    path_to_Image.append([
                        full_path,
                        os.path.basename(os.path.splitext(full_path)[0])
                    ])
    Images = []

    for img_path, file_name in path_to_Image:

        imp = IJ.openImage(img_path)
        maskimage = ops.run("create.img", imp)
        cursor = maskimage.localizingCursor()
        imp.show()
        IJ.run("Select None")
        overlay = imp.getOverlay()
        if overlay == None:

            overlay = Overlay()
            imp.setOverlay(overlay)
        else:

            overlay.clear()

        imp.updateAndDraw()
        impY = imp.getHeight()
        impX = imp.getWidth()
        print(impY, impX)
        rm = RoiManager.getInstance()
        if not rm:
            rm = RoiManager()

        rm.runCommand("reset")
        WaitForUserDialog("Select the landmark and the second point").show()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()
        for Roi in roi_points:

            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Start Landmark', xpoints[0], ypoints[0])
        fixedpointX = xpoints[0]
        fixedpointY = ypoints[0]
        print('End Landmark', xpoints[1], ypoints[1])
        IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1])
        gui = GenericDialog("Rotation Angle")
        gui.addNumericField("Choose Angle", 15, 0)
        gui.showDialog()
        if gui.wasOKed():

            rotateangle = gui.getNextNumber()
            IJ.run("Rotate...", "angle=" + str(int(float(rotateangle))))

        rm.runCommand("reset")
        overlay = imp.getOverlay()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()

        for Roi in roi_points:
            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Rotated Start Landmark', xpoints[0], ypoints[0])
        print('Rotated End Landmark', xpoints[1], ypoints[1])
        slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20)
        intercept = fixedpointY - slope * fixedpointX
        print(fixedpointX, fixedpointY)
        print('Slope', slope, 'Intercept', intercept)
        XwY0 = -intercept / slope
        YxwY0 = slope * XwY0 + intercept

        XwYmax = (impY - intercept) / slope
        YxwYmax = slope * XwYmax + intercept

        YwX0 = intercept
        XywX0 = (YwX0 - intercept) / slope
        YwXmax = impX * slope + intercept
        XxwXmax = (YwXmax - intercept) / slope
        rm.runCommand("reset")

        if XwY0 > 0:
            lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0)
            lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        if XwY0 < 0:
            lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0)
            lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        while cursor.hasNext():
            cursor.fwd()
            X = cursor.getDoublePosition(0)
            Y = cursor.getDoublePosition(1)
            if abs(Y - slope * X - intercept) <= 4:
                cursor.get().set(0)
            else:
                cursor.get().set(1)
        labeling = ops.labeling().cca(maskimage,
                                      StructuringElement.EIGHT_CONNECTED)

        # get the index image (each object will have a unique gray level)
        labelingIndex = labeling.getIndexImg()
        dataImg = ds.create(labelingIndex)
        location = ls.resolve(
            str(savedir) + '/' + file_name + '.' + file_type_image)
        dio.save(dataImg, location)
        imp.close()