def show(title, nuclei, radius, bounds, scale=1.0):
    points = [RealPoint.wrap([c * scale for c in coords]) for coords in nuclei]
    interval = FinalInterval([int(b * scale) for b in bounds[0]],
                             [int(b * scale) for b in bounds[1]])
    img = virtualPointsRAI(points, radius * scale, interval)
    imp = showStack(img, title=title)
    return imp, img, points
Пример #2
0
def withIcospheres(time_window=None):
  with open(os.path.join(baseDir, csvFilename), 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    header = reader.next()
    peaks = [RealPoint.wrap(imap(float, peak.split('::'))) for peak in islice(header, 1, None)]
    # Template icosahedron
    ico = MeshMaker.createIcosahedron(2, radius)
    # Share lists of Point3f across all timepoints
    icos = [MeshMaker.copyTranslated(ico, peak.getFloatPosition(0), peak.getFloatPosition(1) , peak.getFloatPosition(2)) for peak in peaks]
    #
    univ = Image3DUniverse(512, 512)
    instants = TreeMap()
    #
    rows = reader if time_window is None else islice(reader, time_window[0], time_window[1])
    for row in rows:
      # Values mapped to 0-1: Color3f takes 3 values in domain [0, 1].
      # So: ensure the value is inside [minimum, maximum] range, then rezero by subtracting minimum, and divide by span (maximum - minimum)
      values = ((min(max(float(v), minimum), maximum) - minimum) / span for v in islice(row, 1, None))
      meshes = [CustomTriangleMesh(mesh, Color3f(v, v, v), 0)
                for v, mesh in izip(values, icos)]
      ci = ContentInstant(str(row[0]))
      ci.display(CustomMultiMesh(meshes)) # each mesh has its color
      ci.setLocked(True)
      print row[0]
      instants.put(int(row[0]), ci)
    
    print "n instants:", instants.size()
    univ.addContent(Content("deltaF/F", instants, False))
    univ.show()
    univ.updateStartAndEndTime(0, len(instants) -1)
def withVirtualStack(time_window=None, subsample=None):
    with open(os.path.join(baseDir, csvFilename), 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        header = reader.next()
        peaks = [
            RealPoint.wrap(imap(float, peak.split('::')))
            for peak in islice(header, 1, None)
        ]
        frames = [
            virtualPointsRAI(peaks,
                             radius,
                             interval,
                             inside=to8bitRange(
                                 map(float, islice(row, 1, None))))
            for row in reader
        ]
        if time_window:
            first, last = time_window
            frames = frames[first:last + 1]
        img4D = Views.stack(frames)
        # Scale by a factor of 'subsample' in every dimension by nearest neighbor, sort of:
        if subsample:
            img4D = Views.subsample(img4D, subsample)
        imp = ImagePlus("deltaF/F", ImageJVirtualStackUnsignedByte.wrap(img4D))
        imp.setDimensions(1, img4D.dimension(2), img4D.dimension(3))
        imp.setDisplayRange(0, 255)
        com = CompositeImage(imp, CompositeImage.GRAYSCALE)
        com.show()
        univ = Image3DUniverse(512, 512)
        univ.show()
        univ.addVoltex(com)
Пример #4
0
        "calibration": calibration,
        "minPeakValue": 0.2,  # determined by hand: the bright peaks
        "sigmaSmaller": somaDiameter / 4.0,  # in calibrated units: 1/4 soma
        "sigmaLarger": somaDiameter / 2.0,  # in calibrated units: 1/2 soma
    }

    csv_path = os.path.join(
        tgtDir, "peaks_somaDiameter=%0.1f_minPeakValue=%0.3f.csv" %
        (somaDiameter, params["minPeakValue"]))

    if os.path.exists(csv_path):
        print "Parsing CSV file %s" % csv_path
        with open(csv_path, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
            reader.next()  # skip first line: the header
            peaks = [RealPoint.wrap(map(float, coords)) for coords in reader]

    else:
        peaks = doGPeaks(max_projection, params)
        print "Detected %i peaks with somaDiameter %f" % (len(peaks),
                                                          somaDiameter)

        if len(peaks) > 0:
            with open(csv_path, 'w') as csvfile:
                w = csv.writer(csvfile,
                               delimiter=",",
                               quoting=csv.QUOTE_NONNUMERIC)
                w.writerow(["x", "y", "z"])  # header
                for peak in peaks:
                    w.writerow([peak.getFloatPosition(d) for d in xrange(3)])
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
Пример #6
0
# Test whether the first nearest neighbor is the point itself
from net.imglib2 import RealPoint, KDTree
from net.imglib2.neighborsearch import RadiusNeighborSearchOnKDTree

points = [RealPoint.wrap([1.0, 1.0, float(i)]) for i in xrange(10)]

tree = KDTree(points, points)
search = RadiusNeighborSearchOnKDTree(tree)

radius = 3
search.search(RealPoint.wrap([1.0, 1.0, 1.0]), 3, False) # unordered

for i in xrange(search.numNeighbors()):
  print "Point " + str(i), search.getSampler(i).get()


# Prints:
# Point 0 (1.0,1.0,3.0)
# Point 1 (1.0,1.0,4.0)
# Point 2 (1.0,1.0,0.0)
# Point 3 (1.0,1.0,1.0)
# Point 4 (1.0,1.0,2.0)


# So yes: the first point is always the query point.
Пример #7
0
import sys
sys.path.append("/home/albert/lab/scripts/python/imagej/IsoView-GCaMP/")
from lib.io import readN5
from lib.dogpeaks import createDoG
from lib.synthetic import virtualPointsRAI
from lib.ui import showStack
from net.imglib2 import RealPoint, FinalInterval


points = [RealPoint.wrap([255, 255, 255]),
          RealPoint.wrap([255, 255, 0]),
          RealPoint.wrap([128, 384, 128])]

rai = virtualPointsRAI(points, 70, FinalInterval([512, 512, 512]))
imp = showStack(rai, title="test virtualPointsRAI")