def threshold(imp, lower, upper):
	duplicate=Duplicator().run(imp)
	duplicate.getProcessor().resetMinAndMax()
	IJ.setAutoThreshold(duplicate, "Default dark");
	IJ.setThreshold(duplicate, lower, upper)
	IJ.run(duplicate, "Convert to Mask", "");
	return duplicate
	return SpotDetectionLog(imgBgs32, data, ops, thresholdmethod, dimensions2D, factory)

	
def SpotDetection2(imp):
	
	imp=Duplicator().run(imp)
	
	# subtract background
	return SpotDetectionLog(imgBgs32, data, ops, thresholdmethod, dimensions2D, factory)

	
def SpotDetection2(imp):
	
	imp=Duplicator().run(imp)
	
	# subtract background
	bgs=BackgroundSubtracter()
	bgs.rollingBallBackground(imp.getProcessor(), 50.0, False, False, True, True, True) 
	IJ.run(imp, "Auto Threshold", "method=Triangle white");
	return imp

def SpotDetection3(imp, invert=False):
	# operate on a duplicate as not to change the original
	imp=Duplicator().run(imp)
	if (invert):
		IJ.run(imp, "Invert", "");
	
	# subtract background
	bgs=BackgroundSubtracter()
	IJ.run(imp, "Auto Threshold", "method=Triangle white");
	return imp

def SpotDetection3(imp, invert=False):
	# operate on a duplicate as not to change the original
	imp=Duplicator().run(imp)
	if (invert):
		IJ.run(imp, "Invert", "");
	
	# subtract background
	bgs=BackgroundSubtracter()
	bgs.rollingBallBackground(imp.getProcessor(), 50.0, False, False, True, True, True)
Exemplo n.º 6
0
def boxed_intensities(imp1, width, height):
    """Create a new image with averaged intensity regions.

    Parameters
    ----------
    imp1 : ImagePlus
    width, height : int
        The width and height of the rectangles.

    Returns
    -------
    imp2 : ImagePlus
        The resulting ImagePlus, same dimensions as imp1.
    """
    imp2 = Duplicator().run(imp1)
    imp2.setTitle('heatmap-' + imp1.getTitle())

    imw = imp1.getWidth()
    imh = imp1.getHeight()

    ip1 = imp1.getProcessor()
    ip2 = imp2.getProcessor()

    if (imw % width + imh % height) > 0:
        msg = "WARNING: image size (%dx%d) not dividable by box (%dx%d)!"
        IJ.log(msg % (imw, imh, width, height))

    for box_y in range(0, imh / height):
        start_y = box_y * height
        for box_x in range(0, imw / width):
            start_x = box_x * width
            # print "%d %d" % (start_x, start_y)
            bavg = rect_avg(ip1, start_x, start_y, width, height)
            # print bavg
            rect_set(ip2, start_x, start_y, width, height, bavg)

    return imp2
Exemplo n.º 7
0
def boxed_intensities(imp1, width, height):
    """Create a new image with averaged intensity regions.

    Parameters
    ----------
    imp1 : ImagePlus
    width, height : int
        The width and height of the rectangles.

    Returns
    -------
    imp2 : ImagePlus
        The resulting ImagePlus, same dimensions as imp1.
    """
    imp2 = Duplicator().run(imp1)
    imp2.setTitle('heatmap-' + imp1.getTitle())

    imw = imp1.getWidth()
    imh = imp1.getHeight()

    ip1 = imp1.getProcessor()
    ip2 = imp2.getProcessor()

    if (imw % width + imh % height) > 0:
        msg = "WARNING: image size (%dx%d) not dividable by box (%dx%d)!"
        log.warn(msg % (imw, imh, width, height))

    for box_y in range(0, imh / height):
        start_y = box_y * height
        for box_x in range(0, imw / width):
            start_x = box_x * width
            # print "%d %d" % (start_x, start_y)
            bavg = rect_avg(ip1, start_x, start_y, width, height)
            # print bavg
            rect_set(ip2, start_x, start_y, width, height, bavg)

    return imp2
Exemplo n.º 8
0
if chl is None:
    maxC = max([i.getNChannels() for i in imL])
else:
    maxC = len(chl)
