def roi(mask, image):
    # Convert ROI from R^n to Z^n.
    #discreteROI = Views.raster(Masks.toRealRandomAccessible(mask))
    # Apply finite bounds to the discrete ROI.
    boundedDiscreteROI = Views.interval(mask, image)
    # Create an iterable version of the finite discrete ROI.
    iterableROI = Regions.iterable(boundedDiscreteROI)
    return Regions.sample(iterableROI, image)
Beispiel #2
0
def measurePeaks(filename, retry=0):
    img3D = klb.readFull(os.path.join(srcDir, filename))
    """
  mean_intensities = []
  print Intervals.dimensionsAsLongArray(img3D)
  for inside, peak in zip(insides, peaks):
    samples = Regions.sample(inside, img3D)
    #print type(samples)
    #print Intervals.dimensionsAsLongArray(samples)
    s = sum(t.get() for t in samples)
    print s, count, Regions.countTrue(inside), str([peak.getFloatPosition(d) for d in [0,1,2]])
    mean_intensities.append(s / count)
  """
    try:
        mean_intensities = [
            (sum(t.get() for t in Regions.sample(inside, img3D)) / count)
            for inside in insides
        ]
        return mean_intensities
    except:
        syncPrint(sys.exc_info())
        if retry < 2:
            syncPrint("Retrying %s" % filename)
            return measurePeaks(filename, retry=retry + 1)
    return mean_intensities
def looping(img, center):
  for z in xrange(img.dimension(2)):
    radius = img.dimension(0) * 0.5 / (z + 1)
    circle = GeomMasks.openSphere(center, radius)
    # Works, explicit iteration of every pixel
    for t in Regions.sample(circle, Views.hyperSlice(img, 2, z)):
      t.setOne()
from net.imglib2.algorithm.labeling.ConnectedComponents import StructuringElement
from net.imglib2.roi import Regions
from net.imglib2.roi.labeling import LabelRegions

# create a log kernel
logKernel = ops.create().kernelLog(inputData.numDimensions(), sigma)

logFiltered = ops.filter().convolve(inputData, logKernel)

# otsu threshold and display
thresholded = ops.threshold().otsu(logFiltered)

# call connected components to label each connected region
labeling = ops.labeling().cca(thresholded, StructuringElement.FOUR_CONNECTED)

# get the index image (each object will have a unique gray level)
labelingIndex = labeling.getIndexImg()

# get the collection of regions and loop through them
regions = LabelRegions(labeling)
for region in regions:
    # get the size of the region
    size = region.size()

    # get the intensity by "sampling" the intensity of the input image at the region pixels
    intensity = ops.stats().mean(Regions.sample(region,
                                                inputData)).getRealDouble()

    print "size", size, "intensity", intensity
Beispiel #5
0
                             "deltaFoF_somaDiameter%0.2f.csv" % somaDiameter)
peaks = peak_map[somaDiameter]

# Measure intensity over time, for every peak
# by averaging the signal within a radius of each peak.
measurement_radius_px = [
    (somaDiameter / calibration[d]) * 0.66 for d in xrange(3)
]  # NOTE: DIVIDING BY 3, not 2, to make the radius a bit smaller
spheres = [
    ClosedWritableEllipsoid([peak.getFloatPosition(d)
                             for d in xrange(3)], measurement_radius_px)
    for peak in peaks
]
insides = [
    Regions.iterable(
        Views.interval(Views.raster(Masks.toRealRandomAccessible(sphere)),
                       Intervals.largestContainedInterval(sphere)))
    for sphere in spheres
]

count = float(Regions.countTrue(insides[0]))  # same for all