ssL = [] # Same number of slices
nff=True
for im in imL:
    if chl is not None: ## Here we extract only the channels we need
        im = SubHyperstackMaker().makeSubhyperstack(im, [i+1 for i in chl], range(1, im.getNSlices()+1), range(1, im.getNFrames()+1))
    nz = maxZ-im.getNSlices() # Number of z planes to add
    if nz==0 and im.getNChannels()==maxC:
        ssL.append(im)
        continue
    if im.getNFrames()==1:
        tmp = Duplicator().run(im, 1, im.getNChannels(), 1, 1, 1, 1) # create a duplicated slice
        tmp.getProcessor().multiply(0) # make it a dark frame    
        ssL.append(Concatenator().concatenate([im]+[tmp]*nz, False)) # This deletes references/images in imL
    else: # if im.getNFrames()>1 (we need to concatenate time-point-per timepoint :s )
        nff=False        
        allFrames = []
        stack = im.getImageStack()
        nZ = im.getNSlices()
        nC = im.getNChannels()
        dark = Duplicator().run(im, 1, 1, 1, 1, 1, 1)
        dark.getProcessor().multiply(0)
        res = ij.ImageStack(im.width, im.height)
        icnt = 0
        for ia in range(1, im.getNFrames()+1):
            for ib in range(1, maxZ+1):
                for ic in range(1,maxC+1):
                    icnt +=1
Exemplo n.º 9
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 generate_background_rois(input_mask_imp,
                             params,
                             membrane_edges,
                             dilations=5,
                             threshold_method=None,
                             membrane_imp=None):
    """automatically identify background region based on auto-thresholded image, existing membrane edges and position of midpoint anchor"""
    if input_mask_imp is None and membrane_imp is not None:
        segmentation_imp = Duplicator().run(membrane_imp)
        # do thresholding using either previous method if threhsold_method is None or using (less conservative?) threshold method
        if (threshold_method is None
                or not (threshold_method in params.listThresholdMethods())):
            mask_imp = make_and_clean_binary(segmentation_imp,
                                             params.threshold_method)
        else:
            mask_imp = make_and_clean_binary(segmentation_imp,
                                             threshold_method)
        segmentation_imp.close()
    else:
        input_mask_imp.killRoi()
        mask_imp = Duplicator().run(input_mask_imp)

    rois = []
    IJ.setForegroundColor(0, 0, 0)
    roim = RoiManager(True)
    rt = ResultsTable()

    for fridx in range(mask_imp.getNFrames()):
        mask_imp.setT(fridx + 1)
        # add extra bit to binary mask from loaded membrane in case user refined edges...
        # flip midpoint anchor across the line joining the two extremes of the membrane,
        # and fill in the triangle made by this new point and those extremes
        poly = membrane_edges[fridx].getPolygon()
        l1 = (poly.xpoints[0], poly.ypoints[0])
        l2 = (poly.xpoints[-1], poly.ypoints[-1])
        M = (0.5 * (l1[0] + l2[0]), 0.5 * (l1[1] + l2[1]))
        Mp1 = (params.manual_anchor_midpoint[0][0] - M[0],
               params.manual_anchor_midpoint[0][1] - M[1])
        p2 = (M[0] - Mp1[0], M[1] - Mp1[1])
        new_poly_x = list(poly.xpoints)
        new_poly_x.append(p2[0])
        new_poly_y = list(poly.ypoints)
        new_poly_y.append(p2[1])
        mask_imp.setRoi(PolygonRoi(new_poly_x, new_poly_y, PolygonRoi.POLYGON))
        IJ.run(mask_imp, "Fill", "slice")
        mask_imp.killRoi()

        # now dilate the masked image and identify the unmasked region closest to the midpoint anchor
        ip = mask_imp.getProcessor()
        dilations = 5
        for d in range(dilations):
            ip.dilate()
        ip.invert()
        mask_imp.setProcessor(ip)
        mxsz = mask_imp.getWidth() * mask_imp.getHeight()
        pa = ParticleAnalyzer(
            ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_PROGRESS,
            ParticleAnalyzer.CENTROID, rt, 0, mxsz)
        pa.setRoiManager(roim)
        pa.analyze(mask_imp)
        ds_to_anchor = [
            math.sqrt((x - params.manual_anchor_midpoint[0][0])**2 +
                      (y - params.manual_anchor_midpoint[0][1])**2)
            for x, y in zip(
                rt.getColumn(rt.getColumnIndex("X")).tolist(),
                rt.getColumn(rt.getColumnIndex("Y")).tolist())
        ]
        if len(ds_to_anchor) > 0:
            roi = roim.getRoi(ds_to_anchor.index(min(ds_to_anchor)))
            rois.append(roi)
        else:
            rois.append(None)
        roim.reset()
        rt.reset()
    roim.close()
    mask_imp.close()
    return rois
    original)  # duplicate the original image, only the CFOV
CFOV.setTitle("CFOV")
CFOV.show()

######### Nema process including Re-bin image to larger pixels ################################################################################
desired_pixel_width = getPixel(
)  # 6.4 mm default, remember tolerance is +/-30%
current_pixel_width = CFOV.getCalibration(
).pixelWidth  #get pixel width, 1.16 mm
shrink_factor = int(desired_pixel_width /
                    current_pixel_width)  # must be an integer

IJ.run(CFOV, "Bin...", "x=" + str(shrink_factor) + " y=" + str(shrink_factor) +
       " bin=Sum")  # run the bin plugin
IJ.run(CFOV, "Convolve...",
       "text1=[1 2 1\n2 4 2\n1 2 1\n] normalize")  # apply the nema filter

######## Analyse pixels
CFOVpixels = CFOV.getProcessor().convertToFloat().getPixels(
)  # access processor, get float array of pixels
CFOVmean = sum(CFOVpixels) / len(CFOVpixels)
#pixels_above_threshold = filter(lambda pix: pix > 0.75*mean, pixels)  # return a new array with values above zero, use anonymous function
CFOVunifiormity = getUniformity(min(CFOVpixels), max(CFOVpixels))

######## Print results
results_string = "The integral uniformity of the CFOV is: " + str(
    CFOVunifiormity) + "% for pixel size of " + str(
        desired_pixel_width) + " mm"