def measurePeaks(filename, retry=0):
    img3D = klb.readFull(os.path.join(srcDir, filename))
    """
  mean_intensities = []
  print Intervals.dimensionsAsLongArray(img3D)
  for inside, peak in zip(insides, peaks):
    samples = Regions.sample(inside, img3D)
    #print type(samples)
# Threshold if required
if thresholding == "None":
    binary = ops.run("threshold.mean", mask)
else:
    binary = ops.run("threshold.%s" % thresholding, smoothed)

# Create LabelRegions
img_labeling = ops.run("labeling.cca", binary,
                       StructuringElement.EIGHT_CONNECTED)
regions = list(LabelRegions(img_labeling))

# Process each LabelRegion
for region in regions:
    # Get a sample view
    sample = Regions.sample(region, image)

    # Compute the stats
    area = ops.run("stats.size", sample)
    min = ops.run("stats.min", sample)
    max = ops.run("stats.max", sample)
    mean = ops.run("stats.mean", sample)
    median = ops.run("stats.median", sample)
    stdev = ops.run("stats.stdDev", sample)
    sum = ops.run("stats.sum", sample)

    # Increment the row and add everything to the table
    results.incrementCounter()
    results.addValue("area", area.getRealDouble())
    results.addValue("min", min.getRealDouble())
    results.addValue("max", max.getRealDouble())
def countTrue(mask):
	n = 0
	for px in Regions.iterable(mask):
		n=n+1
	return n
	# "MASK"
	# AND operation between MIP Green and "MASK"
	green_masked_tophat = ops.eval("g * uint8(m)", {"g":green_tophat,"m":red_mask})
	if debugging:
		ui.show('GREEN_MASKED_TOPHAT',green_masked_tophat)
	
	# Threshold (1,65k)
	v = green_masked_tophat.firstElement().copy()
	v.set(1)
	green_mask = ops.create().img(red_mask)
	ops.threshold().apply(green_mask,green_masked_tophat,v)

	# Region statistics
	# Threshold T = Mean+Std*1.5
	# Convert to Mask
	R = Regions.sample(Regions.iterable(green_mask),green_masked_tophat)
	Gmean = ops.stats().mean(R).getRealDouble()
	Gstd = ops.stats().stdDev(R).getRealDouble()
	T = Gmean + Gstd*3.5
	log('Calculated threshold for the green is {}'.format(T))
	green_mask = ops.create().img(red_mask)
	ops.threshold().apply(green_mask,ops.convert().float32(green_masked_tophat),FloatType(T))

	if debugging:
		print green_mask
		ui.show('GREEN_MASK',green_mask)
	
	# Analyze particles (minPSize-maxPSize) (default: 4-80)
	# Create new object mask
	log('Creating cleaned mask and counting....')
	green_mask_new = ops.create().img(green_mask)
from ij import IJ
from itertools import imap

# Open the embryos sample image, and turn it into 16-bit grayscale
imp = IJ.getImage()
IJ.run(imp, "16-bit", "")
IJ.run(imp, "Specify...", "width=61 height=61 x=1037 y=83 oval")
circle = imp.getRoi()
bounds = circle.getBounds()
center = bounds.x + bounds.width / 2.0, bounds.y + bounds.height / 2.0
print center

img = IL.wrap(imp)
sphere = GeomMasks.closedSphere(center, 61 / 2.0)
inside = Regions.iterable(
    Views.interval(Views.raster(Masks.toRealRandomAccessible(sphere)),
                   Intervals.largestContainedInterval(sphere)))

pixels = []
ra = img.randomAccess()
cursor = inside.cursor()  # only True pixels of the sphere mask

while cursor.hasNext():
    cursor.fwd()
    ra.setPosition(cursor)
    pixels.append(ra.get().get())

print "Average:", sum(pixels) / float(len(pixels))

# prints: 68.91
# whereas ImageJ "measure" prints: 69.285 for the EllipseRoi
def measureFluorescence(series_name, img4D, mask=None):
    csv_fluorescence = os.path.join(srcDir,
                                    "%s_fluorescence.csv" % series_name)
    if not os.path.exists(csv_fluorescence):
        # Generate projection over time (the img3D) and extract peaks with difference of Gaussian using the params
        # (Will check if file for projection over time exists and just load it)
        img3D_filepath = os.path.join(
            srcDir, "%s_4D-to-3D_max_projection.zip" % series_name)
        img3D, peaks, spheresRAI, impSpheres = findNucleiByMaxProjection(
            img4D, params, img3D_filepath, show=True)
        comp = showAsComposite([wrap(img3D), impSpheres])
        # Measure intensity over time, for every peak
        # by averaging the signal within a radius of each peak.
        measurement_radius = somaDiameter / 3.0
        spheres = [
            ClosedWritableSphere([peak.getFloatPosition(d)
                                  for d in xrange(3)], measurement_radius)
            for peak in peaks
        ]
        insides = [
            Regions.iterable(
                Views.interval(
                    Views.raster(Masks.toRealRandomAccessible(sphere)),
                    Intervals.largestContainedInterval(sphere)))
            for sphere in spheres
        ]

        count = float(Regions.countTrue(insides[0]))  # same for all
        measurements = []

        with open(csv_fluorescence, 'w') as csvfile:
            w = csv.writer(csvfile,
                           delimiter=",",
                           quotechar='"',
                           quoting=csv.QUOTE_NONNUMERIC)
            # Header: with peak coordinates
            w.writerow(["timepoint"] + [
                "%.2f::%.2f::%.2f" %
                tuple(peak.getFloatPosition(d) for d in xrange(3))
                for peak in peaks
            ])
            # Each time point
            for t in xrange(img4D.dimension(3)):
                img3D = Views.hyperSlice(img4D, 3, t)
                mean_intensities = array(
                    ((sum(t.get()
                          for t in Regions.sample(inside, img3D)) / count)
                     for inside in insides), 'f')
                w.writerow([t] + mean_intensities.tolist())
                measurements.append(mean_intensities)

    else:
        # Parse CSV file
        with open(csv_fluorescence, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            header = reader.next()
            # Parse header, containing peak locations
            peaks = [
                RealPoint.wrap(map(float, h.split("::")))
                for h in islice(header, 1, None)
            ]
            # Parse rows
            measurements = [map(float, islice(row, 1, None)) for row in reader]

    return peaks, measurements
def dequeing(img, center):
  for z in xrange(img.dimension(2)):
    radius = img.dimension(0) * 0.5 / (z + 1)
    circle = GeomMasks.openSphere(center, radius)
    deque(imap(BitType.setOne, Regions.sample(circle, Views.hyperSlice(img, 2, z))), maxlen=0)
Beispiel #12
0
from net.imglib2.img.display.imagej import ImageJFunctions as IL
from net.imglib2.img.array import ArrayImgs
from net.imglib2.roi.geom import GeomMasks
from net.imglib2.roi import Regions
from net.imglib2.view import Views
from net.imglib2.type.logic import BitType
from collections import deque
from itertools import imap

# A binary image
img = ArrayImgs.bits([512, 512, 50])

# Add some data to it
center = img.dimension(0) / 2, img.dimension(1) / 2
for z in xrange(img.dimension(2)):
    radius = img.dimension(0) * 0.5 / (z + 1)
    #print radius
    circle = GeomMasks.openSphere(center, radius)
    # Works, explicit iteration of every pixel
    #for t in Regions.sample(circle, Views.hyperSlice(img, 2, z)):
    #  t.setOne()
    # Works: about twice as fast -- measured with: from time import time .... t0 = time(); ... t1 = time()
    deque(imap(BitType.setOne,
               Regions.sample(circle, Views.hyperSlice(img, 2, z))),
          maxlen=0)

IL.wrap(img, "bit img").show()
for peak in peaks:
    # Read peak coordinates into an array of integers
    peak.localize(p)
    # Define limits of the interval around the peak:
    # (sigmaSmaller is half the radius of the embryo)
    minC = [int(p[i] - sigmaSmaller) for i in xrange(img.numDimensions())]
    maxC = [int(p[i] + sigmaSmaller) for i in xrange(img.numDimensions())]
    # View the interval around the peak, as a flat iterable (like an array)
    square = Views.flatIterable(Views.zeroMin(Views.interval(img, minC, maxC)))
    s1 = sum(t.getInteger() for t in square)
    area1 = Intervals.numElements(square)
    # Use a sphere instead
    radius = sqrt(area1 / pi)  # same area for both
    print sigmaSmaller, radius
    circle = Masks.toIterableRegion(GeomMasks.closedSphere(p, radius))
    s2 = sum(t.getInteger() for t in Regions.sample(circle, imgE))
    area2 = Intervals.numElements(circle)

    print area1, area2

    # Compute sum of pixel intensity values of the interval
    # (The t is the Type that mediates access to the pixels, via its get* methods)

    # Add to results table
    table.incrementCounter()
    table.addValue("x", p[0])
    table.addValue("y", p[1])
    table.addValue("avg square", float(s1) / area1)
    table.addValue("avg circle", float(s2) / area2)

table.show("Embryo intensities at peaks")
Beispiel #14
0
outputinversetargetRan = invert_copy_output_skel.randomAccess()
while inversetargetCursor.hasNext():
    inversetargetCursor.fwd()

    outputinversetargetRan.setPosition(inversetargetCursor)
    if (inversetargetCursor.get().get() == 1):
        value = 0
    if (inversetargetCursor.get().get() == 0):
        value = 1
    outputinversetargetRan.get().set(value)

# call connected components to label each connected region
labeling = ops.labeling().cca(invert_copy_output_skel,
                              StructuringElement.EIGHT_CONNECTED)

# get the index image (each object will have a unique gray level)
labelingIndex = labeling.getIndexImg()

# get the collection of regions and loop through them
regions = LabelRegions(labeling)
for region in regions:
    # get the size of the region
    size = region.size()

    # get the intensity by "sampling" the intensity of the input image at the region pixels
    intensity = ops.stats().mean(Regions.sample(region,
                                                original)).getRealDouble()

    print "size", size, "intensity", intensity

output_label = ds.create(labelingIndex)