IJ.log(results_string)
IJ.showMessage(results_string)
Exemplo n.º 12
0
otsu=ops.run("threshold", ops.create( dimensions2D, BitType()), imgBgs, Otsu())
display.createDisplay("thresholded", data.create(ImgPlus(otsu)))
'''

#Utility.clearOutsideRoi(imp, clone)
IJ.run(imp, "Auto Local Threshold",
       "method=MidGrey radius=15 parameter_1=0 parameter_2=0 white")
IJ.run(imp, "Fill Holes", "")
IJ.run(imp, "Close-", "")
IJ.run(imp, "Watershed", "")

iplus.updateAndDraw()

# create a hidden roi manager
roim = RoiManager(True)

# count the particles
countParticles(iplus, roim, 10, 200, 0.5, 1.0)

[truecolor1.getProcessor().draw(roi) for roi in roim.getRoisAsArray()]
truecolor1.updateAndDraw()

#Prefs.blackBackground = False;
#IJ.run("Make Binary", "");

#IJ.run("LoG 3D");

#IJ.run("Duplicate...", "title="+"test")
#IJ.run("RGB Stack");
#IJ.run("Convert Stack to Images");
Exemplo n.º 13
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!")
Exemplo n.º 14
0
	def __addroi(self, event) :
		if ( not self.__init) : 
			IJ.showMessage("", "please start a new stack")
			return
		if ( not self.__initDIA) :
			IJ.showMessage("", "please select an image for DIA")
			return

		if ( not self.__initFLUO) :
			IJ.showMessage("", "please select an image for FLUO")
			return

		twres = TextWindow("measures-"+self.__name, "label\tname\tsol\tarea\tcirc\tAR\tFeret\taxis\traf\tdMajor\tdFeret\tdArea", "", 300, 450)
		tab="\t"
		
		self.__widthl = self.__display2.getText()
		IJ.selectWindow(self.__impF.getTitle())

		self.__rm = RoiManager.getInstance()
		if (self.__rm==None): self.__rm = RoiManager()

		if self.__impF.getImageStackSize() > 1 :
			roisarray =[(roi, self.__rm.getSliceNumber(roi.getName())) for roi in self.__rm.getRoisAsArray()]
		else : 
			roisarray =[(roi, 1) for roi in self.__rm.getRoisAsArray()]
			
		self.__rm.runCommand("reset")
		#self.__rm.runCommand("Delete")
		IJ.selectWindow(self.__impF.getTitle())

		self.__maxraf=float(self.__display19.text)
		self.__minraf=float(self.__display20.text)

		count=1

		for roielement in roisarray :
			roi = roielement[0]
			pos = roielement[1]
			lab = self.__impF.getImageStack().getShortSliceLabel(pos)

			if lab==None : lab=str(pos)
			
			if self.__conEllipses :
				IJ.selectWindow(self.__impF.getTitle())
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				self.__rm.runCommand("Add")
				IJ.run(self.__impF,  "Fit Ellipse", "")
				ellipse=self.__impF.getRoi()
				params = ellipse.getParams()
				ferets = ellipse.getFeretValues()
				imp2 = Duplicator().run(self.__impF,pos,pos)
				IJ.run(imp2, "Rotate... ", "angle="+str(ferets[1])+" grid=0 interpolation=Bilinear enlarge slice")
				temproi=Roi((imp2.getWidth()-ferets[0])/2.0,(imp2.getHeight()-ferets[2])/2.0,ferets[0],ferets[2])
				imp2.setRoi(temproi)
				imp3 = Duplicator().run(imp2,1,1)
				ip3=imp3.getProcessor()

				if int(self.__display5.text) < ip3.getWidth() < int(self.__display6.text) : 
					self.__iplist.append(ip3)
					self.__display.text = self.__name + " cell " + str(len(self.__iplist))
					fer=Line(params[0],params[1],params[2],params[3])
					self.__cellsrois.append((fer, pos))
					self.__labels.append(self.__isF.getShortSliceLabel(pos))

				m=Morph(self.__impF, roi)

				twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(fer.getLength())+tab+str(1)+tab+str(0)+tab+str(0)+tab+str(0))
				self.__dictCells[count]=(str(roi.getName()), lab, roi)
				count=count+1
				continue
			
			if roi.getType() in [6,7] : 
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				self.__rm.runCommand("Add")

			elif roi.getType() in [2,4] :
				self.__impF.setSlice(pos)
				self.__impF.setRoi(roi)
				m=Morph(self.__impF, roi)
				m.setMidParams(10, 2)
				midroi=m.MidAxis
				if midroi == None : continue

				raf = m.MaxFeret/midroi.getLength()
				
				if (self.__maxraf < raf) or (raf < self.__minraf) : continue

				maxsol = float(self.__display7.text)
				minsol = float(self.__display8.text)
				maxarea = float(self.__display9.text)
				minarea = float(self.__display10.text)
				maxcirc = float(self.__display11.text)
				mincirc = float(self.__display12.text)
				maxar = float(self.__display13.text)
				minar = float(self.__display14.text)
				maxfer = float(self.__display15.text)
				minfer = float(self.__display16.text)
				maxmean = float(self.__display17.text)
				minmean = float(self.__display18.text)
				maxmferet = float(self.__display21.text)
				minmferet = float(self.__display22.text)

				testsol = (minsol<= m.Solidity <= maxsol)
				testarea = (minarea<= m.Area <= maxarea)
				testcirc = (mincirc<= m.Circ <= maxcirc)
				testar = (minar<= m.AR <= maxar)
				testfer = (minfer<= m.MaxFeret <= maxfer)
				testmean = (minmean <= m.Mean <= maxmean)
				testmferet = (minmferet <= m.MinFeret <= maxmferet)
				
				#print minmferet , m.MinFeret , maxmferet

				test = (testsol+testarea+testcirc+testar+testfer+testmean+testmferet)/7	

				if test : 				
					fmaj, ffmx, fa =[],[],[]
					for r in m.getMidSegments(10, 40, 0)[0] :
						if r == None : continue
						m2=Morph(self.__impF, r)
						fmaj.append(m2.Major)
						ffmx.append(m2.MaxFeret)
						fa.append(m2.Area)

					diffmajor, diffferet, diffarea = 0,0,0
					
					if len(fa) > 4 :
						medfmaj = self.listmean(fmaj[1:-1])
						medffmx = self.listmean(ffmx[1:-1])
						medfa   = self.listmean(fa[1:-1])

						diffmajor = (max(fmaj[1:-1])-medfmaj)/medfmaj
						diffferet = (max(ffmx[1:-1])-medffmx)/medffmx
						diffarea = (max(fa[1:-1])-medfa)/medfa

					twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea))
					#print lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea)

					self.__impF.setRoi(roi)
					self.__rm.runCommand("Add")
					self.__impF.killRoi()
					self.__impF.setRoi(midroi)
					
					#self.__dictCells[str(roi.getName())]=(str(roi.getName()), lab, roi)
					self.__dictCells[count]=(str(roi.getName()), lab, roi)
					count=count+1
					
				else : 
					#print "test falls"
					continue

			else : 
				print "out loop"
				continue
			
			straightener = Straightener()
			new_ip = straightener.straighten(self.__impF, midroi, int(self.__widthl))
			if int(self.__display5.text) < new_ip.getWidth() < int(self.__display6.text) : 
				self.__iplist.append(new_ip.convertToShort(False))
				self.__display.text = self.__name + " cell " + str(len(self.__iplist))
				#print "add", roi.getName(), roi.getType()
				self.__cellsrois.append((midroi, pos))
				self.__labels.append(self.__isF.getShortSliceLabel(pos))


		#roisarray=self.__rm.getRoisAsArray()		
		#self.__rm.runCommand("reset")
		#self.__rm.runCommand("Delete")
		

		self.__impD.killRoi()
		self.__impF.killRoi()
		IJ.selectWindow(self.__impD.getTitle()) 
display.createDisplay("log", data.create(ImgPlus(log)))

otsu=ops.run("threshold", ops.create( dimensions2D, BitType()), imgBgs, Otsu())
display.createDisplay("thresholded", data.create(ImgPlus(otsu)))
'''

#Utility.clearOutsideRoi(imp, clone)
IJ.run(imp, "Auto Local Threshold", "method=MidGrey radius=15 parameter_1=0 parameter_2=0 white");
IJ.run(imp, "Fill Holes", "");
IJ.run(imp, "Close-", "");
IJ.run(imp, "Watershed", "");

iplus.updateAndDraw()

# create a hidden roi manager
roim = RoiManager(True)
	
# count the particles
countParticles(iplus, roim, 10, 200, 0.5, 1.0)

[truecolor1.getProcessor().draw(roi) for roi in roim.getRoisAsArray()]
truecolor1.updateAndDraw()
	
#Prefs.blackBackground = False;
#IJ.run("Make Binary", "");

#IJ.run("LoG 3D");

#IJ.run("Duplicate...", "title="+"test")
#IJ.run("RGB Stack");
#IJ.run("Convert Stack to Images");
UFOV = Duplicator().run(original) # duplicate the original image, only the CFOV
UFOV.setTitle("UFOV")
UFOV.show() 

CFOV_fraction = 0.75  # choose the fraction of the UFOV that defines the CFOV
IJ.run(original,"Scale... ", "x="+str(CFOV_fraction)+" y="+str(CFOV_fraction)+" centered") # rescale bounding box to get CFOV

CFOV = Duplicator().run(original) # duplicate the original image, only the CFOV
CFOV.setTitle("CFOV")
CFOV.show() 


######### Nema process including Re-bin image to larger pixels ################################################################################
desired_pixel_width = getPixel() # 6.4 mm default, remember tolerance is +/-30%
current_pixel_width =  CFOV.getCalibration().pixelWidth  #get pixel width, 1.16 mm
shrink_factor = int(desired_pixel_width/current_pixel_width)  # must be an integer

IJ.run(CFOV, "Bin...", "x="+str(shrink_factor)+" y="+str(shrink_factor)+" bin=Sum") # run the bin plugin
IJ.run(CFOV, "Convolve...", "text1=[1 2 1\n2 4 2\n1 2 1\n] normalize")  # apply the nema filter

######## Analyse pixels
CFOVpixels = CFOV.getProcessor().convertToFloat().getPixels()     # access processor, get float array of pixels
CFOVmean = sum(CFOVpixels) / len(CFOVpixels) 
#pixels_above_threshold = filter(lambda pix: pix > 0.75*mean, pixels)  # return a new array with values above zero, use anonymous function
CFOVunifiormity = getUniformity(min(CFOVpixels), max(CFOVpixels))

######## Print results
results_string = "The integral uniformity of the CFOV is: " +str(CFOVunifiormity)+ "% for pixel size of "+str(desired_pixel_width)+" mm"
IJ.log(results_string)
IJ.showMessage(results_string)